单击时在 Unity 中生成单个对象

问题描述 投票:0回答:1

我想在点击屏幕时生成一个游戏对象。我试过使用循环,但它仍然实例化了不止一次。 在这里我也使用了其他循环并尝试将它也放在 Start 方法中......我已经关注了很多 youtube 视频但无法获得所需的输出。

[SerializeField]
GameObject spawnObject;

void Update()
{
    for (int i = 0; i < 1; i++)
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            GameObject g = Instantiate(spawnObject, (Vector2)touchPos, Quaternion.identity);
            //Debug.Log(i);
            Debug.Log(Input.mousePosition);
        }
    }
}

帮帮我……

unity3d spawn gameobject
1个回答
0
投票

Sooo,这是一个基于您当前代码的真正简单的解决方案,但它应该为您提供所需的功能😊我取出了 for 循环,因为我真的不明白为什么会在那里......如果需要它,请将其添加回去您没有与我们分享的内容;但请了解您描述的功能不需要它。

[SerializeField]
GameObject spawnObject;
private bool hasClicked;

void Update()
{
        if (Input.GetMouseButtonDown(0) && !hasClicked)
        {
            Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            GameObject g = Instantiate(spawnObject, (Vector2)touchPos, Quaternion.identity);
            hasClicked = true;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            hasClicked = false;
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.