Minimus
Minimus

Reputation: 1

Passing values from one script to another without a game object in the scene

I’ve found a lot of information on passing parameters from one script to another when a game object is present in the hierarchy. My problem is that my Transform object is created on the fly using Instantiate(myPrefab). Is there any way to access the position of myPrefab game object from another script?

Upvotes: 0

Views: 54

Answers (1)

Edwin Chua
Edwin Chua

Reputation: 690

You could store a reference to the instantiated GameObject after it has been instantiated (see example below). If there are more GameObjects, use a list to store them instead.

Call the InstantiateGO() and GetGOPosition() where it makes sense for you.

public class YourClass: MonoBehaviour 
{
    public GameObject yourPrefab;
    public GameObject yourGameObject;

    // Use this for initialization
    void Start () 
    {

    }

    // Update is called once per frame
    void Update () 
    {

    }

    void InstantiateGO()
    {
        yourGameObject = Instantiate(yourPrefab); // assign the newly instantiated GameObject to yourGameObject 
    }

    void GetGOPosition()
    {
        var x = yourGameObject.position;
        //Do something here
    }
}

Upvotes: 1

Related Questions