Home > Software engineering >  changing the reticle if an object is intractable
changing the reticle if an object is intractable

Time:02-04

Im a beginner in Unity and im actually making a horror game,I recently added reticle into my game. I want to change the reticle if u can interact w an object (im using raycasts). Can someone check my code pls?

public Camera mainCam;
public LayerMask interactableLayerMask;
UnityEvent onInteract;
[SerializeField] GameObject reticle;
[SerializeField] GameObject interactReticle;


void Update()
{
    RaycastHit hit;

    if (Physics.Raycast(mainCam.transform.position, mainCam.transform.forward, out hit, 2, interactableLayerMask))
    {
        if (hit.collider.GetComponent<Interactable>() != false)
        {
            onInteract = hit.collider.GetComponent<Interactable>().onInteract;
            interactReticle.SetActive(true);
            reticle.SetActive(false);
            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                onInteract.Invoke();
            }
        }
        if (hit.collider == null)
        {
             interactReticle.SetActive(false);
             reticle.SetActive(true);            }
    }
}

CodePudding user response:

I would not rely on if (hit.collider == null). Physics.Raycast returns a bool to indicate if it hit something, see docs

bool Returns true if the ray intersects with a Collider, otherwise false.

Try something like this:

if (Physics.Raycast(...) {
    // your code for interaction
}
else {
    interactReticle.SetActive(false);
    reticle.SetActive(true); 
}

This could be then further optimised with a flag like hasInteractiveFocus to not set the active state of the game objects all the time.

  • Related