如何在Unity中使用c#让我的按钮做不同的事情
本文关键字:我的 按钮 不同的事 Unity | 更新日期: 2023-09-27 18:06:09
我目前有一些代码,通过数组在屏幕上放置一些按钮,我在检查器中分配纹理。问题是,我不知道如何让按钮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;
}
}
}