Instance of an instantiated object is set to NULL every cycle of Update()


I have been trying to work on a prefab placement system recently, I made another post about it but I believe it may have not been clear enough, so I am making a new post and I will update the old one should I find a answer to my problem.

In short, I am trying to make a game which allows you to spawn in a wall when you left click, and when you left click again destroy the original wall and replace it with a different colored wall.

The problem is the variable containing the instance of the first wall is becoming NULL in the second part of my code - where it deletes the first wall :S

Here is my code:

function Update () {

	if(Input.GetMouseButtonDown(0)){ // If left click down
		if(Placing == false){ // If there is not currently a wall be previeewed
			// There is now a wall being previewed
			Placing = true;
			// Define a variable for the preview
			var PrePlaceWall : GameObject = Instantiate(InvisWall, transform.position + transform.forward * 10, transform.rotation);
			// Make sure that the preview wall is a child of the camera so it moves with the camera
			PrePlaceWall.transform.parent = transform;
			if(PrePlaceWall != null){
				Debug.Log("After placing wall, PrePlaceWall is not null!");
		}else{ // If there is currently a wall being previewed
			if(PrePlaceWall != null){
				Debug.Log("PrePlaceWall not null");
				// There is no longer a wall being previewed
				Placing = false;
				// Place the real wall in the position of the preview wall
				Instantiate(Wall, PrePlaceWall.transform.position, PrePlaceWall.transform.rotation);
				// Destroy the Preview wall

I cannot work out why the variable “PrePlaceWall” is turning to NULL, could somebody please help me? Essentially I need to place the prefab wall model when someone clicks and then destroy it when the user clicks again.

Thanks in advance,


It is becoming null because it is local to the function. Any variable declared inside a function only lives as long as the function is running. As soon as you return from Update() call, the value of PrePlaceWall is gone. The fix is declare the variable at the top of the file (outside of all functions):

private var PrePlaceWall : GameObject;

Then you would change line 11:

PrePlaceWall = Instantiate(InvisWall, transform.position + transform.forward * 10, transform.rotation);