Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Resolved Sanity check needed: OnCollisionEnter2D, basic 'shoot enemy, they take damage' script interaction

Discussion in 'Scripting' started by OverthinkingThis, Sep 4, 2020.

  1. OverthinkingThis

    OverthinkingThis

    Joined:
    Sep 4, 2020
    Posts:
    5
    Hey guys,

    Dusting off old bones of a game and trying to get OnCollisionEnter2D to work (it worked before but now it's not). I'm sure I'm missing something hilariously obvious.

    ====method in script attached to bullet

    void onTriggerEnter2D (Collider2D col) {
    Debug.Log("HIT");
    EnemyHealth Healthinter = col.GetComponent<EnemyHealth>();
    if (Healthinter != null) {
    Healthinter.damageReceived(damage);
    }
    }

    ====method in script attached to enemy (named EnemyHealth)

    public void damageReceived (float damage) {
    health -= damage;
    Debug.Log(this.name + " has taken [" + damage + "] damage.");

    if (health<=0) {
    dead(); //this is referenced elsewhere
    }
    }

    I have both enemy and bullet attached with 2DRigidbodies and 2DPolygoncolliders (set as triggers) and I doublechecked to make sure they were actually hitting each other. Yet I am getting no interaction, including not getting any relevant log entries.

    Unity version is 2020.1.0f1

    Any help would be appreciated!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,724
    onTriggerEnter2D
    is misspelled. It should be
    OnTriggerEnter2D


    if you're using recent versions of Visual Studio and Unity, the IDE should give you this little helper above any Unity message functions:
    upload_2020-9-4_17-18-20.png

    If you don't see that "Unity Message" notice, it could be a sign that something is not spelled right. Also, always check the list of "Messages" here to make sure things are spelled right: https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
     
  3. OverthinkingThis

    OverthinkingThis

    Joined:
    Sep 4, 2020
    Posts:
    5
    I knew it was something as innocuous as that! This is what happens when I let a project collect dust for a few weeks haha.

    That was it! Thank you for the sanity check!