Spawn/Destroy

Hey guys, I was just wondering if someone could take a quick look at my code to figure out why my game object is not being destroyed. What I am trying to do is to spawn an object, and then destroy it when the function runs again. This code doesnt come up with any errors, and the debug message does show so im not sure why it isnt working.

isFoundation is a boolean
and foundation is a gameobject

function foundationOn () {

	isFoundation =!(isFoundation);
	
	

	if (isFoundation == true) {
	
		foundations = Instantiate (foundation, transform.position, transform.rotation);
		
	}
	
		
	if (isFoundation == false) {
	
		Destroy(foundations);
		
		Debug.Log("foundations destroyed");
			
	}		
		
		
}

Is it because you have foundations in the desrtoy line instead of foundation :idea:

So why did you create your own function to do this, are you planning on calling it from another script? :smile:

Yep, it is called from another script. Thanks ill try it out.

Hmmmm now I get the “Destroying assets is not permitted to avoid data loss.” Error =/

How about trying a static bool in an Update function instead of a static function :idea:

var fireOne = false;
var myGameobject : GameObject;

function Update () {
	
if(fireOne == true){	
			
var myGameobject : GameObject = Instantiate(myGameobject, transform.position, transform.rotation);

Destroy(myGameobject,0.4);

  }
}

IDK then set the bool back some how :idea:

Well at the moment I have it set up so that there is another script with all my GUI information. This script holds is attached to a game object that spawns items on it when you press a GUI.button. The GUI.button sends a message to this script to run the function. I cant tell if it is something simple or if there is a problem with the entire set up because im tired lol, and scripting while im tried = mistakes :frowning:

Use your gui button to set the static bool to true with an else statment to set it back to false. :smile:

I got it working =D thanks for bouncing ideas off me though =P it woke me up a bit here is the fix.

var currentFoundation : GameObject;


function foundationOn () {

	isFoundation =!(isFoundation);
	
	

	if (isFoundation == true) {
	
		foundations = foundation;

		currentFoundation = Instantiate (foundations, transform.position, transform.rotation);
		
	}
	
		
	if (isFoundation == false) {
	
		Destroy(currentFoundation);
		
		Debug.Log("foundations destroyed");
			
	}		
		
		
}

I added another var “currentFoundation”