Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...