#Issue with raycast hitting multiple objects of the same type.

1 messages · Page 1 of 1 (latest)

slim girder
#

So, I'm trying to make a system where you can pick up items by simply clicking on them from a given distance. The problem is that no matter what I tried with a Physics.Raycast, it will always check for ALL of the objects in the given raycast. In cases where I line myself up with a line of items, I end up picking everything up in the given range.

Here's the code I'm working with:

{
    if (hit.transform == base.transform && Input.GetMouseButton(0))
    {
        if (gc.CheckInvSize() != 8)
            transform.gameObject.SetActive(false);
        else if (gc.item[gc.itemSelected] == 22)
            durability = gc.itemDurability[gc.itemSelected];
        this.gc.CollectItem(GetID(item), this);
    }
}

Is there a way to have the raycast only detect the first object it collides with?

sharp dune
#

well your inner check is true when left mouse is held so its going to probably execute for a few frames and thus pick up many things...

#

I am also confused why you perform the raycast and then check if left mouse is held (wasteful)

#

It should be:

  • detect input was pressed
  • do raycast
  • try to pickup item

if you detect only when the button/mouse button was pressed it executes on that frame only

proud harness
#

You need to either:

  • just not run this code if you're already holding something
  • use GetMouseButtonDown instead of GetMouseButton
slim girder
#

Ohhhh, I see. That makes sense. I forgot to mention that setting it to GetMouseButtonDown solves the problem, but there’s still a rare chance that it’ll grab multiple items. I’m doing my this in the Update() Method, so would it make more sense to put it in FixedUpdate() instead?

proud harness
#

Or you're clicking twice

slim girder
#

Ohhhh, ok, I think I know what’s wrong in that case, this code is running inside the items themselves, so that seems to add up. When I get back home I’ll try and move it into the player script

sharp dune
#

yea that would be a MUCH better place for it