Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
    
A Unity 4.x answer still works fine. This part of the fundamentals hasn't changed since Unity was first released. – jhocking Jan 8 '16 at 15:55

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;
}
share|improve this answer
1  
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. – Gunther Fox Jan 8 '16 at 16:19
    
@GuntherFox Good point! I didn't even think about that. – Draco18s Jan 8 '16 at 16:20
    
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; – wondra Jan 8 '16 at 17:21
    
How you write a getter isn't as important as providing access. ;) – Draco18s Jan 8 '16 at 17:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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