Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c# - How to spawn a prefab in the position of the mouse cursor

Instantiate(clickPrefab, Input.mousePosition, Quaternion.identity);

 
 

this is the code what im using. I want to spawn a "1+" in the mousePosition. The Problem is, that the Prefab is not spawning in the correct location. In the scene view its spawning correct in the game view its spawning totaly random...

 void scoreButtonOnClick()
{
    Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    pos.z = 0;
    Instantiate(clickPrefab, pos, Quaternion.identity);
    money += dpc;
    scoreText.text = money.ToString("#.##");
}`

this is my setup https://i.imgur.com/NOtcITN.png

the Problem is now if I click with your code on my button the text is spawning not in the mouse position. Its spawning alwasy in the center.

https://i.imgur.com/niS3Pzt.png

question from:https://stackoverflow.com/questions/65837818/how-to-spawn-a-prefab-in-the-position-of-the-mouse-cursor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Z problem

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);

Z = 0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...