- Home /
how do i fill an array with an objects children?
im struggling to get running code that will take all the children of an object and change a variable
example code:
var master : Transform;// has a few wheelcollider children
var power : float = 1.0;
private var wheelsArray : Component[];
function start() {
wheelsArray = master.GetComponentsInChildren(WheelCollider) ;
}
function Update () {
for(var wheel : WheelCollider in wheelsArray){
wheel.motorTorque = power ;
};
}
produces a NullReferenceException
cutting out the array stuff and executing
for(var wheel : WheelCollider in master){
wheel.motorTorque = power ;
};
produces MissingReferenceException: The variable master of 'testScript' doesn't exist anymore.
setting the master vars type as a Component or GameObject causes slightly different errors like ApplicationException: Argument is not enumerable
what am i misunderstanding? why would the variable cease to exist?
To start with your Start function is called start and isn't being called - it needs that capital S
it's pretty easy code, have a look at lots of examples from the questions and you will figure it out-you can print the component transform of different elements of the array to make sure they are filled,and you can do for(arrwheel in arrwheels){
Answer by dscroggi · Oct 26, 2012 at 06:52 AM
Try setting wheelsArray to an array of WheelCollider[]
and call GetComponentsInChildren(WheelCollider) as WheelCollider[]
The computer forgets it's a WheelCollider when it downcasts to Component. It's thinking, 'Wait a minute, there's no WheelColliders in this array, only Components!'
Alternatively I think you could cast it back up to a WheelCollider before using it in the foreach loop.
Hope that helps.
turns out the first snippet of code i wrote works in a fresh scene, also found that not specifying wheelsarray type mysterious works around all the errors
thanks for the explanation of the casting errors though, ill keep that in $$anonymous$$d