Using and/or in an IF Statement for picking up objects within a game

Hey guys,
So I am trying to utilise an and in my if statement and I’m having problems with it.

What I want it to do is:

  • Once the player has collided (become in range with an object) with a book:
  • Check to see if it is really the book AND he has pressed the “e” key to pick it up.
  • Then execute the following…

Now I get no errors at all on runtime so that good, but it just INSTANTLY destroys the book object before even pressing the E key.

It’s just that this particular part in the code I suggest is the culprit:

  if(other.gameObject == book | Input.GetKeyDown("e"))

And for reference this is my whole code:

using UnityEngine;

public class ObjectPickup : MonoBehaviour
{
    public float bookweight = 1.2f;

    GameObject book;

    void Awake ()
    {
    }

    void Start () {
        book = GameObject.FindGameObjectWithTag ("book");
    }

    void OnTriggerEnter (Collider other)
    {
        if(other.gameObject == book | Input.GetKeyDown("e"))
        {
            ScoreManager.currentweight += bookweight;
            Destroy(other.gameObject);
        }
    }
}

That isn’t the syntax for and, and is &&
Or is ||

Ok awesome, thank you very much!

I’ve tried this now:

if(other.gameObject == book && Input.GetKeyDown("e"))

And when I press the e key NOTHING happens. Know why? :slight_smile:

Appreciate the help.

OnTriggerEnter only fires in the first frame the collision happens, GetKeyDown only fires in the first frame the key is pressed. You would need to hit the button in the exact frame the collision first occurs for it to work…

Consider GetKey and OnTriggerStay.

1 Like

Awesome, it worked!

Here is the working code below for anyone in the future who wants to implement a pick-up system in their game (perhaps not the most efficient solution :P)

using UnityEngine;

public class ObjectPickup : MonoBehaviour
{
    public float bookweight = 1.2f;
   
    GameObject book;
   
    void Awake ()
    {
    }
   
    void Start () {
        book = GameObject.FindGameObjectWithTag ("book");
    }
   
    void OnTriggerStay (Collider other)
    {
        // If the entering collider is the book...
        if(other.gameObject == book && Input.GetKey("e"))
        {
            ScoreManager.currentweight += bookweight;
            Destroy(other.gameObject);
        }
    }
}
1 Like