Destroy 2D obj issue
I have a simple script to keep track of the players health and destruction, but it won't work fully. The health does work and colliding with objects works fine, but I can't get it to destroy the object when the player is at 0 health.
using UnityEngine;
using System.Collections;
public class damagePlayer : MonoBehaviour {
public int playerHealth=30;
int damage=10;
void Start()
{
print (playerHealth);
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Colliders")
{
playerHealth-=damage;
print ("Player hit" + playerHealth);
}
}
void update()
{
if (playerHealth <= 0)
{
Destroy (this.gameObject);
}
}
}
Answer by Dave-Carlile · Jun 07, 2016 at 12:44 PM
Most programming languages are case sensitive, so for example update
and Update
are not the same thing. You need to fix the name of your Update
method so Unity will actually recognize and call it.
Answer by skillbow · Jun 07, 2016 at 12:38 PM
Should be just
Destroy(gameObject);
Since there is no other gameObject variable in scope gameObject
and this.gameObject
refer to the same object.
Your answer
Follow this Question
Related Questions
Checking if the player jumps while not grounded 0 Answers
How do I move a game object only on the x axis with arrow keys? 1 Answer
NullReferenceException by detecting health 1 Answer
Having UI follow player 2D C# 0 Answers
C# 2D Top down game how to detect if objects are touching while they can pass through each other? 1 Answer