How works IF

Hi, please explain how if(firstBG) works in this example, when it gives the truth?ths

public MeshRenderer firstBG;

private Vector2 savedFirst;

void Awake()
{
if (firstBG) savedFirst = firstBG.sharedMaterial.GetTextureOffset("_MainTex");
}
public MeshRenderer firstBG;

private Vector2 savedFirst;

void Awake()
{
    if (firstBG)
        savedFirst = firstBG.sharedMaterial.GetTextureOffset("_MainTex");
}

Firstly, use Code tags on the forum. firstBG will return true if it is not null. The below should be effectively the same thing, and is how I usually write it for clarity.

public MeshRenderer firstBG;

private Vector2 savedFirst;

void Awake()
{
    if (firstBG != null)
    {
        savedFirst = firstBG.sharedMaterial.GetTextureOffset("_MainTex");
    }
}
1 Like

Unity objects will return true if they are not null, and false if they are null.
The problem with that test is that it will only work for Unity objects so a c# object won’t work, but it is a good shortcut null test.

1 Like