2
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ 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.) \$\endgroup\$
    – Vaillancourt
    Commented Jun 22, 2018 at 0:46
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 22, 2018 at 1:17

1 Answer 1

2
\$\begingroup\$

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);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Sorry for the late reply, I managed to solved it but your answer is exactly the better way to do it. Thanks! \$\endgroup\$
    – Mira
    Commented Jul 31, 2018 at 12:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .