- Home /
Modifying components of an array
(Just registered here(well, a while back but haven't really been on lately...) so sorry if this is the wrong section or something, didn't undrestand the thing with "Default Space"....) Hi everyone! I've been trying to use arrays to be more organized in my code, but there are some problems I've run into, most notably I'm not sure how I can modify the components of arrays. This is a snippet of my code:
var bones : Transform[];
var isRagdoll = false;
function Update () {
if(!isRagdoll){
bones.rigidbody.isKinematic = true;
}else{
bones.rigidbody.isKinematic = false;
}
}
However, when I do this, my whole script stops working and I get the error "Object Reference not set to an instance of an object" I've checked that every single one of the gameobjects in my array has the component Rigidbody, and they do, but this still won't work. Any ideas? Thanks in advance
Answer by syclamoth · Mar 20, 2012 at 07:02 AM
Well, an array of Transforms (which is what 'bones' is) doesn't have a 'rigidbody' property- that's something that only the individual members of the array have!
The problem is that you are trying to modify all the values in a single step, which doesn't really make sense. Thankfully, there exists control flow statements for iterating through a group like that:
for(var bone : Transform in bones)
{
if(!isRagdoll){
bone.rigidbody.isKinematic = true;
}else{
bone.rigidbody.isKinematic = false;
}
}
This assigns each element in turn to the name 'bone', where it can be operated upon individually.
Thank you! That did exactly what I needed :D $$anonymous$$y previous approach was to make all the transform variables seperately, but I thought that would work slowly in code.
Well, it would work just as fast, but it's a really inefficient solution from a coding standpoint.