George B George B - 3 months ago 15
C# Question

How do I assign a GameObject's x and y position?

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 :)

Answer

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.

Comments