How to access a variable from another C# script in Unity
Hi Everyone ,
I am working on a simple game project, and have a problem. The problem is accessing the variable from one script to another.
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.
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
{
public 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 ?
Regards :-)
you need to find the game object containing the other script and then get a reference to it using GetComponent()
Answer by LazyElephant · Jan 10, 2016 at 07:45 AM
You can find two ways to do it explained here: http://blog.christianhenschel.com/2013/05/16/how-to-pass-data-between-scenes-static-variables/
The second option he explains would probably be the easiest for your situation. By making the Score variable static, it wouldn't be reset on a new scene load, so as long as you have a Game_Scene_Script in your Game Over Scene, you could access the score.
This means you will have to remember to reset the score yourself. Also, in the event you need more than one of these scripts running, the Score variable will be shared between all instances of the script.