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. 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. The Unity documentation has some more in-depth info on this.
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);
}
}
}
}