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’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?
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
}