游戏制作之路(31)创建自定义的按钮

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

在前面学习了怎么样创建按钮,也学习了显示纯文本,不过这些都是使用缺省的模式来显示的,但是游戏开发人员常常使用自定义的按钮比较多,因为它显示多样化,同样可以进行换图美化,也可以符合使用者的个性定义化。因此,这次来学习使用GUIStyle组件来定义按钮的样式。
比如创建如下图的按钮:

这个按钮背景是使用一个蓝色图片,当鼠标在这个按钮上面时,就会显示如下:

这时,就是unity3d根据按钮的模式来切换的。我们只要定义一个GUIStyle,就可以把它使用到N个按钮那里。

要创建这样的按钮,首先要在脚本代码里添加下面的代码:

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

public class SampleMenu : MonoBehaviour {

    public GUIStyle btnStyle;
    private Rect btnRect;

    int count;

	// Use this for initialization
	void Start ()
    {
        count = 0;
        btnRect = new Rect();
    }
	
	// Update is called once per frame
	void Update ()
    {
        
	}

    //界面显示
    private void OnGUI()
    {
        btnRect.x = Screen.width / 3;
        btnRect.y = Screen.height * 2 / 5;
        btnRect.width = Screen.width / 3;
        btnRect.height = Screen.height / 5;

        if (GUI.Button(btnRect, "深圳改革开放", btnStyle))
        {
            print(count);
            count++;
        }
    }
    
}

在这里定义了GUIStyle的对象btnStyle,在函数GUI.Button里第三个参数赋值给按钮对象。有了这个GUIStyle对象,就可以编辑器里进行设置了和定义:

通过这样的方式,就可以自定义不同的按钮进行显示。

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

猜你喜欢

转载自blog.csdn.net/caimouse/article/details/85233005
今日推荐