How do I get collision and trigger to work?
I'm new to Unity and am trying to create a simple 2d game. However I cannot get collisions or triggers to work under any circumstances. I even created an entirely new 2d project in unity with only 2 objects colliding to remove any other factors but was unable to get it to work. Here is the C# script I've been using:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void Start()
{
print("Start: " + gameObject.name);
}
void OnTriggerEnter(Collider other)
{
print("OnTriggerEnter: " + gameObject.name);
}
void OnCollisionEnter(Collision col)
{
print("OnCollisionEnter: " + gameObject.name);
}
}
Because this is a completely fresh project the collision matrix (for both 3d and 2d) are set to interact with all layers, so that's not the issue. I also make sure to have colliders on objects and a rigidbody on one of them.
Based on search results for similar problems I've tried the following:
I just create 2 game objects, 1 circle to drop on a square. For the square I just add a default 2d box collider and the script. For the circle to be dropped I added a default 2d rigidbody and a default 2d box collider. Gravity will do the rest.
When I start the game I only get the start message from the script. The circle drops and stops at the square, but no further messages are fired. I expected the OnCollisionEnter message to be fired.
If I set isTrigger on the square, the circle drops through it as expected, but no message is triggered. Similar behaviour if i set isTrigger on the circle or both, however since the circle has no script I wouldn't expect that to work.
I tried switching to continuous collision detection on the rigidbody, but this did not help.
I tried increasing the mass on the rigidbody, using several different values up to 10000, however this had no effect (nor should it?).
I tried moving the script to the circle, and also having the script on both. The only message which is ever fired is still the start message for each object.
I tried using 2d circle colliders, edge colliders and polygon colliders.
In my actual project I've tried moving the objects with rigidbody.AddForce and rigidbody.velocity instead of just using gravity. However this worked no better.
What could be the problem?
Answer by LazyElephant · Mar 26, 2016 at 09:21 AM
You're using the 3d versions of OnCollisionEnter and OnTriggerEnter but using 2d rigidbodies and colliders. You need to use OnCollisionEnter2D and OnTriggerEnter2D.
Answer by Max_power1965 · May 24, 2020 at 03:49 PM
I also had really a lot of problems when configuring the collision between game objects. After years I wrote every tips in this article https://gamedevelopertips.com/unity-collision-detection-2d/, I'm sure it'll be helpful if you want to set up properly you collider/triggers properly.