Answer the question
In order to leave comments, you need to log in
How to create a game object on the stage in the coordinates of the cursor position?
Hello. Using Instantiate I create an instance of an object (Circle) on the stage (By clicking the left mouse button), I assign the coordinates to Input.mousePosition. The object appears miles away from where I clicked. Project 2d.
using UnityEngine;
public class SnotCreater : MonoBehaviour
{
public GameObject Circle;
public GameObject CirclePrefab;
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Circle = Instantiate(CirclePrefab, Input.mousePosition, Quaternion.Euler(0,0,0)) as GameObject;
}
}
}
Answer the question
In order to leave comments, you need to log in
The mouse position is in the screen coordinate system, and you create the prefab in the world coordinate system.
To convert the mouse position to the world coordinate system, use the
Camera.main.ScreenToWorldPoint() method.
using UnityEngine;
public class SnotCreater : MonoBehaviour
{
public GameObject Circle;
public GameObject CirclePrefab;
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Circle = Instantiate(CirclePrefab, mousePos, Quaternion.Euler(0,0,0)) as GameObject;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question