[英]Is there a way to only instantiate one instance of an object?
Currently, I am developing a recourse management game where the player can select a certain tool, fore example fire, and apply it to a tile.目前,我正在开发一个资源管理游戏,玩家可以在其中选择某种工具,例如火,并将其应用于瓷砖。 This script is supposed to check is the player clicks on a "Forest" tile with the fire tool, but it instantiates many meadow tiles and in the wrong location.这个脚本应该检查玩家是否用火工具点击了“森林”图块,但它实例化了许多草地图块并且在错误的位置。 How can I stop players from holding down click and only instantiate one object?如何阻止玩家按住单击并仅实例化一个对象? Also, if anyone knows why the tile is appearing above the hit objects transform, that would be appreciated.此外,如果有人知道为什么瓷砖出现在命中对象变换上方,那将不胜感激。
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;
}
}
Use Input.getMouseButtonDown(0) to check whether the left mouse button was clicked in this frame.使用 Input.getMouseButtonDown(0) 检查鼠标左键是否在该帧中被点击。 Your current method fires continuously while the button is held down, so you are spawning the object several times.您当前的方法在按住按钮时连续触发,因此您将多次生成对象。 I assume canClick was used to try to prevent this, so i removed it here.我认为 canClick 被用来试图防止这种情况,所以我在这里删除了它。 The Unity documentation has some more in-depth info on this. Unity 文档对此有一些更深入的信息。
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);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.