简体   繁体   中英

Getting Vector 3 from another Script (C# Unity)

I have a script to position the player where fell off from the platform.

Platform Tracker.cs

public GameObject platformTrackerPoint;
public Vector3 platformTransform;

public PlayerMovement thePlayerMovement;

void Start()
{
    platformTrackerPoint = GameObject.Find("PlatformTrackerPoint");

    thePlayerMovement = FindObjectOfType<PlayerMovement>(); 
}

void Update()
{
    if ((transform.position.x < platformTrackerPoint.transform.position.x) && thePlayerMovement.grounded)
    {
        platformTransform = gameObject.transform.position;
        Debug.Log ("Plaform Transform =" + platformTransform);
    }
}

As I debugged, platformTransform shows the value I need. But its not reflecting in the code below.

GameController.cs

    public PlatformTracker thePlatformTracker;

    public Vector3 tempPosition;

void Start () {
        platformStartPoint = platformGenerator.position;
        playerStartPoint = thePlayer.transform.position;

        thePlatformTracker = FindObjectOfType<PlatformTracker>();
        thePlayer = FindObjectOfType<PlayerMovement>();
    }


    public void RespawnPlayer()
    {
       thePlayer.transform.position = thePlatformTracker.platformTransform;
    }

Your help is much appreciated. Please let me know if anything is not clear.

To access thePlatformTracker correctly, you need to use GetComponent. In GameController.cs Start() simply change:

thePlatformTracker = FindObjectOfType<PlatformTracker>();

To:

thePlatformTracker = GameObject.Find("").GetComponent<Platform Tracker>();

Be sure and add the game controller object name between the GameObject.Find("") quotation marks.

Then you should be able to access the platformTransform no problem since thePlatformTracker is now correctly referencing the script.

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