简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM