- Home /
I can't change a variable that is in another script.
I am trying to change a variable in ballControl.cs called playerScore inside the script enemyControl.cs:
public class enemyControl : MonoBehaviour { public ballControl ball;
void Update()
{
if(transform.position.x < 0)
{
ball.playerScore++; //playerScore is declared in ballControl.cs
}
}
}
When I run the game, I get this error: "NullReferenceException: Object reference not set to an instance of an object enemyControl.Update () (at Assets/enemyControl.cs:16)"
What am I doing wrong?
Answer by Ashish Dwivedi · Feb 12, 2014 at 12:42 PM
First of all you need to find the reference of "ballControl" in your variable "ball" then you can access public members of that class. "ball" is null, firstly assign it. Suppose you are having object "ABC" with script "ballControl" then add this method to your script.
void Start()
{
ball = GameObject.Find("ABC").GetComponent<ballControl>();
}
aah, ok I have assigned it like this:
public class enemyControl : $$anonymous$$onoBehaviour
{
public ballControl ball;
void Start(){
ball = GameObject.Find("Ball").GetComponent<ballControl>();
}
}
I'm still getting the same error though. EDIT: I think I've got it working.
ball = GameObject.Find("Ball").GetComponent<ballControl>();
I moved this line to the same if statement
Just to add to Ashish's answer, it is good practice to first check if a variable is null before trying to read anything from it (looking at your first post). $$anonymous$$ore so, I have been told that using GameObject.Find is computationally expensive. It is something you should leave out of Update() if you can avoid it.
You can drag'n'drop object with ballControl script into specific field in the inspector in the editor when object with enemyControl is in focuse, too.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
Editing a variable from another script on collision 3 Answers
How to not allow ball to be thrown after first Toss 2 Answers