1
\$\begingroup\$

Sorry for asking a noob question, but I have never used c# in Unity, only unityscript.

Basically I have a public int score variable stored in Players Class.

I need to retrieve it in the following method:

void OnTriggerEnter(Collider c)
{
    if(c.tag == "PlayerCollision")
    {
        if(!c.gameObject.transform.parent.gameObject.GetComponent<Player>().isDead)
        {
            Debug.Log("Hit");
            //Load next scene
        }
    }
}

How can I retrieve the score variable in this method below and send the variable to the next scene? (In unity script I had to do something like Application.LoadLevel(1); after of course building the scene as levels. Thanks

\$\endgroup\$
1
  • \$\begingroup\$ It looks like you already got useful answers to your question, but just want to clarify one thing you seem to be misunderstanding: Application.LoadLevel() is the same command regardless of programming language, and that command has nothing to do with persisting variables between scenes, that is the command to change scenes. \$\endgroup\$
    – jhocking
    Commented Jan 22, 2014 at 20:34

2 Answers 2

0
\$\begingroup\$

I think the simplest way would be to make the variable static. Eg.

public static int score

Then you could access it any time using Players.score. There are other approaches such as singletons, but I think that would be overkill.

If you have several variables like this, you could decouple them into a helper class and access them all from there.

\$\endgroup\$
1
\$\begingroup\$

Set the script to an object and set this in the script:

void Awake () { DontDestroyOnLoad (transform.gameObject); }

Your object pass all scenes and you can give their variables these values you need in the other scenes.

\$\endgroup\$

You must log in to answer this question.

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