简体   繁体   English

如何在鼠标 cursor 的 position 中生成预制件

[英]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.我想在 mousePosition 中生成一个“1+”。 The Problem is, that the Prefab is not spawning in the correct location.问题是,Prefab 没有在正确的位置生成。 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这是我的设置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.现在的问题是,如果我在按钮上单击您的代码,则文本不会在鼠标 position 中生成。 Its spawning alwasy in the center.它的产卵总是在中心。

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

Make sure you convert your mouse position from Screen to World cordinates with: Camera.ScreenToWorldPoint .确保将鼠标 position 从屏幕坐标转换为世界坐标: Camera.ScreenToWorldPoint

Here's a minimal example, the Creator script is added to an empty GameObject on the scene.这是一个最小的示例,将Creator脚本添加到场景中的空 GameObject 中。 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问题

This happens because when converting Screen to World coordinates, Unity takes the Camera Z position.这是因为在将 Screen 转换为 World 坐标时,Unity 使用 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:您可以在相机范围内手动分配 Z 值以避免这种情况:

Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0;
Instantiate(prefab, pos, Quaternion.identity);

Z = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM