Calling Generated Child Object in same script

Hi All!

Using JavaScript, I’m trying to make a variable out of a child object, wich is generated earlier in the script.

var WheelFL = GameObject.WheelFLCollider;

This keeps giving me Nullexceptions, and is obviously not the way to do it. What is the correct way of doing it?

Thanks!!

1 Answer

1

If you want to have a variable referencing an object’s child, you can use Find to get the object by name:

var wheelFL: WheelCollider;
var wheelFR: WheelCollider;

function Start(){
  wheelFL = transform.Find("WheelFL").collider;
  wheelFR = transform.Find("WheelFR").collider;
}

It’s better to do it at Start, since Find is a somewhat slow operation.

Ahhh ok Thanks man! One question though; why do you set the variables before the function?

–

Variables declared inside a function only exist there - they disappear when the function ends. We use to say that they have local scope. Outside the function, the variable has "script scope" (not an "official" term, but very adequated): it exists while the script is alive, and is known by everybody in the script - thus you can use them inside other functions.

–