Access variable declared in previous if statement

I have a double if statement. I am trying to reference a variable named obj that is declared in the first if statement. In the second statement I am trying to reference this variable so that I can unparent it. I have all of the code correct for making the parent null but for the life of me I can’t find out how to reference the obj variable. In my current build it says “NullReferenceException” when i attempt to use the obj variable in my second if statement.

Below is my code.

var respawnPrefab : GameObject;
var respawnPrefab1 : GameObject;
var respawnPrefab2 : GameObject;
var respawn : GameObject;


function Start()
{
    if (respawn==null) 
        respawn = GameObject.FindWithTag ("Respawn");
}

function Update()
{

var objs = new GameObject[3];

objs[0] = respawnPrefab;
objs[1] = respawnPrefab1;
objs[2] = respawnPrefab2;


if (Input.GetKeyDown (KeyCode.Mouse0))
	{  
	
	   var obj = Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation);
	   obj.transform.parent = Camera.main.transform;
	}
	
	
	if (Input.GetKeyUp (KeyCode.Return))
	{
	obj.transform.parent = null;
	}
}

Actually, your problem has another cause: the variable obj is temporary, thus it’s destroyed when you leave the function where it’s declared (Update, in this case). You should declare obj outside the function: this makes it a member variable, which survives while the script exists. Additionally, you could declare the objs array as a public variable and assign the prefabs to it in the Inspector in order to avoid allocating a new array each frame:

var objs : GameObject[]; // assign the prefabs in the Inspector
var respawn : GameObject;

private var obj : GameObject; // declare obj outside any function

function Start()
{
    if (respawn==null) 
        respawn = GameObject.FindWithTag ("Respawn");
}

function Update()
{
    if (Input.GetKeyDown (KeyCode.Mouse0))
    {  
        obj = Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation);
        obj.transform.parent = Camera.main.transform;
    }

    if (Input.GetKeyUp (KeyCode.Return))
    {
        obj.transform.parent = null;
    }
}