简体   繁体   中英

Accessing object's position from another script in Unity

I'm making a game with both a ball and a player. So far I made a sphere for the ball and a square (models will be made later) for the player. I attached a movement script to the player so that it can go in all directions, but I want him to be able to pick up the ball when he runs into it. To do this, I'm assuming that in the ball script, within a collision function, I would have to change its position to the position of the player. So I'm wondering: what is the correct way of accessing those coordinates of the player from the ball script?

I hope I understood you right. To just get the position you would do:

GameObject player = GameObject.Find ("Player");
Transform playerTransform = player.transform;
// get player position
Vector3 position = playerTransform.position;

But to pick up and carry away the ball you should rather do parenting:

// ...
transform.parent = playerTransform;
// take care to disable physics while ball is under control of the player
rigidbody.isKinematic = true;

This way you don's have to care about moving the ball by yourself every Update or FixedUpdate. If the player looses the ball later on, just reverse is by setting the ball's transform.parent = null and isKinematic = false .

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