Search Unity

Issue with Item Pickup

Discussion in 'Scripting' started by Kal3b, Jul 8, 2019.

  1. Kal3b

    Kal3b

    Joined:
    Apr 15, 2019
    Posts:
    14
    Hey, Currently I'm building a FPS Type Game. When the player Collides with a pick up object (Such As AK47) A pop up message appears saying "press E to Equip." I thought if I add a Boolean value for when the player collides with an object that when the bool = true and E is pressed the "Wild" AK would be hidden and the Inventory AK would appear however they just stay the same.
    Any help would be highly appreciated as I'm only fairly new to unity.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PickUpFinder : MonoBehaviour
    6. {
    7.     public GameObject MessagePanel;
    8.     private bool AKavailable = false;
    9.     public GameObject AK;
    10.     public GameObject invAK;
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.        
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         if (Input.GetKeyDown(KeyCode.E) && !AKavailable)
    22.         {
    23.             Debug.Log("E");
    24.             AK.SetActive(false);
    25.             invAK.SetActive(true);
    26.         }
    27.     }
    28.  
    29.     private void OnCollisionEnter(Collision collisionInfo)
    30.     {
    31.         if (collisionInfo.collider.tag == "PickUp")
    32.         {
    33.             MessagePanel.SetActive(true);
    34.             AKavailable = true;
    35.         }
    36.     }
    37.  
    38.     private void OnCollisionExit(Collision collisionInfo)
    39.     {
    40.         if (collisionInfo.collider.tag != null)
    41.             MessagePanel.SetActive(false);
    42.             AKavailable = false;
    43.     }  
    44.  
    45. }  
     
  2. Antony-Blackett

    Antony-Blackett

    Joined:
    Feb 15, 2011
    Posts:
    1,778
    Should !AKavailable actually be AKavailable in the Update if statement?
     
  3. Kal3b

    Kal3b

    Joined:
    Apr 15, 2019
    Posts:
    14
    Making AKavailable = true works however you can press E from anywhere to pick it up
     
  4. Antony-Blackett

    Antony-Blackett

    Joined:
    Feb 15, 2011
    Posts:
    1,778
    You can press E anywhere because you are testing for !AKavailable (not AKavailable)

    Code (csharp):
    1.  
    2. if( (Input.GetKeyDown(KeyCode.E) && !AKavailable )
    3.  
    That means when AKavailable is false it will work. When you're standing on the AK and it's true it will not work.

    Remove the ! (not) from the if statement.

    Code (csharp):
    1.  
    2. if( (Input.GetKeyDown(KeyCode.E) && AKavailable )
    3.  
     
    Last edited: Jul 8, 2019