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.
I have tried this code-
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-
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
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 :)
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;
}
Note that z pos will be 0 when you do this.
Two things:
One, for Unity questions, consider using https://gamedev.stackexchange.com/
Two, you can't directly set the position values of transforms. What you have to do is something like:
levelWindow.transform.position = new Vector3(xPos,yPos,0);
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.