- Home /
Scripts not on instantiated GameObjects?
Trying to create a stream of projectiles that disappear after being around for a short amount of time.
Code on the spawner (seems to work fine) using UnityEngine; using System.Collections;
public class PewPewBehavior : DefenderBehavior {
public GameObject pewpew;
void Update() {
GameObject clone;
clone = (GameObject)Instantiate(pewpew, transform.position + Vector3.forward, transform.rotation);
clone.rigidbody.AddForce((Vector3.up * 10),ForceMode.Force);
}
}
Script on the projectile: using UnityEngine; using System.Collections;
public class ProjectileDestroy : MonoBehaviour {
public int MaxLife = 50;
public int Life = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (Life > MaxLife)
Destroy(this);
else
Life += 1;
}
}
However, I the projectiles last forever. When I pause the game and select a projectile the script is not there. Thoughts?
Answer by Landern · Jan 05, 2013 at 06:07 AM
You are not destroying the GameObject.
public class ProjectileDestroy : MonoBehaviour {
public int MaxLife = 50;
public int Life = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (Life > MaxLife)
Destroy(this.gameObject);
else
Life += 1;
}
}
So it is normal to not see scripts on instantiated objects when you pause the game player?
No, the problem is that you destroy the script with Destroy(this), so the Script has already been removed when you look at the object. Like Jordan said, you have to use Destroy(gameObject) ('this' is redundant here).