【问题标题】:Unity/C#: On/Off Music GUI ButtonUnity/C#:开/关音乐 GUI 按钮
【发布时间】:2016-05-15 18:27:37
【问题描述】:

几乎 90% 的时间,我的问题已经在这里解决了。不过今天是我第一次问。

我正在开发一个小型的飞扬小鸟克隆,作为一项编程挑战。我之前从未使用过 C# 或 Unity...

我有一个想要“切换”的开/关按钮。到目前为止,我有这个。除了再次显示“musicOn”纹理并再次播放音乐的部分外,它可以正常工作。

这里有什么问题?提前谢谢你。

void OnGUI(){

    toggleMusicButton();

    if(GUI.Button(rect,"", new GUIStyle())){
        music.Pause();
        musicBool = false;
    } 

    if(GUI.Button(rect,"", new GUIStyle())){
        music.Play();
        musicBool = true;
    }

}

void toggleMusicButton(){

    if(musicBool){
        GUI.DrawTexture(rect, musicOn);
    } else {
        GUI.DrawTexture(rect, musicOff);
    }

}

【问题讨论】:

  • 为什么要创建两个 GUI 按钮?
  • 我刚开始使用 C#/Unity。我有点了解事情的运作方式。我的错。

标签: c# unity3d


【解决方案1】:

我没有时间测试,但我相信这是因为您在 OnGUI 之外的另一个方法中进行 GUI 调用。我认为 OnGUI 调用很昂贵,所以越少越好。

private Texture musicTexture;    

void OnGUI(){

    GUI.DrawTexture(rect, musicTexture);


    if(GUI.Button(rect,"", new GUIStyle())){
        if (musicBool) {
            music.Pause();
            musicBool = false;
            musicTexture = musicOff
        }
        else {
            music.Play();
            musicBool = true;
            musicTexture = musicOn
        }
    } 
}

如果您使用 DrawTexture 只是为了更改按钮的外观,请执行以下操作。

创建 2 个 GUIStyles 并为您的按钮设置正确的纹理

public GUIStyle musicOff; //assign a GUIStyle with the correct button image for off
private GUIStyle musicOn; //assign a GUIStyle with the correct button image for on
private GUIStyle musicGUIStyle; //holds GUIStyle being displayed. Assign this a default

void OnGUI(){

    if(GUI.Button(rect,"", musicGUIStyle)){
        if (musicBool) {
            music.Pause();
            musicBool = false;
            musicGUIStyle = musicOff;
        }
        else {
            music.Play();
            musicBool = true;
            musicGUIStyle = musicOn;
        }
    } 
}

【讨论】:

  • 效果很好。我喜欢这个网站社区。我一有声望就会投赞成票。
  • 如果允许,也请标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多