Data transfer across scenes and more

Hello Unity community, I am stuck in a tricky situation and need your help (as usual :smile: )

I’ve 2 scenes - Scene 1 & Scene 2. In scene 1, I am having a script ‘first’ that says

using UnityEngine;
using System.Collections;

public class first : MonoBehaviour {
    public static int health;
 void Update()
{
   Debug.Log("some value "+health);

}
}

Now what I want is this: I want to start scene 2 from scene 1 - and then in scene 2 I want to do some changes to ‘health’ from another script like say

using UnityEngine;
using System.Collections;

public class second : MonoBehaviour {
 int t=0;
 void Update()
{
   while(t<10)
{
  first.health++;
t++;

}

}
}

After this, I want to resume scene 1 from the point where I left it. And I want my ‘health’ variable to have the new value i.e 9.

What I thought of:

Using an autosave of Scene 1, before starting scene 2, then reloading the autosave of scene 1 after ending scene 2, but then the problem is that probably, the value of ‘health’ variable would be restored back to what it was during saving, and all changes done to it in scene 2 would get discarded.

Will the changes done to a global variable, (like ‘health’ is) in a scene get discarded once the scene ends?

What would be the ‘simplest’ way to get going? I’ve no idea about this. Someone mentioned about PlayerPrefs, but then again, I haven’t really used this in the past, so totally blank about that either.

the script which holds the var in question needs a DontDestroyOnLoad… the manipulation script at the start of screen 2 can then get a reference to that script to alter it as needed.

1 Like

how exactly do you call that function on a script? that function works for gameobjects if am not wrong…

Add the script to a GameObject, then call DontDestroyOnLoad(nameOfGameObject).

1 Like

thanks I’ll try it out