Mus*_*car 8 c# dialog unity-game-engine
我想使用对话框(有两个选项).
我尝试过UnityEditor,但是当我构建项目来创建一个exe文件时,它没有用,因为具有UnityEditor引用的脚本只是在编辑模式下工作.在互联网上搜索了几个小时后,有两个建议(两个都没有用).
第一个:#if UNITY_EDITOR在代码之前使用并以#endif.结尾.在这种情况下,它是在没有错误的情况下构建的,但我的游戏中根本没有对话框.
第二个:将脚本放在Assets/Editor目录下.在这种情况下,我无法将脚本添加到我的游戏对象中.也许,在Editor目录下创建一个新脚本并粘贴UnityEditor中使用的行可以工作,但我无法弄清楚如何做到这一点.
我用了:
#if UNITY_EDITOR
if (UnityEditor.EditorUtility.DisplayDialog("Game Over", "Again?", "Restart", "Exit"))
{
Application.LoadLevel (0);
}
else
{
Application.Quit();
}
#endif
Run Code Online (Sandbox Code Playgroud)
我还尝试添加"使用UnityEditor;"并使用我提到的预处理器命令封装它.它也没用.
有没有人知道如何在运行模式下使用UnityEditor或如何以不同的方式创建对话框?
小智 7
如果我理解正确,你需要一个弹出窗口,当角色死亡(或玩家失败).UnityEditor类用于扩展编辑器,但在您的情况下,您需要一个游戏解决方案.这可以用gui窗户来实现.
这是c#中的一个简短脚本,可以解决这个问题.
using UnityEngine;
using System.Collections;
public class GameMenu : MonoBehaviour
{
// 200x300 px window will apear in the center of the screen.
private Rect windowRect = new Rect ((Screen.width - 200)/2, (Screen.height - 300)/2, 200, 300);
// Only show it if needed.
private bool show = false;
void OnGUI ()
{
if(show)
windowRect = GUI.Window (0, windowRect, DialogWindow, "Game Over");
}
// This is the actual window.
void DialogWindow (int windowID)
{
float y = 20;
GUI.Label(new Rect(5,y, windowRect.width, 20), "Again?");
if(GUI.Button(new Rect(5,y, windowRect.width - 10, 20), "Restart"))
{
Application.LoadLevel (0);
show = false;
}
if(GUI.Button(new Rect(5,y, windowRect.width - 10, 20), "Exit"))
{
Application.Quit();
show = false;
}
}
// To open the dialogue from outside of the script.
public void Open()
{
show = true;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将此类添加到任何游戏对象中,并调用其Open mehtod打开对话框.
例子:
using UnityEngine;
using System.Collections;
public class GUITest : MonoBehaviour {
private Rect windowRect = new Rect (20, 20, 120, 50);
void OnGUI () {
windowRect = GUI.Window (0, windowRect, WindowFunction, "My Window");
}
void WindowFunction (int windowID) {
// Draw any Controls inside the window here
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以在相机的中心显示一个带纹理的平面。