C#从零开始学习(用户界面)(unity Lab4)

这是书本中第四个unity Lab

在这次实验中,将学习如何搭建一个开始界面

分数系统

点击球,会增加分数

csharp 复制代码
    public void ClickOnBall()
    {
        Score++;
    }

在OneBallBehaviour类添加下列方法

csharp 复制代码
    void OnMouseDown()
    {
        GameController controller = Camera.main.GetComponent<GameController>();
        controller.ClickOnBall();
        Destroy(gameObject);
    }

GameController

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameController : MonoBehaviour
{
    public GameObject OneBallPrefab;
    public int Score = 0;
    public bool GameOver = true;

    public int numberOfBalls = 0;
    public int MaximumBalls = 15;

    public Text ScoreText;
    public Button PlayAgainButton;
    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("AddBall", 1.5F, 1);
    }
    public void ClickOnBall()
    {
        Score++;
        numberOfBalls--;
    }
    // Update is called once per frame
    void Update()
    {
        ScoreText.text = Score.ToString();
    }
    void AddBall()
    {
        if (!GameOver)
        {
            Instantiate(OneBallPrefab);
            numberOfBalls++;
            if (numberOfBalls >= MaximumBalls)
            {
                GameOver = true;
                PlayAgainButton.gameObject.SetActive(true);
            }
        }

    }
    public void StartGame()
    {
        foreach (GameObject ball in GameObject.FindGameObjectsWithTag("GameController"))
        {
            Destroy(ball);
        }
        PlayAgainButton.gameObject.SetActive(false);
        Score = 0;
        numberOfBalls = 0;
        GameOver = false;
    }
}

给游戏增加界面

增加界面

在UI中显示分数

点击Hierarchy中的text,在inspector窗口下修改

增加按钮调用

设置好后,将这些绑定

相关推荐
是一个Bug14 小时前
Agent(智能体)应用 的入门学习路径
学习·机器学习
2301_8090511414 小时前
Linux 网络编程 学习笔记
linux·网络·学习
eggcode15 小时前
【Qt学习】Linux(ARM架构)在线安装Qt6.x
linux·qt·学习·arm
xiaoshuaishuai816 小时前
C# 内存管理与资源泄漏
开发语言·c#
_李小白17 小时前
【android opencv学习笔记】Day 26: 滤波算法之低通滤波与图像缩放插值
android·opencv·学习
Bechamz17 小时前
大数据开发学习Day43
大数据·学习
Ulyanov19 小时前
用声明式语法重新定义Python桌面UI:QML+PySide6现代开发入门(一)
开发语言·python·算法·ui·系统仿真·雷达电子对抗仿真
z落落20 小时前
C#参数区别
java·算法·c#
影寂ldy20 小时前
C#随机数
开发语言·c#