Unity ignoring mouse position in favor of player position?

I’m creating a Sim City/City Skylines style game. I am trying to allow the player to place a building at the mouse position, however the buildings always appear at the player’s position, not the mouse position. I have no idea what’s going on. As far as I know, my building place script should not allow this.

Here is the code of my BuildingPlaceHandler.cs:

public class PlaceBuildingHandler : MonoBehaviour {

public GameObject AVGNApartments;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

    if (Input.GetMouseButtonDown(0))
    {

        var worldMousePosition = Camera.main.ScreenToWorldPoint(new 
Vector3(Input.mousePosition.x, 30, Input.mousePosition.z));
        
        Instantiate(AVGNApartments, worldMousePosition, gameObject.transform.rotation);

    }
}
}

Note: 30 is the height of my terrain.

Why is it placing buildings at the player vs. the mouse position?

“ScreenToWorldPoint” expects a screenspace coordinate. Screen space uses 2d coordinates in the x-y plane. The z value you pass to ScreenToWorldPoint will determine how far away the point should be from the camera.

So the vector that you’re passing doesn’t make any sense. You use a fix y position that is close to the bottom of the screen (screen space 0,0 is the bottom left corner of the screen). As distance from the camera you use “Input.mousePosition.z” which makes no sense as “mousePosition” is only a 2d position and z is always 0.

Note that if you don’t know the distance from the camera you probably want to use a raycast against the terrain to get the position on the terrain surface.