Instantiated object is null in next frame

I’ve got the following code

        public GameObject currentObject;
        
        // Start is called before the first frame update
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {
            if (currentObject != null)
            {
                    //Do stuff
            }
           
        }

        public void SpawnObject(GameObject gameObject)
        {
            if (currentObject == null)
            {
                currentObject = Instantiate(gameObject);
            }
        }

The SpawnObject is called on a button click and adds a gameobject. When I click the button the gameobject is instaniated and I can see it in my scene but in the next update the currentObject variable is null and I can’t see why that would be.

Any help in spotting what I’m missing would be much appreciated.

Further debugging shows that if I click the button to SpawnObject again the currentObject isn’t null but if I put a breakpoint on the update then it shows as null.

Dammit. I had the prefab in the button click rather than the empty object in my scene which had the script attached.

Hi Stephen,

Does that mean you managed to fix the issue? If so, it would be great if you could mark your answer as the solution.


See also:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms