- Home /
Destroying Game object (Not destroying) C#
I currently have a script which spawns objects at the top of the screen and fall with gravity. However, when I call "Destroy(prefab)", the prefab does not destroy at all. Here is the code:
using UnityEngine;
using System.Collections;
public class AsteroidManager : MonoBehaviour {
public float minTime;
public float maxTime;
public bool doSpawn = true;
public GameObject prefab;
public Vector3 minSize, maxSize;
public float minX, maxX;
public Vector3 startPosition;
// Use this for initialization
void Start () {
rigidbody.useGravity = false;
doSpawn = false;
renderer.enabled = true;
enabled = false;
GameController.GameStart += GameStart;
GameController.GameOver += GameOver;
}
// Update is called once per frame
void Update () {
if(prefab.transform.localPosition.y < -5){
Destroy(prefab);
}
}
IEnumerator Spawner(){
while(doSpawn) {
Vector3 v = new Vector3(Random.Range(minX, maxX), 25, 0);
Quaternion r = new Quaternion(0,0,0,0);
Instantiate(prefab, v, r);
prefab.renderer.enabled = true;
prefab.rigidbody.useGravity = true;
yield return new WaitForSeconds(Random.Range(minTime, maxTime));
}
}
private void GameStart () {
Vector3 temp;
temp.x = 0; temp.y = 0; temp.z = 0;
rigidbody.velocity = temp;
rigidbody.useGravity = true;
transform.localPosition = startPosition;
renderer.enabled = true;
enabled = true;
doSpawn = true;
StartCoroutine(Spawner());
}
private void GameOver () {
rigidbody.useGravity = true;
Destroy(prefab);
renderer.enabled = false;
doSpawn = false;
enabled = false;
}
}
Any help would be greatly appreciated.
Answer by robertbu · Mar 10, 2014 at 04:38 PM
You are trying to destroy the prefab...the blueprint for all of your asteroid. Luckily, since the prefab is not moving, the condition is never met. These lines of code...
void Update () {
if(transform.position.y < -5){
Destroy(prefab);
}
}
...need to be on a script attached to the asteroid prefab. That is, each asteroid is needs to be responsible for destroying itself. The alternative is to keep a generic list of asteroids created in your AsteroidManager and then check each one each frame, destroying it and removing it from the list if the condition is met.
using UnityEngine;
using System.Collections;
public class AsterBeh : $$anonymous$$onoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(transform.localPosition.y < -5){
Destroy(this.gameObject);
}
}
}
Like this?
Got it working. Thank you very much for your help Robertbu. You've been an amazing help.
Note unless you are doing parenting, line 13 should use transform.position, not transform.localPosition. I know my original answer used 'localPosition'.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Hide/Unhide Game Object 4 Answers
Two exact objects behaving differently... *scratches head* 0 Answers