Accessing A Variable from another script C#
Yes I know this question has been asked many times! But I can't figure it out, I am making a Pong game and I am trying to get it so the user inputs a score limit they want. (called limit)
Then in another script from another scene I say: when Player 1 score is >= limit Change the scene to Player 1 wins (I have got rid of this now while I am testing)
But for some reason when limit is seen in the other script the value resets to 0
And I have done a test to see what is the problem and it is the fact that the variable "limit" isn't being accessed by the other script, the other script just makes a new variable called limit. Any help?
The Image above is where the limit variable is input (from an input field)
This image above is where I am trying to access it from - as you can see with the "Debug.Log(limit)" I am testing to see if if it has the same value that was input and the answer is no
Answer by Menyus777 · Jul 11, 2017 at 10:10 PM
To understand your fault here: Static integer is only points to one place into the memory, so if u have 10 GameObjects with a script that has a static value, all the script will look for one place in the memory, while in normal case all the 10 GameObjects had a unique value.
To access the Static Value, from the CountScore script do the following:
public GameController GameController_Script;
void Start(){
Debug.Log(GameController.limit);//Because of static
}
Sorry late response I didn't get notified, I added this to my CountScore script and got the response: NullReferenceException: Object reference not set to an instance of an object
Because You need to attach that script, from an existing GameObject
Sorry I am new to C# and Unity for that matter, how would I go about doing this? Thanks again
Answer by CyborgX · Aug 03, 2017 at 11:33 AM
Just realised this question has been answered now as I can use the variable in other scripts so thank you all!
Your answer
Follow this Question
Related Questions
Need a variable to exist in the current context - not sure where to start 0 Answers
C# Unity dot syntax exercise correct solution? 1 Answer
[SOLVED]bool is getting reset by no reason 2 Answers
¿How can i add a fixed joint configured by script? 0 Answers
Changing Variable Outside of the Script 0 Answers