Nullititiousness
Nullititiousness

Reputation: 371

How to handle 2d collisions in a script that isn't attached to Game Object

Generally, from what I've learnt, collisions are handled in the script that is attached to a Game Object. In my game, I have 6 game objects that collide with each other making the former idea difficult to implement. I want to make all the game objects prefabs and instantiate them in another script attached to an empty game object. How can I handle collisions between all these 6 game objects in the new script?

Upvotes: 0

Views: 640

Answers (1)

Agustin0987
Agustin0987

Reputation: 601

I'm wondering the same thing as Joe Blow, but still if what you want to try to do is handle collisions manually (which by the way will make Physics harder since you would have to calculate bounciness, gravity, etc... manually) then you can try this:

public class OtherScript : MonoBehavior
{
    public GameObject[] objects; //Your 6 GameObject

    void Update()
    {
        for (int i=0; i<objects.Length; i++)
        {
            for (int j=0; j<objects.Length; i++)
            {
                if (objects[i].GetComponent<Renderer>().bounds.Intersects(
                           objects[j].GetComponent<Renderer>().bounds))
                {
                    //Handle collision
                    break;
                }
            }
        }
    }
}

If this doesn't work then you should also try with GetComponent<MeshFilter>().mesh.bounds. Note that if your game is 2D you should use GetComponent<SpriteRenderer>().mesh.bounds instead.

Upvotes: 1

Related Questions