- Home /
Null Reference exception when calling using "script.gameObject.GetComponent
I'm trying to access the values per se, of a game object that my script is not attached to. I used the script.gameObject.GetComponent() line but it still gives me the same null reference.
Any advice?
I'd advise you to post the script in question.
Additionally, your description is not very clear. If the script is not attached to the game object you want to access, why would script.gameObject access the non-attached game object in question?
I'm trying to access a script from a different game object I'm unsure about how to go about that
Answer by aldonaletto · Oct 21, 2011 at 07:17 PM
To access a script in another GameObject you need a reference to the object. You can assign this reference to a variable at the Inspector, or find it using tag or name, or get it in some functions like OnTriggerEnter, OnCollisionEnter, Raycast and others that return the transform, the collider or any component of the desired GameObject.
To set the reference at the Inspector:
var target: GameObject; // drag the object here in the Inspector
To find it by name:
var target = GameObject.Find("TargetObject");
Or by tag:
var target = GameObject.FindWithTag("Enemy");
Anyway, once you have the reference to the object in some variable, you can access the script using a variable with the script type - which is the name of the script without quotes or extension. If the script is called EnemyControl.js, for instance, you can get a reference to the script using something like this:
var enemyScript: EnemyControl; // declare a variable of the script type
// get the script reference with the object reference and GetComponent
enemyScript = target.GetComponent(EnemyControl);
if (enemyScript){ // check if the object actually has a EnemyControl script
enemyScript.health = 100; // read or assign variables this way
enemyScript.WakeUp(); // or call a EnemyControl function this way
}
I am trying to access the script of enemy just the way you have described. But I am getting Null Reference Exception. I dont get the error always, only sometimes which is making it hard to debug. I cannot drag the enemy object in the inspector because the enemy object is an instantiated prefab. I find the enemy object using GameObject.FindWithTag("Enemy"). From the line number given in error, it looks like the player finds the enemy object but it cannot access the script. Why is this happening?
Your answer
Follow this Question
Related Questions
Null Reference Exception Error. Modified Stats. Need Help. 1 Answer
Null Reference Annoying Error 0 Answers
NullReferenceException - With Network PlayerSpawn 0 Answers
NullReferenceException yet Debug.Log shows nothing is null? 1 Answer
String in array is null when checking length, help bug?! 2 Answers