游戏制作之路(37)显示统计星星的个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caimouse/article/details/85617327

在前面已经实现从开始菜单到进入游戏,也实现了从游戏主循环退出到开始菜单,但是在玩这个游戏时,点击一下就产生一个星星,那么怎么样才能像别的游戏那样实现计分,比如计算有多少个星星,并把它显示在游戏界面上面。这次就来解决这个问题,要想在游戏界面上显示星星的个数,那么就得先在界面上创建一个label,接着问题又来了,怎么样创建这个label呢?

 

要创建这个label,如下图打开StarGame.cs脚本文件:

打开这个脚本之后,在脚本里添加按下面的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StarGame : MonoBehaviour
{
    public GameObject starPrefab;
    public GUISkin skin;

    private Rect btnEndRect;
    private List<GameObject> starList;

    private Rect lbCountRect;

    // Use this for initialization
    void Start()
    {
        btnEndRect = new Rect();
        starList = new List<GameObject>();

        lbCountRect = new Rect();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //
            Vector3 pos = Input.mousePosition;
            pos.x /= Screen.width;
            pos.y /= Screen.height;

            //
            GameObject g = (GameObject)Instantiate(starPrefab, pos, Quaternion.identity);
            starList.Add(g);
        }
    }

    void OnGUI()
    {
        //显示统计星星的个数
        lbCountRect.x = 0;
        lbCountRect.y = Screen.height - 30;
        lbCountRect.width = 100;
        lbCountRect.height = 30;
        
        GUI.Label(lbCountRect, starList.Count.ToString(), skin.label);

        //结束按钮
        btnEndRect.x = 0;
        btnEndRect.y = 0;
        btnEndRect.width = 100;
        btnEndRect.height = 45;
        //
        if (GUI.Button(btnEndRect, "结束", skin.button))
        {
            foreach(GameObject g in starList)
            {
                Destroy(g);
            }
            starList.Clear();
            //
            StartMenu menu = gameObject.GetComponent<StartMenu>();
            menu.enabled = true;
            this.enabled = false;
        }

    }
}

在这段代码里,先定义一个Rect的私有变量lbCountRect,用来保存标签所在的位置,然后在Start()函数初始化变量lbCountRect,在函数OnGUI()增加设置标签的位置,同时GUI.Label把它显示出来。这时点击运行之后可以看到统计星星的个数,如下图:

但是这时可以看到,这个计数显示有点难看,那么就来美化一下吧。由于它是采用skin.label定义的,那么只要设置GUISkin类,就可以改变标签的样式,因此如下图进行编辑:

经过上面修改标签显示的背景图片,同时把字体的对齐方式修改为居中显示,这时再运行游戏,就显示如下:

到这里,就把星星游戏的创建过程完全做完了。在这个过程里,经历界面文本显示、按钮显示、自定义按钮、自定义的界面样式管理、创建星星的预制件、游戏开始菜单、游戏开始菜单切换到游戏循环、退出游戏循环返回开始菜单,把这些学完之后,就可以自己去尝试不同的小游戏开发了。

https://blog.csdn.net/caimouse/article/details/51749579

猜你喜欢

转载自blog.csdn.net/caimouse/article/details/85617327