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

增加按钮调用

设置好后,将这些绑定

相关推荐
~kiss~2 小时前
A Survey of On-Policy Distillation for LLMs 学习(一)
学习
小杨小杨、努力变强!3 小时前
python学习笔记
笔记·学习
Star(up up up)9 小时前
Redis Windows 安装教程:使用Windows 的 Redis 压缩包
redis·笔记·学习·程序人生·云原生·学习方法·改行学it
乌暮11 小时前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
暴走约伯13 小时前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
xy345316 小时前
Axure 9.0 垂直菜单介绍
ui·产品经理·axure·原型设计
蒸蒸yyyyzwd16 小时前
从邓明学习的后端笔记
笔记·学习
机器学习之心16 小时前
基于变量相关图与残差学习的 GCN 多变量回归方法——混凝土 28 天抗压强度预测
学习·回归·gcn
Rabitebla1 天前
【Linux】进程控制(十二) 自定义 Shell(二):内建命令与进程工作目录管理
linux·c++·笔记·学习·bash
Gary移动存储固件1 天前
eMMC5.1协议中文学习讲解(6.6.17~6.6.22.4.6)
学习·ufs·emmc·nand·存储固件