- Home /
Only destroy one instatnce
Hi, I'm having a problem where all of the game objects with the health script get destroyed, not just one specific instance. I know why this has happened, but don't have a solution. If I'm correct it's because the scripts changes a value for all instances that it's attached to.
The health script:
using UnityEngine;
using System.Collections;
public class health : MonoBehaviour {
public float maxHealth;
public float minHealth;
static float currentHeath;
void Start() {
currentHeath = maxHealth;
}
void Update() {
if (currentHeath < minHealth) {
Destroy(this.gameObject);
}
}
public void takeDamage(float Damage) {
currentHeath = currentHeath - Damage;
}
}
When you have "static float" and you change that static float, it will of-course change it to all objects, that have this script attached to. Change that static float to public float and alter the currentHealth only to the object, that get's damaged. example: damagedObject.GetComponent(health).takeDamage(10)
... This way only the referred object will get damaged and only it will get destroyed when it's health get's 0
Answer by Murkas · Jun 04, 2014 at 09:26 PM
Your currentHealth
is declared as "static". That means all instances share the same value. Removing the "static" should solve your problem.