I know this question has been answered many times, but no matter what I do, the object keeps instantiating at the middle of the screen, but slightly towards where my mouse is. Here’s what I’ve tried.
This is the best way I’ve found so far to transform from mouse screen pixel point to world point, the key here is to add depth to the pixel coordinates and then remove that depth after transforming to world coordinates.
Add this class to a gameobject, assign a prefab, hit play and (if you got an orthographic camera setup) you should be able to instantiate that prefab on the position where you pressed your left mouse button.
using UnityEngine;
public class InstantiateOnMousePosition : MonoBehaviour
{
public GameObject prefabToInstantiate;
private Camera _Camera;
private void Awake()
{
// Store your camera on Awake (better performance).
_Camera = Camera.main;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Store current mouse position in pixel coordinates.
Vector3 mousePixelPos = Input.mousePosition;
// Add depth so it can actually be used to cast a ray.
mousePixelPos.z = 20f;
// Transform from pixel to world coordinates
Vector3 mouseWorldPosition = _Camera.ScreenToWorldPoint(mousePixelPos);
// Remove depth
mouseWorldPosition.z = 0f;
// Spawn your prefab
Instantiate(prefabToInstantiate, mouseWorldPosition, Quaternion.identity);
}
}
}
Thanks to @tadadosi, I was able to get a script that should work for whatever setup you have. As they said you have to add depth to the mouse position to get the true worldposition, but it shouldn’t be any arbitrary number or else it may not work as needed. Instead, use the absolute of your camera’s z position
using UnityEngine;
public class Builder : MonoBehaviour
{
public GameObject go;
Camera cam;
public void Awake()
{
cam = Camera.main;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 worldPoint = Input.mousePosition;
worldPoint.z = Mathf.Abs(cam.transform.position.z);
//worldPoint.z = 11f;
Vector3 mouseWorldPosition = cam.ScreenToWorldPoint(worldPoint);
mouseWorldPosition.z = 0f;
Instantiate(go, mouseWorldPosition, Quaternion.identity);
}
}
}