Home > OS >  I am struggling to get a game object to be destroyed when colliding with the player
I am struggling to get a game object to be destroyed when colliding with the player

Time:12-04

I have written code to heal the player after colliding with the health potion and then destroy the potion game object making it one time use, however, the gameobject does not get destroyed and the player is not healed. Code is as shown below:

    private void OnCollisionEnter2D(Collision2D collision)
    {

        if (collision.gameObject.tag == "Player" )
        {
            playerHealthScript.heal();
            Destroy(gameObject);
        }
    }
}

(code below is in a seperate script, used for player health)

    public void heal()
    {
        currentHealth  = healingAmount;
        currentHealth = Mathf.Clamp(currentHealth, 0, 100);

        healthBar.fillAmount = currentHealth / 100f;

    }

CodePudding user response:

There could be several reasons why the gameobject is not being destroyed and the player is not being healed. Here are some possible solutions:

  1. Make sure that the playerHealthScript variable is properly initialized and refers to the correct script component attached to the player gameobject.

  2. Check if the playerHealthScript.heal() method is being called by adding a Debug.Log statement before the heal() method is called.

  3. Verify that the healingAmount variable in the playerHealthScript is properly set and is not zero or negative.

  4. Make sure that the player gameobject has the correct tag assigned to it.

  5. Try using the OnTriggerEnter2D() method instead of OnCollisionEnter2D() for detecting collisions with the health potion gameobject. Check Unity documentation to see the difference between OnTriggerEnter2D and OnCollisionEnter2D.

  6. Use OnCollisionEnter if its supposed to be 3D and not 2D.

CodePudding user response:

Before seek for anything, you should Debug.Log("Collision") in your first function, maybe your code is right but the collision isn't detect.

If so, yo could consideer check if the syntax of "Player" is the same as the tag, or maybe your "Player" doesn't have any rigidbody2D ( 2D is important ! ).

  • Related