-1
\$\begingroup\$

This question already has an answer here:

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\$

marked as duplicate by Vaillancourt, MrCranky, Almo, Seth Battin, DMGregory Sep 7 '16 at 0:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    \$\begingroup\$ what's happening now with the setup? \$\endgroup\$ – Sourav Paul Aug 12 '16 at 8:42
4
\$\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\$
  • \$\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 Aug 14 '16 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 or ask your own question.