Accessing object's position from another script in Unity

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-05 06:05:23

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10002634/accessing-objects-position-from-another-script-in-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!