OnTriggerEnter2D is not being called

2019-01-20 16:26发布

问题:

I am trying to make a replica of Asteroids in Unity. The problem is that my bullets are not triggering the OnTriggerEnter2D method on the asteroids. The asteroids have the following script attached:

using UnityEngine;
using System.Collections;

public class Asteroid : MonoBehaviour {

    void Start () {

        print ("class initiated"); 

    }

    void onTriggerEnter2D (Collider2D collider) {

        Debug.Log (collider); 

    }

}

The bullet GameObject has Is Kinematic and Is Trigger enabled, and has Rigidbody 2D and Box Collider 2D attached. The asteroid GameObject has Rigidbody 2D and Circle Collider 2D, and Is Kinematic and Is Trigger is unchecked.

回答1:

The problem is the Spelling. The o in onTriggerEnter2D should be capitalized. Simple mistake like this one can ruin your day. I didn't even notice it until I ran your code.

void OnTriggerEnter2D(Collider2D collider)
{
    Debug.Log(collider);
}

Next time if you are not sure about the spelling of the Unity callback function, right click in Visual Studio then click Implement MonoBehaviours search for the function you want, select it and click OK. Visual Studio will add that function for you.