【问题标题】:Is there a way to only instantiate one instance of an object?有没有办法只实例化一个对象的一个​​实例?
【发布时间】:2020-10-13 16:39:20
【问题描述】:

目前,我正在开发一个资源管理游戏,玩家可以在其中选择某种工具,例如火,并将其应用于瓷砖。该脚本应该检查玩家是否使用开火工具单击了“森林”图块,但它实例化了许多草地图块并且位于错误的位置。如何阻止玩家按住点击并仅实例化一个对象?另外,如果有人知道为什么瓷砖出现在命中对象变换上方,那将不胜感激。

 void CheckMouseDown()
{

    if (Input.GetAxis("Fire1") != 0 && canClick == true)
    {
        print("yes");
        canClick = false;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        // Casts the ray and get the first game object hit
        Physics.Raycast(ray, out hit);
        if (hit.collider.gameObject.CompareTag("Forest"))
        {
            if (gamerule.gm.IsBurning == true)
            {
                Instantiate(meadow, hit.transform);

            }
        }
    }
    else
    {
        canClick = true;
    }
    
}

【问题讨论】:

  • 我认为你应该搜索的词是“Singleton”(这里有很多关于 SO 的帖子)。
  • 正如@GetOffMyLawn 提到的问题是你在它处于关闭状态时实例化它,你应该只在两种状态(按钮向上/按钮向下)之间转换时才这样做。

标签: c# unity3d instantiation


【解决方案1】:

使用 Input.getMouseButtonDown(0) 检查鼠标左键是否在该帧中被点击。您当前的方法在按住按钮时会连续触发,因此您会多次生成对象。我假设 canClick 被用来试图阻止这种情况,所以我在这里删除了它。 Unity documentation 对此有一些更深入的信息。

void CheckMouseDown()
{
    if (Input.GetMouseButtonDown(0))
    {
        print("yes");
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        // Casts the ray and get the first game object hit
        Physics.Raycast(ray, out hit);
        if (hit.collider.gameObject.CompareTag("Forest"))
        {
            if (gamerule.gm.IsBurning == true)
            {
                Instantiate(meadow, hit.transform);

            }
        }
    }
}

【讨论】:

    最近更新 更多