我有以下代码创建主菜单:
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);'代码Everythings被删除,因此我不知道它当前的文件(级别)是什么。
所以我创建了一个名为'Preserved Variables'的空游戏对象,我在其中放了一个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已正确更新)。
如果我想问一个额外的小问题,我如何从空的游戏对象'Preserved Variables'中再次检索文件路径变量,以便我可以在我的重启代码中使用它?