2D collision script not working

Hello!
I have a 2d collision script that is supposed to acknowledge collision to the player from a certain object (sword) and subtract health from the players total health. Finally it turns on a box that says, “You Died.” when the player gets equal to or below 0.
However this isn’t working/registering, and I tried to use the debug.log to help but to no prevail.

Any Help Would be Greatly Appreciated!!!

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class healthcollison : MonoBehaviour
{

    public int health = 100;
    public RawImage deathbox;
    // Start is called before the first frame update
    void Start()
    {
        deathbox.enabled = false;

    }

    // Update is called once per frame
    void Update()
    {
        if (0 >= health)
            deathbox.enabled = true;

    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.name == "sword")
        {
            health -= 35;
            Debug.Log(health);
        }
    }
}

Well the first thing that looks funny to me is this:

 void Update()
    {
// You're looking for zero Greater than or Equal to health
        if (0 >= health)
            deathbox.enabled = true;
    }

// Try this instead:
if(health <= 0)
{
deathbox.enabled = true;
}

Ok, the next thing I must question is here:

5208278--518291--upload_2019-11-24_11-9-52.png
Is sword spelled exactly as in the inspector, including punctuation?
Is your sword an isTrigger ? If isTrigger is set to true, then you would want to use OnTriggerEnter2D()

void OnTriggerEnter2D(Collider2D collision)
    {
        // Put a Tag on your sword called "sword"
        if (collision.tag == "sword")
        {
            health -= 35;
            Debug.Log(health);
        }
    }

Ok thanks!

1 Like