Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Data transfer across scenes and more

Discussion in 'Scripting' started by Soumikbhat, Jul 31, 2014.

  1. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110
    Hello Unity community, I am stuck in a tricky situation and need your help (as usual :D )

    I've 2 scenes - Scene 1 & Scene 2. In scene 1, I am having a script 'first' that says
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class first : MonoBehaviour {
    5.     public static int health;
    6.  void Update()
    7. {
    8.    Debug.Log("some value "+health);
    9.  
    10. }
    11. }
    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

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class second : MonoBehaviour {
    5.  int t=0;
    6.  void Update()
    7. {
    8.    while(t<10)
    9. {
    10.   first.health++;
    11. t++;
    12.  
    13. }
    14.  
    15. }
    16. }

    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.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Soumikbhat likes this.
  3. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110
    how exactly do you call that function on a script? that function works for gameobjects if am not wrong...
     
  4. Philip-Rowlands

    Philip-Rowlands

    Joined:
    May 13, 2013
    Posts:
    353
    Add the script to a GameObject, then call DontDestroyOnLoad(nameOfGameObject).
     
    Soumikbhat likes this.
  5. Soumikbhat

    Soumikbhat

    Joined:
    Nov 23, 2013
    Posts:
    110
    thanks I'll try it out