I'm trying to do collision for a 2D character and a collider object. I have defined the OnTriggerEnter function to display a message in the debugger when a trigger is entered. The character is the "CharacterRobotBoy" asset from the Unity standard assets package (contains a BoxCollider2D) and I want it to collide with another object with attached BoxCollider2D, set as a trigger. I have trigger ticked on the second object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpCheck : MonoBehaviour {
private int pickUpCount;
// Use this for initialization
void Start () {
pickUpCount = 0;
}
void OnTriggerEnter(Collider collider)
{
// if (collider.gameObject.name == "RobotBoy")
// pickUpCount++;
Debug.Log("PickUp " + pickUpCount);
}
// Update is called once per frame
void Update () {
}
}
I've tried attaching the script to both the character and the other object but can't seem to register collisions with the trigger.
/edit - I've read there is or was an OnTriggerEnter2D. I've tried calling this but it's not recognized in Visual Studio. Not sure if it still exists or I'm doing something wrong?
/edit - Switched code to -
void OnTriggerEnter2D(Collider2D collider)
{
// if (collider.gameObject.name == "RobotBoy")
// pickUpCount++;
Debug.Log("PickUp " + pickUpCount);
}
But still no luck...
/edit - @Eddge Have set a common layer for both the character and pickup object, though I think collisions should still occur with no layers set?
This answer was informative, but I made sure I have the described components in my set up already - colliders on both objects, rigidbody present on one of the objects and one set as trigger.
/edit Solved! - Ok, so I cleaned up the debug (thanks to @Eddge for the suggestion). I moved the script to the character and noticed that collisions were occurring but not with the pickup object.
I switched the code in the OnTriggerEnter2D to output the name of the collided objects and this helped me get a clearer idea of what was going on:
void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log(collider.gameObject.name);
}
Turns out the problem was with the BoxCollider2D in the prefab I modified to be the pickup. I rebuilt the game object and this solved the problem.