- Home /
Why when I destroy an object that shares same script with others, the rest of the objects are moving to infinity?
Hey! I created a game with some cars moving in the screen. When the player shoots a car and car's health is less than 0, it explodes and destoyed.Also it changes material. The problem is that when the car is destroyed and exploded, all of the rest cars in the scene are disappearing from the scene(they are having extreme values and keep moving to infinity). Is there a way to destroy only the car that has health<0, and just leave the rest car moving around?
My code looks like:
public class HealthController : MonoBehaviour {
//public variables public float priv_Health; public GameObject exlplosion; public Material material; public float destroyTime;
//private variables private Rigidbody rb; private BoxCollider col; private Renderer render;
public void Start() {
render = GetComponent<Renderer>();
rb = GetComponent<Rigidbody>();
col = GetComponent<BoxCollider>();
render.enabled = true;
}
public void ApplyDamage(float damage) { priv_Health -= damage;
if (priv_Health <= 0)
{
//Instantiate the explosion at the position of the current object
Instantiate(exlplosion, transform.position, transform.rotation);
render.sharedMaterial = material;//change the material of the car (rusty car)
rb.Sleep();
col.enabled = false;
gameObject.GetComponent<CARS>().speed = 0;//stop the car from moving
Destroy(gameObject, destroyTime);//destroy the car after a few seconds
}
}
}