#Unity does not detect some mouseclicks and key presses at random

1 messages · Page 1 of 1 (latest)

rough ember
#

In the project i am working on i have made it so you can collect items by clicking on a certain game object via this code
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D raycastHit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
if (raycastHit.collider!=null)
{
string ItemClass=raycastHit.transform.gameObject.tag;
Collect(ItemClass);
}
}
The Collect() function looks like this
void Collect(string objTag)
{
int n=0;
foreach (string tag in RenewableTags)
{
if (tag==objTag)
{
ItemsCount[n]++;
InventoryTexts[n].text=ItemsCount[n].ToString();
n=0;
}
n++;
}
}
If the tag of the gameobject clicked is in "RenewableTags" you can just keep clicking on it to gather as many items as you would like. The problem is that for apparently no reason a good number of times it fails to recognize objTag is in Renewable tags. If you click on the same point of an object 10 times it will only give you about 6 items. Similar errors happen for other functions that use key inputs. Is it a system, editor or programming error?
(i am using unity 2021.3.6f1 btw)

hard gust
#

The most common cause for this issue is that you are querying input from the wrong context.

When checking Input.Get...Down and Input.Get...Up, make sure you do it from inside Update.

rough ember
hard gust
#

You can also separate input checks into your own methods - as long as those are called from Update.

This is because the ...Up and ...Down methods only return true for a single frame after the key is initially pressed. Update runs every frame and thus will catch that reliably. FixedUpdate does not run every frame, so you will experience input loss when checking for frame-perfect inputs inside it.

rough ember
#

Can i have an update and fixedupdate in the same script?

hard gust
#

of course

rough ember
#

Nice

#

Thank you a lot!