Search Unity

How to pick up item by pressing "E" when cursor is on item

Discussion in 'Getting Started' started by swineek, Aug 28, 2020.

  1. swineek

    swineek

    Joined:
    Aug 25, 2020
    Posts:
    10
    I have a function which picks up item but it does it whenever my cursor is and I want to make it only pickable when cursor is on it

    void Update()
    {

    if (Input.GetKeyUp(KeyCode.E))
    {
    GetComponent<Rigidbody>().useGravity = false;
    this.transform.position = theDest.position;
    this.transform.parent = GameObject.Find("Destination").transform;
    }
    }
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,555
    try..
    Code (CSharp):
    1. if (Input.GetKeyUp(KeyCode.E))
    2. {
    3.   if ((Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit)) && (hit.transform == transform))
    4.   {
    5.     GetComponent<Rigidbody>().useGravity = false;
    6.     transform.position = theDest.position;
    7.     transform.parent = GameObject.Find("Destination").transform;
    8.   }
    9. }
     
  3. swineek

    swineek

    Joined:
    Aug 25, 2020
    Posts:
    10
    Thank you :D
     
    adamgolden likes this.