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

增加按钮调用

设置好后,将这些绑定

相关推荐
初学者7.7 分钟前
lodash手写源码-cloneDeep,debounce,throttle
笔记·学习·loadsh
m0_7482552638 分钟前
Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)
spring boot·后端·ui
前端 贾公子1 小时前
Vue.js 3 的设计思路:从声明式UI到高效渲染机制
vue.js·flutter·ui
eggcode1 小时前
IDEA与Maven使用-学习记录(持续补充...)
学习·maven·intellij-idea
小码编匠2 小时前
西门子PLC通信掌握这几项技能,效率大幅提升
人工智能·后端·c#
小码编匠2 小时前
.NET 快速开发企业级CMS内容管理系统,告别重复造轮子!
后端·c#·.net
小怪兽长大啦2 小时前
【UI自动化框架第五张】AndroidUiAutomation 类功能简介
运维·ui·自动化
charlie1145141913 小时前
从0开始的操作系统手搓教程33:挂载我们的文件系统
学习·系统架构·操作系统·教程·文件系统·手搓教程
木木黄木木3 小时前
Theos环境搭建与XM文件开发指南,以及iOS弹窗源码分享
ios·c#