我有以下创建主菜单的代码:
public class EscapeGUI : MonoBehaviour {
public GUISkin MySkin;
public bool pauseToggle = false;
public bool showGUI = false;
public bool levelLoaded = false;
static string filePath;
private List<string> list = new List<string>();
private string line;
void Update() {
if (!levelLoaded) {
showGUI = true;
Time.timeScale = 0;
Debug.Log ("NO LEVEL LOADED");
} else {
if (Input.GetKeyDown (KeyCode.Escape)) {
pauseToggle = !pauseToggle;
if (pauseToggle) {
Time.timeScale = 0;
showGUI = true;
} else {
Time.timeScale = 1;
showGUI = false;
}
}
Debug.Log("FILEPATH IS " + filePath);
Debug.Log("LEVEL IS LOADED");
}
}
void OnGUI() {
if (showGUI) {
GUI.skin = MySkin;
GUILayout.BeginArea (new Rect (Screen.width / 4, Screen.height / 4, 400, Screen.width / 2));
GUILayout.BeginHorizontal ();
if (levelLoaded){
if (GUILayout.Button ("Resume")) {
Time.timeScale = 1;
showGUI = false;
pauseToggle = false;
}
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (levelLoaded){
if (GUILayout.Button ("Restart")) {
Application.LoadLevel (0);
showGUI = false;
pauseToggle = false;
Time.timeScale = 1;
levelLoaded = true;
Debug.Log ("Game is restarted with this level: " + filePath);
}
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Load")) {
filePath = EditorUtility.OpenFilePanel("Select JSON file",Application.streamingAssetsPath,"txt");
Debug.Log ("Game is loaded with this level: " + filePath);
StreamReader reader = new StreamReader(filePath);
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
//Debug.Log(line);
}
//Do this as soon as the JSON is checked and found to be OK.
GameObject.Find("Preserved Variables").SendMessage("setFilePath", filePath);
Time.timeScale = 1;
levelLoaded = true;
showGUI = false;
pauseToggle = false;
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Quit")) {
Application.Quit();
}
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
}
}
}
游戏是通过导入一个 JSON 文件创建的(在代码中它只是 txt 用于测试,我还没有实现 JSON 部分),在这个 JSON 文件中将描述游戏流程。
所以基本上当玩家点击加载时,我希望游戏可以玩,然后当他点击重新启动时,因为“Application.LoadLevel (0);” 代码所有内容都被删除,因此我不再知道当前文件(级别)是什么。
所以我创建了一个名为“保留变量”的空游戏对象,并在其中放置了一个 C# 脚本组件,脚本如下所示:
public class PreservedVariables : MonoBehaviour {
public string filePath;
public static PreservedVariables instance;
void Awake() {
if(instance){
Destroy(this);
} else {
DontDestroyOnLoad(this);
instance = this;
}
}
void setFilePath(string fp) {
filePath = fp;
}
string getFilePath() {
return filePath;
}
}
现在的问题是,当我运行它并进入游戏时,我单击“加载”,我选择了我的文件,到目前为止一切都很好。但是当我点击“重启”时,我遇到了以下两个问题:
1)主菜单只显示“加载”和“退出”,因为它只应该在没有加载游戏时显示(所以这只发生在启动时),但我认为这将通过修复 nr.2 来解决(见下文)
2)一旦我在加载文件后单击重新启动,游戏对象“保留变量”就会再次创建,但这次它没有附加脚本组件。(虽然原始游戏对象的 FilePath 已正确更新)。
如果我想问一个额外的小问题,我如何从空的游戏对象“保留变量”中再次准确地检索文件路径变量,以便我可以在我的重新启动代码中使用它?