- Home /
Script not changing int variable
I am trying to make it so when an enemy touches you the player, and an integer on another script equals 0, the integer switches to a 1. Problem is that the int is not changing.
The Int script:
[System.Serializable]
public class SaveFile {
public int Respawn;
}
The enemy script:
public int Scene;
public Transform target;
NavMeshAgent agent;
public SaveFile respawn;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update () {
agent.SetDestination(target.position);
}
public void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
{
if(respawn.Respawn == 0)
{
respawn.Respawn = 1;
SceneManager.LoadScene(Scene);
}
if (respawn.Respawn == 1)
{
SceneManager.LoadScene(Scene);
respawn.Respawn = 2;
}
if (respawn.Respawn == 2)
{
SceneManager.LoadScene(Scene);
respawn.Respawn = 3;
}
}
}
Answer by Sabre-Runner · Dec 14, 2018 at 04:16 AM
When you load the scene, any previous runtime data is destroyed. Even monobehaviours on gameobjects are destroyed so there will be nothing to save on.
If you want to save data between scene reloads you should use an object with DontDestroyOnLoad, a ScriptableObject, PlayerPrefs, or save it to file somewhere.
I added this to the script the script and have it initialized in void Start however it still doesn't work.
public void SaveSettings()
{
string jsonData = JsonUtility.ToJson(respawn, true);
File.WriteAllText(Application.persistentDataPath + "/SaveFile.json", jsonData);
}
public void LoadSettings()
{
if (File.Exists(Application.persistentDataPath + "/SaveFile.json") == true)
{
File.ReadAllText(Application.persistentDataPath + "/SaveFile.json");
respawn = JsonUtility.FromJson<SaveFile>(File.ReadAllText(Application.persistentDataPath + "/SaveFile.json"));
}
else
{
Debug.LogError("Cannot load game data");
}
}
Explain. How are you using this? Where? When? Did you check that all the data is serialized and deserialized correctly? Because you are not using just primitives there.
Well, I removed the SaveSettings and LoadSettings and I replaced it with PlayerPrefs. In the save file I added a PlayerPrefs.SetInt and in the enemy script when it's checking in the int is 0 or 1 I changed it to if(PlayerPrefs.GetInt == 1) and now it works.
Answer by Vega4Life · Dec 14, 2018 at 03:26 AM
A scene load would cause it to reset. Is that intentional?
Your answer
Follow this Question
Related Questions
Issue with PlayerPrefs not loading a value, as well as a bug... 1 Answer
How do I increase an integer?? 3 Answers
Damage script not changing enemy's health integer 1 Answer
How do I create a save scene feature though int value in c# 2 Answers
How to i set the int to hitpoints / 10 + the current int. 1 Answer