- Home /
do something if a method cant be executed
Hi :)
so basically here I don't want my player to load its game if there is no save to load. I'm using simple json to save and load infos about the character.
In my menu I also want a pop up to display whenever a save cant be reached.
Ive tried some do while but as i cant go further than the line where it says "LoadAllInformation()" well I'd like to know if there's a way to check for certain file ? or even if in case of the failure of the execution of a method to execute some code ? thank you !
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class MainMenu : MonoBehaviour
 {
     public GameObject ErrorLoad_Panel;
 
 
     private void Start()
     {
         ErrorLoad_Panel.SetActive(false);
     }
 
     public void PlayGameButton()
     {
         SceneManager.LoadScene("RaceSelection");
     }
 
     public void LoadGameButton()
     {
         GameController.LoadAllInformation();
         SceneManager.LoadScene("MainWorld");
 
         // if cant load then do this
         ErrorLoad_Panel.SetActive(true);
     }
 
     public void QuitGameButton()
     {
         Application.Quit();
     }
 
     public void ErrorLoadButton()
     {
         ErrorLoad_Panel.SetActive(false);
     }
 }
 
               Comment
              
 
               
              Answer by Ymrasu · Feb 19, 2019 at 04:44 PM
You should have your LoadAllInformation() return a bool depending on weather you loaded or not. To determine that, you should usually check if a file exists before trying to read from it. An example:
 public bool LoadGameData()
 {
     string filePath = @"\saves\character.json";
 
     if(File.Exists(filePath))
     {
         string dataAsJson = File.ReadAllText(filePath); 
         GameData loadedData = JsonUtility.FromJson<GameData>(dataAsJson);
     }
     else
     {
         // No save file
         return false;
     }
 
     return true;
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                