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窗口下修改

增加按钮调用

设置好后,将这些绑定

相关推荐
必胜的思想钢印3 小时前
修改主频&睡眠模式&停机模式&待机模式
笔记·stm32·单片机·嵌入式硬件·学习
hez20104 小时前
TypedSql:在 C# 类型系统上实现一个 SQL 查询引擎
c#·.net·.net core·compiler
世洋Blog5 小时前
利用<<左移运算符优雅的设计游戏能力的任意组合和判断
游戏·unity·c#
曹牧5 小时前
C#中,#region和#endregion
开发语言·c#
czhc11400756636 小时前
c# 1121 构造方法
java·javascript·c#
brave and determined6 小时前
可编程逻辑器件学习(day30):数字电路设计中的流水线技术:原理、实现与优化
学习·fpga开发·verilog·fpga·数字电路·硬件设计·嵌入式设计
Radan小哥6 小时前
Docker学习笔记—day007
笔记·学习·docker
PyAIGCMaster7 小时前
如何编译一个apk,我是新手
深度学习·学习
在路上看风景8 小时前
2.3 C#装箱和拆箱
开发语言·c#
立志成为大牛的小牛8 小时前
数据结构——四十四、平衡二叉树的删除操作(王道408)
数据结构·学习·程序人生·考研·算法