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:
Make sure that the playerHealthScript variable is properly initialized and refers to the correct script component attached to the player gameobject.
Check if the playerHealthScript.heal() method is being called by adding a Debug.Log statement before the heal() method is called.
Verify that the healingAmount variable in the playerHealthScript is properly set and is not zero or negative.
Make sure that the player gameobject has the correct tag assigned to it.
Try using the
OnTriggerEnter2D()
method instead ofOnCollisionEnter2D()
for detecting collisions with the health potion gameobject. Check Unity documentation to see the difference between OnTriggerEnter2D and OnCollisionEnter2D.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 ! ).