- Home /
How to destroy only one GameObject???
The code I'm using is ~~
using UnityEngine;
public class HealthScript2 : MonoBehaviour {
/// <summary>
/// Total hitpoints
/// </summary>
public int hp = 1;
/// <summary>
/// Enemy or player?
/// </summary>
public bool isEnemy = true;
/// <summary>
/// Inflicts damage and check if the object should be destroyed
/// </summary>
/// <param name="damageCount"></param>
public void Damage(int damageCount)
{
hp -= damageCount;
if (hp <= 0)
{
// Dead!
Destroy(gameObject);
}
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
// Is this a shot?
ShotScript shot = otherCollider.gameObject.GetComponent<ShotScript>();
if (shot != null)
{
// Avoid friendly fire
if (shot.isEnemyShot != isEnemy)
{
Damage(shot.damage);
// Destroy the shot
Destroy(shot.gameObject); // Remember to always target the game object, otherwise you will just remove the script
}
}
}
}
Whenever I destroy one object, all the other objects vanish also!?~~ How could I make it so only the targeted object vanishes?
Comment
Are the other objects a child object of the one that your component is added to? If so, when you call Damage(shot.damage) and that gameobject is destroyed, it will destroy all children.
public void Damage(int damageCount)
{
hp -= damageCount;
if (hp <= 0)
{
// Dead!
Destroy(gameObject);
}
}
When the Destroy() is called above, anything that is a child of that object will be destroyed too.