Home > Software engineering >  How do I reference a GameObject from a script inside an instantiated object in unity c#?
How do I reference a GameObject from a script inside an instantiated object in unity c#?

Time:01-02

(Fairly new to Unity and C# btw)

So we have a GameObject and let's say we want to move it to x = 0, y = 0, z = 0 FROM a script inside an instantiated (cloned) object.

If I write:

public GameObject Obj;

I can't actually assign anything to it that is outside of the prefab that I'm instantiating.

CodePudding user response:

Hopefully I'm following, but you could try assigning the object-to-move inside the script that instantiates the prefab. Then once it's created, assign the object-to-move to the public Obj variable. Like this:

// Inside your instantiating script
public GameObject obj;
public static void InstantiateWithObj()
{
    GameObject newObject = Instantiate(YourPrefab) as GameObject;
    MoveScript moveScript = newObject.GetComponent<MoveScript>();
    moveScript.Obj = obj;
}
  • Related