Search code examples
unity-game-engineinstantiationvoid

How to access an instantiated GameObject from another function in Unity 2D


I just want to use the instantiated GameObject in another function but it always says The name 'newObject' does not exist in the current context

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

public class Deletenow : MonoBehaviour
{
    public Transform Player;
    public GameObject myObject;
    public Vector2 thisVector;

    void Start()
    {
        thisFunction();
    }

    void Update()
    {
        thisVector = newObject.transform.position;
    }

    public void thisFunction()
    {
        GameObject newObject = Instantiate(myObject, Player.transform.position, Player.rotation);
    }

}

I couldn't find any source that could help me


Solution

  • You either need to make the variable global or return it, whenever you call the function. As an example, look at thisFunction() and thatFunction()

    public class Deletenow : MonoBehaviour
    {
        public Transform Player;
        public GameObject myObject;
        public GameObject newObject;
        public Vector2 thisVector;
        public Vector2 thatVector;
    
    void Start()
    {
        thisFunction();
    }
    
    void Update()
    {
        thisVector = newObject.transform.position;
        thatVector = thatFunction().transform.position;
    }
    
    // init object - global variable
    public void thisFunction()
    {
        newObject = Instantiate(myObject, Player.transform.position, Player.rotation);
    }
    
    // init object - returns object
    public GameObject thatFunction() {
        GameObject objectToReturn = Instantiate(myObject, Player.transform.position, Player.rotation);
        return objectToReturn;
    }
    
    }