Y
Y
Yugg02020-11-29 18:09:18
Unity
Yugg0, 2020-11-29 18:09:18

Why doesn't null work in Unity?

In code:

public Text infoObjectText;

private void Update()
    {
        float dis = 3.5f;

        RaycastHit hit;

        if (Physics.Raycast(playerCamera.GetComponent<Camera>().transform.position, playerCamera.GetComponent<Camera>().transform.forward, out hit, dis))
        {
            InfoObject infoObject = hit.transform.GetComponent<InfoObject>();

            if (infoObject != null)
            {
                infoObjectText.enabled = true;
            }
            
            else if (infoObject == null)
            {
                infoObjectText.enabled = false;
            }
        }
    }


This piece of code doesn't work for me:
else if (infoObject == null)
{
      infoObjectText.enabled = false;
}


There is just one cube on the stage, with the "InfoObject" script. And when I point the center of the camera at the cube, "infoObjectText" turns on, and if I don't look, then "infoObjectText" does not turn off.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2020-11-29
@vabka

At you probably the component does not become null. Try another way.
PS: The code can be simplified toinfoObjectText.enabled = infoObject != null;

N
NevePMoPe, 2020-11-29
@NevePMoPe

Yes, I agree, try the method described above infoObjectText.enabled = infoObject != null;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question