- Home /
Why doesn't Destroy() show any effect on my GameObject?
I instantiate game objects any call immediately Destroy(), but the objects won't be removed from the hierarchy.
GameObject go = GameObject.Instantiate( bullet, transform.position, Camera.main.transform.rotation ) as GameObject;
Destroy(go,1);
The objects seem to be removed from the rendered frame but the hierarchy is filled with many instances "bullet(Clone)". Does it depend on the object the script is attached to? (I added the script to a dummy object, because there are no bullets in the scene when starting)
Full script:
public class Bullet : MonoBehaviour {
public GameObject launcher;
public GameObject bullet; // prefab
public GameObject platform;
private List<BulletDetail> bullets = new List<BulletDetail>();
void Update ()
{
Debug.Log( "bullets Update");
if ( bullets.Count < 10 ) {
Transform transform = (Transform) Instantiate( bullet.transform );
GameObject go = GameObject.Instantiate( bullet, transform.position, Camera.main.transform.rotation ) as GameObject;
Destroy(go,1);
HexGrid hexGrid = platform.GetComponent<HexGrid>();
if ( hexGrid == null ) {
Debug.Log( "no hex grid selected");
return;
}
Debug.Log( "bullets.Count=" + bullets.Count);
GameObject target = (GameObject) hexGrid.GetSelected();
BulletDetail bull = new BulletDetail(go,transform,target.transform);
bullets.Add( bull );
}
for(int i = bullets.Count - 1; i >=0 ; i--) {
BulletDetail bd = bullets[i];
if ( bd.Move() ) {
bullets.RemoveAt(i);
Destroy(bd.getBullet());
Debug.Log( "destroy called");
}
}
}
}
Answer by Xtro · Apr 01, 2015 at 07:08 PM
You are double Instantiating the bullet but destroying only once.
Remove the line 13 and use go.transform instead.
Answer by stacker3d · Apr 02, 2015 at 05:20 AM
I had to add a script to the prefab gameobject and apply it (Menu:GameObject/Apply Changes To Prefab):
using UnityEngine;
using System.Collections;
public class Destroy : MonoBehaviour {
public float timeToLive = 2f;
// Use this for initialization
void Start () {
Destroy(gameObject, timeToLive);
}
// Update is called once per frame
void Update () {
}
}
I would still like to know what is the reason that my approach from the question doesn't work (the gameObject is a parameter of Destroy() and should have a unique references.
As I told you in my answer, you were creating 2 bullets at a time but destroying only one of them. You also marked my answer as a correct one. Why do you still wonder what was the reason?
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Destroying objects 1 Answer
Destroy + Score 1 Answer
Simple on Collision Help (C#) 2 Answers
gameObject doesn't self-destruct after collision c# 2 Answers