简体   繁体   中英

How can I disable collisions for all sibling game objects?

I have a spawner which spawns balloons every second. I want to stop these balloons from colliding with other balloons. I can see how you can loop through child objects from a parent, but I don't know how to loop through other child objects that share the same parent. All balloons are spawned in the same parent.

Currently I have this but it obviously doesn't work. I tried transform.parent.transform too but this didn't work either. It only spawns one balloon and the script breaks for "object not set to an instance of an object" on the same line.

var NewBalloon = Instantiate(balloons[0], transform.position, Quaternion.Euler(new Vector3(-90, 0, 0)));
NewBalloon.transform.parent = GameObject.Find("Balloons").transform;

foreach(Transform child in transform.parent)
{
      Physics.IgnoreCollision(NewBalloon.GetComponent<Collider>(), child.GetComponent<Collider>());
}

Not quite the way I intended to do it, but I found that if you go to "Edit" > "Project Settings" > "Physics" (on version 5.5), I could disable the checkbox for balloons / balloons which stops them colliding with each other.

Edit: This seems to be the best way to do it. No need to add scripting for it, and it just works perfectly.

but I don't know how to loop through other child objects that share the same parent.

You don't have to!

This is really easy. Just create a layer and put the balloon prefab in the layer. Let's say Layer 9.

Now, run this in the Awake function to ignore collison between each balloon in that layer:

Physics.IgnoreLayerCollision(9, 9, true);

If you want to recognize collison, run this:

Physics.IgnoreLayerCollision(9, 9, false);

That's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM