Make sure you convert your mouse position from Screen to World cordinates with:
Camera.ScreenToWorldPoint.
Here's a minimal example, the Creator
script is added to an empty GameObject on the scene. A prefab is manually assigned on the Editor.
public class Creator : MonoBehaviour
{
public GameObject prefab;
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Instantiate(prefab, Camera.main.ScreenToWorldPoint(Input.mousePosition), Quaternion.identity);
}
}
}
This assumes you have a single Ortographic Camera in your scene.
With this approach, objects don't appear on the game view, only on the scene:
This happens because when converting Screen to World coordinates, Unity takes the Camera Z position. So the prefabs are created right on top of the camera, and are not rendered. You can manually assign a Z value inside the camera range in order to avoid that:
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0;
Instantiate(prefab, pos, Quaternion.identity);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…