I tried both
if(object)
and
if(object != null)
but if it doesn’t exist Unity always throws an exception, is it normal?
I tried both
if(object)
and
if(object != null)
but if it doesn’t exist Unity always throws an exception, is it normal?
Second version is more correct, but it should not thow an exception.
object is a reserved keyword. so post your original code that we can have a closer look.
also there is some ambiguity between null for the unity managed objects (c++ side) and those in your code. look here for example: Components and GameObject evaluate == to null after destroyed, except w/ interfaces? - Unity Engine - Unity Discussions
Object was an example of course
if (secondaryWeaponExists.secondaryWeapon != null)
{
if (Input.GetKeyDown(KeyCode.Alpha2) && !keyPressed)
{
StartCoroutine(waitForSwitch());
weaponActive = !weaponActive;
}
}
I assume secondaryWeaponExists does not exist. Therefore, secondaryWeaponExists.secondaryWeapon throws an error because you are trying to access something which is null.
Uhm what if secondaryWeapon is static?
As long as secondaryWeaponExists is an instance and that instance is null, you can not access any of its members.
If you are trying to check a static variable use the class name rather than the instance.
Thanks.
Just add one more check:
if (secondaryWeaponExists != null && secondaryWeaponExists.secondaryWeapon != null)
{
...
}
Thanks!