# Instantiated Object returns Null outside Start method

I'm attempting to access an instantiated 'goalTemp' GameObject from a different function inside the same script. I'm getting the information in the Start method, assigning the GameObject find/get component script code to a variable. When I'm printing the results outside the Start method, it returns null, even though the 'goal' variable is public.

void Start()
{
GameObject goalTemp = (GameObject)Instantiate(goal,respawnGoalLocation[CreateLevel.currentLevel-1],Quaternion.identity);
goal = goalTemp.gameObject;
}


public void Explode()
{
Debug.Log(goal);
Instantiate(rockParticle, goal.transform.position, goal.transform.rotation);
Instantiate(explosionParticle, goal.transform.position, goal.transform.rotation);
}


What am I doing wrong here? Thanks for your time!

• goal = goalTemp.gameObject; seems weird to me (I'm no expert in Unity). What if you used goal = goalTemp; instead? (goalTemp.gameObject seems to be the constructor of the object.) – Alexandre Vaillancourt Jun 22 '18 at 0:46
• goalTemp is already a GameObject you don't need to refer to .gameObject though I don't think that would cause your issue either way. – Pheonix2105 Jun 22 '18 at 1:17

## 1 Answer

I cannot see why your code would not work outside of setting the goalTemp(GameObjects) variable to the .gameObject property since its already a GameObject, I am unsure if this would cause any issues though as that should just reference the same thing.

I set up a quick plain simple demo to show you how I would do it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour {

//the prefab we will spawn
public GameObject prefab;
//a reference to this instance, normally if there's more than one you put them in a list or array or whatever
private GameObject prefabInstance;

// Use this for initialization
void Start ()
{
//assign the prefabinstance here
prefabInstance = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
}

// Update is called once per frame
void Update ()
{
//debug it on space pressed
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log(prefabInstance);
}
}
}

• Sorry for the late reply, I managed to solved it but your answer is exactly the better way to do it. Thanks! – Mira Jul 31 '18 at 12:24