1
\$\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\$
  • \$\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\$ – Alexandre Vaillancourt Jun 22 '18 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\$ – Pheonix2105 Jun 22 '18 at 1:17
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\$
  • \$\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 Jul 31 '18 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.