0
\$\begingroup\$

I am working on a simple game project, and have a problem. The problem is accessing the variable from one script to another.

For example :-

I have 2 Scenes (Game Scene and Game Over Scene), Game Scene has a Player Game Object , who has a int Variable Score.

using UnityEngine;
using System.Collections;

public class Game_Scene_Script : MonoBehaviour 
{
     private int Score ;

     // Use this for initialization
     void Start () 
     {
          Score = 0 ;
     }

     // Update is called once per frame
     void Update () 
     {
          // Let us assume some one played the game
          // And Now the Score is 207
          Score = 207 ; 
     }
}

Now I want to access that int Variable Score in Game Over Scene which a Game Object.

So how can I access that int Variable from that script?

I searched for, but couldn't find any proper answer I wanted. Even-though some answers are in JavaScript , some are in Unity 4.x etc.

\$\endgroup\$
  • \$\begingroup\$ A Unity 4.x answer still works fine. This part of the fundamentals hasn't changed since Unity was first released. \$\endgroup\$ – jhocking Jan 8 '16 at 15:55
2
\$\begingroup\$

You can't, it's private.

Now, that's not the end of things, as I suspect that wasn't really your question.

Firstly, you need a reference to this script. Which you can get from a reference to the game object this script is attached to. GameObject.Find() works sometimes, I don't recommend it, but none the less, once you have the GameObject reference...

Game_Scene_Script sceneScript = gameObj.GetComponent<Game_Scene_Script>();
int score = sceneScript.GetScore();

Of course, that still means you need to either make the Score public or provide an accessor function, GetScore().

public int GetScore() {
    return Score;
}
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You might want to include a quick implementation of GetScore(). If the public/private paradigm isn't obvious to OP, exposing a private variable with a public function might not be either. \$\endgroup\$ – Foggzie Jan 8 '16 at 16:19
  • \$\begingroup\$ @GuntherFox Good point! I didn't even think about that. \$\endgroup\$ – Draco18s no longer trusts SE Jan 8 '16 at 16:20
  • \$\begingroup\$ Or forget about Java getters and write a C# property instead: public int Score { get { return _score; } } and access it more comfortably int score = sceneScript.Score; \$\endgroup\$ – wondra Jan 8 '16 at 17:21
  • \$\begingroup\$ How you write a getter isn't as important as providing access. ;) \$\endgroup\$ – Draco18s no longer trusts SE Jan 8 '16 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.