c# - 如何让我的按钮在 Unity 中使用 C# 做不同的事情?

标签 c# arrays unity3d

我目前有一些代码可以通过数组在屏幕上放置一些按钮,然后在检查器中分配纹理。问题是我不知道如何让按钮 1 退出游戏,按钮 2 进入下一个级别,按钮 3 加载图像。有人可以向我解释我需要做什么才能使各个按钮在单击时执行不同的操作吗? (第二个数组用于我在屏幕右侧的按钮)

这就是我的代码现在的样子:

using UnityEngine;
using System.Collections;

public class UI : MonoBehaviour
{
    public Texture2D[] parts;
    public Texture2D[] extra;
        int buttonHeight, buttonWidth;
    int x, y;
    int width, height;

    void OnGUI ()
    {
        for (int i = 0; i < parts.Length; ++i) 
        {
            if (GUI.Button (new Rect (x - 35, i * (height + 97), width + 300, height + 90), parts [i]))
            Debug.Log ("Clicked button " + i);
            //if (GUI.Button (new Rect (0, i * (buttonHeight + 20), buttonWidth + 100, buttonHeight + 100), textures [i]))
       }
       for (int x = 0; x < extra.Length; ++x) 
       {
           if (GUI.Button (new Rect (x + 800, x * (height + 140), width + 300, height + 120), extra [x]))

           Debug.Log ("Clicked button " + x);
           if (extra [0] && Input.GetButtonDown ("Jump")) 
           {
               Application.CaptureScreenshot ("Screenshot.png");
               Debug.Log ("Screen captured");
           }
       }
    }
}

最佳答案

像这样的东西会起作用:

using UnityEngine;
using System.Collections;

public class UI : MonoBehaviour {

public Texture2D[] parts;
public Texture2D[] extra;
public string[] actions;
int buttonHeight, buttonWidth;
int x, y;
int width, height;

void OnGUI ()
{
    for (int i = 0; i < parts.Length; ++i) 
    {
        if (GUI.Button (new Rect (x - 35, i * (height + 97), width + 300, height + 90), parts [i]))
            Execute(actions[i]);
        //if (GUI.Button (new Rect (0, i * (buttonHeight + 20), buttonWidth + 100, buttonHeight + 100), textures [i]))
    }
    for (int x = 0; x < extra.Length; ++x) 
    {
        if (GUI.Button (new Rect (x + 800, x * (height + 140), width + 300, height + 120), extra [x]))

            Debug.Log ("Clicked button " + x);
        if (extra [0] && Input.GetButtonDown ("Jump")) 
        {
            Application.CaptureScreenshot ("Screenshot.png");
            Debug.Log ("Screen captured");
        }
    }
}

void Execute(string action) {
    switch (action) {
    case "exit":
        Application.Quit();
        break;
    case "next":
        // Load next level..
        Debug.Log("next");
        break;
    }
}

关于c# - 如何让我的按钮在 Unity 中使用 C# 做不同的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993401/

相关文章:

c# - 如何更改游戏对象的枢轴

c# - DateTime.ToString 格式表达式是否受当前区域性影响?

c# - Wpf 产品在未安装 MS Office 的情况下导出到 Excel

arrays - 来自函数的 Julia count() 结构数组

c# - 我的玩家角色在加载保存位置时掉下盒子

unity3d - 视场棕褐色

c# - 什么是运营商 `|=` ?我如何在 C# 中实现它?

c# - 在 C# 中对小代码示例进行基准测试,可以改进此实现吗?

ios - 如何在 swift 3 中删除数组中的模型类数据?

c++ - 使用 jsoncpp 创建 JSON 字符串数组