- Home /
How to affect multiple rigidbodies with one box collider trigger?
I'm currently trying to make multiple objects change their kinematic status to non-kinematic when the player passes through a box collider trigger. All the pieces have the same tag, including the collider. Does anyone know what I can do?
Here is the block of code so far:
//when car runs into walls/buildings
public void OnTriggerEnter(Collider other)
{
//if our other object is tagged wall
if (other.gameObject.tag == "Wall")
{
//we turn on the kinematic componet of our other object
other.gameObject.GetComponent<Rigidbody>().isKinematic = false;
}
}
Answer by Xamtox · Dec 09, 2019 at 07:16 AM
You need to get a collection of rigidbodies and iterate through them like this:
foreach (var rb in rigidbodies)
rb.isKinematic = false;
or:
for (int i = 0; i < rigidbodies.Count; i++)
rigidbodies[i].isKinematic = false;
So. How'd you get all rigidbodies you need? It depends.
You can store objects you need inside the script via inspector. Write:
[SerializeField] private List<Rigidbody> rigidbodies;
And then drag all rigidbodies you need inside newly created field in inspector.
You can get objects you need during runtime using colliders or physics.
var colliders = Physics.OverlapSphere(...);
returns all colliders inside defined area. Then you can get all tagged objects and select rigidbodies from them:
var rigidbodies = colliders.Where(a=>a.tag == "Wall").Select(a=>a.GetComponent<Rigidbody>();
The same result can be achieved using trigger sphere collider which detects and stores all "Wall" gameobjects entering the sphere. Do not forget to delete objects from collection when they leave trigger collider.
If all rigidbodies are children of your trigger collider or another parent you can easily get, the simplest way is to use
GetComponentsInChildren<Rigidbody>()
.Finally, the most convenient, but slow and architecture-unfriendly solution:
FindGameObjectsWithTag()
returns all gameobjects with specified tag present on the scene. You can easily get any rigidbodies collection you want, but there always is a better approach than that.
Your answer
Follow this Question
Related Questions
Collision Detection for Kinematic Rigidbodies 0 Answers
Ridgidbody cube 1 Answer
Gameobject Following Parent Rotation But Not Position? 0 Answers