On Collision Manager

I forgot how to make a script that watches the collisions between objects
kinda like this

//Collision Manager system
public GameObject ObjectA,
ObjectB;

public void OnCollisionEnter(Collision ObjectA, collision ObjectB)
  {
      if (ObjectA collide with ObjectB.Tag == "tag")
      {
          Debug.Log("Items collided");
      }
  }
1 Like

this looks like it’s for the object the script is attached to but what if i want to view coalitions between two objects the script isn’t attached to.

Make a little wrapper, put it on one of the objects, implement the Unity function I referenced above there, and forward it onto another function, perhaps through using an interface to find an object that has your signature that takes two colliders.

Note also that the Unity function takes a Collision, NOT a Collider. There is a difference.

1 Like

If I half to put OnCollisionEnter on ObjectA or ObjectB I will. I just thought there was a way to detect collisions between objects without having to put the script on every object making collisions.

Directly you can’t, u can make a class like this and make all GameObjects you can track the collisions child of it:

public abstract class Collisionable : Monobehaviour
{
    protected void OnCollisionEnter(Collision collision)
    {
        CollisionManager.Collision(gameObject, collision.gameObject);
    }
}
public static class CollisionManager
{
    public static void Collision(GameObject reporter, GameObject collisioner)
    {
        Debug.Log(collisioner.name + " collisioned with " + reporter.name);
    }
}

And CollisionManager does whatever u wanna do with both GameObjects. Remember that if both GameObject inherits from Collisionable, Collision() would be run twice, one for each.

1 Like

you know I’m probably getting colliders and triggers mixed up.

I’m going to note that if you listen for OnCollisionEnter for EVERY collision in game… you’re likely to get a lot of slow down as your world grows.

This can be fine for a very small game… but scaling up will not be so good.

Instead by having a script on only the GameObject’s you’re concerned about is better. This way you don’t have to really bother with events for random collisions/trigger entering.

Furthermore usually on collision or trigger enter a given object does something specific for that object. Like say a trigger box that opens a door… there’s a specific trigger box, and a specific door that is opened. This doesn’t have to be global… the box has a script that listens for when it’s entered, and it references the door it opens.

Globals are generally considered bad in an OO environment as it makes it difficult to scale your code out.

1 Like