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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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:
    897
    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!