Is ther a way to know what another object is colliding with? I have a bunch of child objects, each with a trigger collider. I want the parent to be able to know which children are colliding with an object. Here is my parent’s script:
foreach (GameObject child in transform) {
if (child. /* on trigger stay includes an object with tag "taken", */){
Debug.Log (child.transform.name + " is colliding with taken");
}
}
Is there a way to get a list of another object’s collisions from script?
Hello, iterating through all childs on each physics update is not quite optimized. Try notifying parent only when a collision occurs.
Try attaching this script to your parent object:
using UnityEngine;
public class ParentScript : MonoBehaviour {
public void CollisionDetected(ChildScript childScript)
{
Debug.Log("child collided");
}
}
and this one to every child which are colliding
using UnityEngine;
public class ChildScript : MonoBehaviour {
void OnCollisionEnter(Collision collision)
{
transform.parent.GetComponent<ParentScript>().CollisionDetected(this);
}
}
Please be aware that childs must be nested inside parents transform.
If your child is buried deep within your objects, you can use this instead. As you may have notice, the parent registers their method via delegate to each child, while the child just triggers the said delegate. if you’re dealing with multiple colliders, you can also pass multiple children to your parent.
PARENT CLASS
public class CollisionParent : MonoBehaviour
{
[SerializeField]
public List<CollisionChild> colliders;
// Start is called before the first frame update
void Start()
{
foreach(CollisionChild child in colliders)
{
child.collide = onCollide;
}
}
void onCollide(Collider collider)
{
Debug.Log("Collided");
}
}
CHILD CLASS
public class CollisionChild : MonoBehaviour
{
public delegate void Collide(Collider collide);
public Collide collide;
private void OnTriggerEnter(Collider other)
{
collide(other);
}
}