- Home /
How to select BoxColliders of children and disable them?
Hello.
I'm trying to make my project recognize the Box Colliders of all of its children and enable them during the specific steps of a walking animation for one second, then disable them again, but Unity cannot find what I'm asking of it (NullReferenceException). Granted, the sound works perfectly fine during the trigger, unless the player/ camera happens to be facing away from what's walking; but it cannot find the colliders at all.
Here's the erroneous code I have. It's simple, but I'm new as well:
var audioVolume = 1.0;
var collisionSoundEffect : AudioClip;
function playSound() {
audio.volume = audioVolume;
audio.clip = collisionSoundEffect;
audio.Play();
gameObject.GetComponentsInChildren(BoxCollider).collider.enabled = true;
yield WaitForSeconds(1);
gameObject.GetComponentsInChildren(BoxCollider).collider.enabled = false;
}
Answer by idunlop_oefun · Dec 11, 2012 at 01:31 AM
I don't fully understand javascript syntax (I use c#), however
GetComponentsInChildren
returns an array of BoxCollider(s). So ideally you want to store that array in a variable then loop through each BoxCollider and enable / disable it.
I'm guessing the exception is due to you trying to access the 'collider' property on an array (which doesn't exist).
One other thought is that your collider is not on the child, so perhaps you just want to use GetComponent instead of GetComponentsInChildren.
Well, the script is on the highest parent object, but the box colliders (there's four of them) are much deeper within. So I was trying to have that script, when it triggers while the walking animation is playing, to both play a sound effect and also enable those box colliders for one second and then disable them. Unfortunately, I don't really know how to make arrays or variables.
There are likely dozens of resources on this site and others that will tell you how to declare arrays using javascript.
The syntax in c# is:
GameObject [] objs = gameObject.GetGomponentsInChildren(); foreach(GameObject obj in objs) { if (obj.collider != null) { obj.collider.enabled = true; } }
Considering how much of a n00b I am with Unity... is it possible to make C# scripts? If not, I'd hafta find a way to make that into Javascript. x.x
I get this error when using that:
Assets/HitSwitch.cs(8,41): error CS1061: Type UnityEngine.GameObject' does not contain a definition for
GetGomponentsInChildren' and no extension method GetGomponentsInChildren' of type
UnityEngine.GameObject' could be found (are you missing a using directive or an assembly reference?)
BoxCollider [] colls = mygameobject.GetComponentsInChildren< BoxCollider>();
This is an issue with the comment / html. See the missing part? Remove the 'space' character immediately after the left arrow.