Search Unity

Raycast and GUI

Discussion in 'Scripting' started by JanKybe, Jun 4, 2018.

  1. JanKybe

    JanKybe

    Joined:
    Nov 10, 2017
    Posts:
    1
    Hi, i have a problem with Raycast and GUI i made simple pickup script for items and i wanna show GUI text.

    I made GUI text and it gets enabled as soon as raycast hits target tagged pickupable but if i look away i want that text to dissapear but that GUI text wont dissapear somewhy.

    My question is how can i disable GUI if raycast doesnt hit pickupable item

    Code (CSharp):
    1. if (Physics.Raycast (transform.position, transform.forward, out hit)) {
    2.             if (hit.distance < 2) {
    3.                 if (hit.collider.gameObject.tag == "Pickupable") {
    4.                     GUI.SetActive (true);
    5.                     if (Input.GetKeyDown ("e")) {
    6.                         hit.collider.gameObject.SetActive (false);
    7.                         CollectSound.Play ();
    8.                     }
    9.                 } else if (hit.collider.gameObject.tag != "Pickupable") {
    10.                     GUI.SetActive (false);
    11.                 }
    12.             }
    13.         } else {
    14.             GUI.SetActive (false);
    15.         }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You have an "if" clause for an object being less than two, but you probably need an else clause for it where you set the GUI to false.
     
    JanKybe likes this.
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I tested the code and it's mostly working for me. However, when the hit object is more than 2 away it doesn't change.
    I made a few small changes and came up with this.
    Code (csharp):
    1. public class Test8 : MonoBehaviour {
    2.  
    3.     [SerializeField]
    4.     GameObject text;
    5.  
    6.     void Update()
    7.     {
    8.         RaycastHit hit;
    9.         bool shouldShow = false;
    10.  
    11.         if (Physics.Raycast(transform.position, transform.forward, out hit))
    12.         {
    13.             if (hit.distance < 2)
    14.             {
    15.                 if (hit.collider.CompareTag("Pickupable"))
    16.                 {
    17.                     shouldShow = true;
    18.  
    19.                     if (Input.GetKeyDown(KeyCode.E))
    20.                     {
    21.                         hit.collider.gameObject.SetActive(false);
    22.                         CollectSound.Play();  // I don't have this, so commented it out.
    23.                     }
    24.                 }
    25.             }
    26.         }
    27.  
    28.         text.SetActive(shouldShow);
    29.     }
    30. }