-1
\$\begingroup\$

I have variable that I need to save and load between 2 scenes.

So this is what I'm trying:

First script:

public class s1sc : MonoBehaviour 
{
public string playername;

public static s1sc Instance;

void Awake ()   
{
    if (Instance == null)
    {
        DontDestroyOnLoad(gameObject);
        Instance = this;
    }
    else if (Instance != this)
    {
        Destroy (gameObject);
    }
 }

Second script:

public class s2sc : MonoBehaviour 
{
    public string pn;

    void Start () 
    {       
        pn = s1sc.Instance.playername;
    }
}

And it doesn't work fine. What is the problem??

\$\endgroup\$
1
  • 1
    \$\begingroup\$ what's happening now with the setup? \$\endgroup\$ Commented Aug 12, 2016 at 8:42

2 Answers 2

3
\$\begingroup\$

This is what I do to retain variables between scenes. Create a static class that is not derived by Monobehaviour:

public static class ApplicationData {
    public static string PlayerName;
}

Then use it in your Monobehaviour scrips like so:

ApplicationData.PlayerName = "Frank";

This PlayerName variable will persist until you close your application. It will be accessible from all MonoBehaviour scripts.

\$\endgroup\$
1
  • \$\begingroup\$ thank's. it work fine when i need to load variable from "ApplicationData" class. but how can i edit "PlayerName" variable from "Monobehaviour" classes ?? \$\endgroup\$
    – mmoj
    Commented Aug 14, 2016 at 9:33
-1
\$\begingroup\$

You can simply use an empty game object with your desired script and this code, at the least:

void Awake() 
{
    Debug.Log("DontDestory Script's Awake");
    DontDestroyOnLoad(this);
}

The script with variable values will be maintain across different scenes. I just confirmed the below code with Scene1 and Scene2:

using UnityEngine;
using System.Collections;

public class DontDestroy : MonoBehaviour
{

    public int testingInt = 10;

    void Reset()
    {
        Debug.Log("DontDestroy Script's Reset");
    }

    void Awake() 
    {
        Debug.Log("DontDestory Script's Awake");
        DontDestroyOnLoad(this);
    }


    void OnGUI() 
    {
        if (GUI.Button(new Rect(10,10,100,50),"increment :"+ testingInt))
        {
            testingInt++;
        }
        if (GUI.Button(new Rect(10,60, 100, 50), "Load second "))
        {
            Application.LoadLevel("Scene2");
        }
    }
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .