Search Unity

Global Variable - Load Level and access an Variable of other Class

Discussion in 'Scripting' started by SteelDragonBR, Mar 31, 2015.

  1. SteelDragonBR

    SteelDragonBR

    Joined:
    Mar 24, 2015
    Posts:
    18
    Hello,

    I Need change value in an variable and access this in the new Scene Load. I try access the variable, or the method, but anyway don't work.

    I need change and get the musicChoose value in other Class/Scene.

    //Song Menu
    public class SongMenu : MonoBehaviour {

    public Canvas songButton;
    public int musicChoose = 1;

    voidStart ()
    {

    songButton = songButton.GetComponent<Canvas> ();

    }

    void SongButton()
    {
    musicChoose = 3;
    Application.LoadLevel (2);

    }

    public int GetMusic()
    {

    return musicChoose;
    }

    //GamePlay Class/Scene
    public class Gameplay : MonoBehaviour
    {
    private SongMenu MusicChoose;
    public int Music;

    void Start()
    {
    MusicChoose = GetComponent<SongMenu> ();
    Music = MusicChoose.GetMusic ();
    //MusicIndex = GetComponent<SongMenu>().musicChoose; //Fail
    //Music = MusicIndex; // Fail
    NowPlaying (Music); // int method
    }
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    You either need to make the object persistent across scenes, by using DontDestroyOnLoad, or else you need to save the value of the variable somewhere and retrieve it in the next scene, using PlayerPrefs or something similar.
     
    SteelDragonBR likes this.
  3. SteelDragonBR

    SteelDragonBR

    Joined:
    Mar 24, 2015
    Posts:
    18
    Thank you very much! Save my time! PlayerPrefs works very well!