How to Destroy a Gameobject in Update thats initiated in Start.

I am creating a GameObject out of an Array in Start. The thing is that i only know the Arrayname plus position and that the GameObject variable is called spawnBG. So GameObject.Find wont work, as much as i know. The Destroy function just gives me the Error (Can`t use variable before it is declared).

`using UnityEngine;
using System.Collections;

public class BG_with_Switch : MonoBehaviour {

public static int levelNow = 0;
public GameObject[] backGrounds;
private int levelOld;
public static int levelMax;

// Use this for initialization
void Start () {
    Debug.Log("Array" + (backGrounds.Length - 1));
    levelOld = levelNow;
    levelMax = backGrounds.Length - 1;
    GameObject spawnBG = (GameObject)Instantiate(backGrounds[levelNow]);
}

// Update is called once per frame
void Update () {
    if (levelOld != levelNow)
    {
        Destroy(spawnBG);
        GameObject spawnBG = Instantiate(backGrounds[levelNow]);
        levelOld = levelNow;
       
    }
}

}`

The best case i could think of would be, if I could Destroy the the old Object by its Arrayname. Like: backGrounds[1] etc.

Hi. Please make sure your code is formatted properly before you post it. This string of red letters is not very easy to read, even worse for spotting errors. Check out this 1.

The thing is that i only know the
Arrayname plus position and that the
GameObject variable is called spawnBG.

Well, yes, since you declared all those things you know what they are, and their names.

The problem is simply that you declared the variable spawnBG within Start. Therefore only the code within Start’s scope “knows” what it is.

You need to declare spawnBG in the scope of your entire script like the other variables, not in Start only.

Watch this tutorial: Scope and Access Modifiers
I can really suggest you have a look at those tutorials, especially the scripting playlist, as they are the foundation of your Unity knowledge.

PS: I wouln’t recommend Destroying and Re-Instantiating an object in Update. This would be executed every frame of the game, which can lead to very poor performance, and I’m certain you don’t need to change your background object every ~60th of a second :wink:

Edit: Ignore that PS, I overlooked the level integer check. Sorry :smiley:

Another Edit: I copied your code into Mono and I spotted another error you are producing when you declare spawnBG in the whole scope. You don’t need to declare it in Update as well. In fact, if you declare a variable with the same name in different scopes, the compiler has no idea that they are meant to be the same thing. Remember, if you want to use something in multiple functions, or scopes, declare it beforehand in the “motherscope”, the entire class.

See? That’s the risk when not formatting your code properly, it’s easy to miss something.

Have a nice day!

GameObject.Find(“[objectName]”) should work fine as long it has a unique name in the scene hierarchy. If it doesn’t have a unique name, you should do something like:

using UnityEngine; 
using System.Collections; 

public class BG_with_Switch : MonoBehaviour 
{ 
	public static int levelNow = 0; 
	public GameObject[] backGrounds; 
	private int levelOld; 
	public static int levelMax; 

	// Use this for initialization 
	void Start () { 
		Debug.Log("Array" + (backGrounds.Length - 1)); 
		levelOld = levelNow; 
		levelMax = backGrounds.Length - 1; 
		GameObject spawnBG = (GameObject)Instantiate(backGrounds[levelNow]); 

		/// Give it unique name with the index of levelNow
		spawnBG.name = "Object " + levelNow;
	} 

	// Update is called once per frame 
	void Update () { 
		if (levelOld != levelNow) 
		{ 
			/// Find and destroy the object whose name is "Object [levelOld]"
			Destroy(GameObject.Find("Object " + levelOld)); 
			GameObject spawnBG = Instantiate(backGrounds[levelNow]);
			levelOld = levelNow;

			/// Give it unique name again
			spawnBG.name = "Object " + levelNow;
		} 
	} 
}

That won’t work. Your GameObject spawnBG is a local variable on Start() and Update(), so it’s never declared in Update(). Try to declare it as global variable like this:

using UnityEngine; 
using System.Collections; 

public class BG_with_Switch : MonoBehaviour { 

public static int levelNow = 0; 
public GameObject[] backGrounds; 
private int levelOld; 
public static int levelMax;
GameObject spawnBG;

// Use this for initialization 
void Start () { 
     Debug.Log("Array" + (backGrounds.Length - 1)); 
     levelOld = levelNow; 
     levelMax = backGrounds.Length - 1; 
     spawnBG = (GameObject)Instantiate(backGrounds[levelNow]); 
} 
// Update is called once per frame 
void Update () { 
if (levelOld != levelNow) { 
       Destroy(spawnBG);
       spawnBG = Instantiate(backGrounds[levelNow]); 
       levelOld = levelNow; } 
    } 
}

This example :

public GameObject  prefabObject;
private GameObject lastSpawnedObject;
public float Destroytimer;

void Start()
{
lastSpawnedObject = Instantiate(prefabObject,transform.position, transform.rotation);
}
void Update()
{
Destroy(lastSpawnedObject, Destroytimer);
}

or create new script and attach to your prefab

public float Destroytimer;

void Start()
{
Destroy(this.gameObject, Destroytimer)
}

Thanks, I had to leave the Project for some time. I will try your suggestions today.

Hey,

You could use the ForeachLoop in your script to destroy all GameObjects in your array.

Havent tested the code but im pretty sure this should work!

Cheers!:slight_smile:

void Update () 
{
     foreach(GameObject BGs in backGrounds)
     {
         Destroy (BGs);
     }
}