Unity3D GUI控件创建了两个控件
我有一个代码向用户显示一个是/否的问题,他们是否真的想退出游戏。这是我的代码:Unity3D GUI控件创建了两个控件,unity3d,Unity3d,我有一个代码向用户显示一个是/否的问题,他们是否真的想退出游戏。这是我的代码: using UnityEngine; using System.Collections; public class UserPrompt : MonoBehaviour { public int count = 0; public bool paused = false; public static UserPrompt Instance; // Use this for initialization vo
using UnityEngine;
using System.Collections;
public class UserPrompt : MonoBehaviour {
public int count = 0;
public bool paused = false;
public static UserPrompt Instance;
// Use this for initialization
void Awake ()
{
if (Instance == null)
{
Instance = this;
}
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
paused = true;
count = 1;
}
if(paused)
Time.timeScale = 0;
else
Time.timeScale = 1;
}
void OnGUI ()
{
if(count == 1)
{
GUI.Box(new Rect(0,0,Screen.width,Screen.height),"Exit");
GUI.Label(new Rect(Screen.width*1/4,Screen.height*2/6,Screen.width*2/4,Screen.height*1/6), "Do you really want quit to main menu ?");
if(GUI.Button(new Rect(Screen.width/4,Screen.height*3/8,Screen.width/2,Screen.height/8),"Yes"))
Application.LoadLevel("Menu");
if(GUI.Button(new Rect(Screen.width/4,Screen.height*4/8,Screen.width/2,Screen.height/8),"Keep Playing"))
{
paused = false;
count = 0;
}
}
}
}
问题是我应该点击“继续播放”按钮两次以消失,似乎这段代码创建了两次每个GUI对象,但我看不出有什么问题。
提前感谢检查脚本是否未在2个对象中使用,您也可以通过添加一个标签来检查这一点,该标签将显示this.parent.name,它将显示使用脚本的用户。哇,真是太过分了
如果你对一个更强大的单体组件感兴趣,请考虑这样的事情:
private static UserPrompt _instance;
public static UserPrompt Instance
{
get
{
if (_instance != null)
return _instance;
_instance = (UserPrompt )FindObjectOfType(typeof(UserPrompt));
if (_instance != null)
return _instance;
GameObject newObject = new GameObject();
_instance = newObject.AddComponent<UserPrompt>();
newObject.name = "UserPrompt";
if (_instance == null)
throw new NullReferenceException("Cannot instance UserPrompt");
return _instance;
}
}
如果场景中出现新的UserPrompt,它将检查是否没有活动实例,否则将禁用自身。禁用优先于DestroyImmediate(此),这可能会在编辑器中引发NullReferenceException。当然,您可以选择简单地捕获异常
private void
OnEnable()
{
if (_instance == null || !_instance.enabled)
{
_instance = this;
}
else
{
enabled = false;
}
}
private void
OnDisable()
{
if (this == _instance) _instance = null;
}