-1

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??

Sourav Paul Roman
  • 2,043
  • 2
  • 15
  • 20
mmoj
  • 11
  • 1
  • 6

2 Answers2

3

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.

jgallant
  • 8,414
  • 7
  • 32
  • 46
  • thank's. it work fine when i need to load variable from "ApplicationData" class. but how can i edit "PlayerName" variable from "Monobehaviour" classes ?? – mmoj Aug 14 '16 at 09:33
-1

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");
        }
    }
}
Gnemlock
  • 5,263
  • 5
  • 28
  • 58
Muhammad Faizan Khan
  • 2,020
  • 3
  • 29
  • 66