将图像插入GUI按钮

时间:2015-07-22 13:16:14

标签: c# unity3d

我可以创建一个包含文本的按钮,如代码注释中所示。但我不确定为什么当我尝试添加图像时它不接受它。我想可能是因为我使用的CustomGUISkin可能会覆盖它?但我不确定。关于我做错了什么或是他们更简单的方法的任何想法? 我使用Unity和c#作为我的脚本语言。

using UnityEngine;
using System.Collections;

public class PracticeButton : MonoBehaviour {

    public GUISkin CustomGuiSkin;

    private float x; 
    private float y; 
    private float z; 
    private float p;

    // here
    GUIContent content = new GUIContent();
    public Texture2D image;

    // Use this for initialization
    void Start () {

        x = 0.5f * Screen.width;
        y = 0.625f * Screen.height;
        z = 0.5f * Screen.width;
        p = 0.125f * Screen.height;
    }

    // Update is called once per frame
    void Update () {
    }

    void OnGUI () {

        GUI.skin = CustomGuiSkin;

        // here
        GUI.skin.button.normal.background = (Texture2D)content.image;

        if(GUI.Button(new Rect(x, y, z, p), content, CustomGuiSkin.button )){ // replace content with "this" and this will show
            Application.LoadLevel("PracticeScene");
            DeathOnImpact.dead = false;
            Score.myScore = 0;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您想将图片添加为内容/标签,这可能会有所帮助

http://docs.unity3d.com/ScriptReference/GUIContent-image.html

如果您想要一个样式,请删除此行GUI.skin.button.normal.background = (Texture2D)content.image;public Texture2D image;,并在检查器/编辑器上的自定义外观中创建一个custo样式或更改按钮默认样式。

如果您在CustomGuiSkin中将按钮样式创建为自定义样式,则需要将此CustomGuiSkin.button更改为包含自定义样式名称的字符串"myButtonStyle"

if(GUI.Button(new Rect(x, y, z, p), content, "myButtonStyle" )){ 
    // content
}

如果您从CustomGuiSkin更改标准按钮样式,只需省略按钮声明中的样式,默认情况下,一旦您将当前外观设置为CustomGuiSkin,它就会获得。

if(GUI.Button(new Rect(x, y, z, p), content )){ 
    // content
}

您可以在文档中找到有关使用GUISkins的更多信息:

http://docs.unity3d.com/Manual/class-GUISkin.html

相关问题