问题描述
我正在统一创建一个视频游戏,对于关卡选择,我需要将 GameObject 的 x 和 y 位置设置为按钮的 x 和 y 位置.
I am creating a video game in unity, and for the level select, I need to set the x and y position of a GameObject to the x and y position of a button.
我试过这个代码-
if (gameObject.CompareTag("Level1")) {
float xPos = gameObject.transform.position.x;
float yPos = gameObject.transform.position.y;
levelWindow.SetActive(true);
levelTitle.text = "One- Dunes of Coral";
levelDescription.text = "Begin your ocean voyage in the safe haven of the Hawaiian coral reefs...";
levelWindow.transform.position.x = xPos;
levelWindow.transform.position.y = yPos;
}
但我收到这样的错误-
Assets/Scripts/LevelTapScript.cs(21,39):错误 CS1612:无法修改UnityEngine.Transform.position"的值类型返回值.考虑将值存储在临时变量中
我的问题是如何使用我的 xPos 和 yPos 浮动设置 levelWindow(这是一个游戏对象)的 x 和 y 位置?谢谢-乔治 :)
My question is how do I set the x and y position of the levelWindow (which is a game object) using my xPos and yPos floats? Thanks- George :)
推荐答案
您必须创建一个临时的 Vector3
变量,修改 x 轴然后将其分配回 Transform.position.
You have to create a temporary
Vector3
variable, modify the x axis then assign it back to the Transform.position
.
if (gameObject.CompareTag("Level1"))
{
float xPos = gameObject.transform.position.x;
float yPos = gameObject.transform.position.y;
Vector3 newPos = new Vector3(xPos,yPos,0);
levelWindow.SetActive(true);
levelTitle.text = "One- Dunes of Coral";
levelDescription.text = "Begin your ocean voyage in the safe haven of the Hawaiian coral reefs...";
levelWindow.transform.position = newPos;
levelWindow.transform.position = newPos;
}
请注意,执行此操作时 z pos 将为 0.
Note that z pos will be 0 when you do this.
这篇关于如何分配 GameObject 的 x 和 y 位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!