Hello
Could anyone please explain me how i have to instantiate a prefab at the current mouse position? I already know how to instantiate prefabs but what i don’t know is how to instantiate them at the currrent mouse position.
Thank you.
Hello
Could anyone please explain me how i have to instantiate a prefab at the current mouse position? I already know how to instantiate prefabs but what i don’t know is how to instantiate them at the currrent mouse position.
Thank you.
Get the current mouse position with Input.mousePosition, then convert that position to world space using Camera.ScreenToWorldPoint.
EDIT: Example in C#:
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 2.0f; // we want 2m away from the camera position
Vector3 objectPos = Camera.current.ScreenToWorldPoint(mousePos);
Instantiate(yourObject, objectPos, Quaternion.identity);
}
}
mousePos.z = 2.0; is this not float??
i mean: mousePos.z = 2.0f;
For anyone attempting to do this in C# is quite simple & works quite fine as of 4/13/20…
private Vector3 mousePos;
private Vector3 objectPos;
public GameObject yourPrefab;
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
mousePos = Input.mousePosition;
mousePos.z = 2.0f;
objectPos = Camera.main.ScreenToWorldPoint(mousePos);
Instantiate(yourPrefab, objectPos, Quaternion.identity);
}
}
}
I keep getting a error when i press the mouse:
NullReferenceException
UnityEngine.Camera.ScreenToWorldPoint (Vector3 position) (at C:/BuildAgent/work/6bc5f79e0a4296d6/Runtime/ExportGenerated/Editor/Graphics.cs:650)
Do you have any idea what this is?
This is my sript:
var testObject : Transform;
function Update ()
{
if (Input.GetButtonDown ("Fire1"))
{
var mousePos = Input.mousePosition;
mousePos.z = 2.0; // we want 2m away from the camera position
var objectPos = Camera.current.ScreenToWorldPoint(mousePos);
var myObject= Instantiate(testObject, objectPos, Quaternion.identity);
}
}