- Home /
Accessing other script variables error
I am trying to have a script check if a variable is not equal to 0 in another script. This the error I'm getting:
NullReferenceException: Object reference not set to an instance of an object EnemyAI.Update () (at Assets/Scripts/EnemyAI.cs:20)
Code accessing other code:
void OnTriggerEnter2D(Collider2D col){
if (col.gameObject.tag == "Bullet") {
var move = gameObject.GetComponent<MoveTrail>();
if(move.moveSpeed != 0){
air = air - 10;
}
}
}
Script MoveTrail's moveSpeed is an int.
i am not sure. but i think you are trying to access variable of a c-sharp script from your javascript file. I mean, scripting language of both your scripts are different.
Answer by Eric5h5 · Nov 28, 2014 at 05:12 AM
You neglected to say what line the error occurred on, but I assume it's "if(move.moveSpeed != 0){". That means the "move" variable is null, since evidently there is no MoveTrail component attached to gameObject. I'd recommend getting in the habit if checking whether variables are null before attempting to use them.
Does the $$anonymous$$oveTrail script have to be part of the same GameObject, or are they able to be part of two different gameObjects? And the error occurred while the game was running.
since you are writing "gameObject.GetComponent();", $$anonymous$$oveTrail must be on your gameObject. If you want to access the $$anonymous$$oveTrail from another game object in scene then try, "GameObject.FindGameObjectWithTag("Tag Of other game object").GetComponenent()"
Yes, the error occurred while the game was running, but you didn't say which line of code. ;) The error says line 20, but you don't have 20 lines in your question. The $$anonymous$$oveTrail script has to be attached to gameObject, since you're doing gameObject.GetComponent. $$anonymous$$aybe you meant col.gameObject.GetComponent.
Your answer
![](https://koobas.hobune.stream/wayback/20220613172626im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Accessing variable from a method in another script and gameObject 2 Answers
Can I access variables of scripts that inherit from abstract classes? 2 Answers
How to access variable from other class? 1 Answer
string + int = variable 2 Answers
how to acess Static variable in other scripts without extended functions? 2 Answers