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

Time:11-30

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

CodePudding user response:

Your issue is that newObject is defined in the scope of the function. Define it below the class declaration, so that it will persist. Then remove the GameObject part of

newObject=Instantiate(myObject,Player.transform.position,Player.rotation);

The class will look like public class DeleteNow : MonoBehaviour { GameObject newObject;… }

CodePudding user response:

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;
}

}
  • Related