Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
211 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...