如何分配GameObject的x和y位置? [英] How do I assign a GameObject's x and y position?
问题描述
我正在统一创建一个视频游戏,对于关卡选择,我需要将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;
}
但是我收到这样的错误-
But I get an error like this-
资产/脚本/LevelTapScript.cs(21,39):错误CS1612:无法修改"UnityEngine.Transform.position"的值类型返回值.考虑将值存储在临时变量中
Assets/Scripts/LevelTapScript.cs(21,39): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable
我的问题是如何使用我的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位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!