Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Class null check returns null but class is not null

Discussion in 'Scripting' started by yuriythebest, Apr 30, 2023.

  1. yuriythebest

    yuriythebest

    Joined:
    Nov 21, 2009
    Posts:
    1,115
    Hi guys! I have a very weird issue and I don't know if it's to do with my programming or if this is a bug


    when I check if the class is null, it says yes but I can access its inner properties. How does c# handle checking if classes are null?


    classNull.png

    code in text form:
    Code (CSharp):
    1.  
    2.     SWATAI swatAI =     enemyGameObject.GetComponent<SWATAI>();
    3.  
    4.         OfficerInfo officerInfoRED = new OfficerInfo();
    5.         officerInfoRED.OfficerName="RED"+teamN;
    6.         officerInfoRED.GenerateRandomNonPlayerSquad();
    7.  
    8.         Debug.Log("ENEMYSPAWNER officerInfoRED="+teamN+"="+officerInfoRED);
    9.         Debug.Log("ENEMYSPAWNER officerInfoRED="+teamN+"="+ officerInfoRED.OfficerName);
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,717
    Unity overloads the bool operator for UnityEngine.Object items.

    Every C# item derived from UnityEngine.Object has two parts:

    - the C# side

    - the native engine side

    Tested for bool, if the engine side is destroyed, it will shoe as null.

    But the C# side still exists and fields that live entirely on the C# side can still be used.

    It's not a Good Idea(tm) to use them, but the entire C# object is still there.

    If you attempt to access a property like .gameObject or .transform it will blow up because those reach over to the native engine side, which in the case above has been destroyed, or else never existed in the first place.

    This is why you must NEVER use
    new
    to create MonoBehaviours. You may only use
    .AddComponent<T>()
    on a valid GameObject.

    You are being naughty on your second line of code, if your OfficerInfo derived in any way from UnityEngine.Object.
     
    yuriythebest likes this.
  3. yuriythebest

    yuriythebest

    Joined:
    Nov 21, 2009
    Posts:
    1,115
    I was about to answer how OfficerInfo isn't derived from monobehaviour, but then I double-checked and it was, due to reasons. You are very much correct and I am humbled by your amount of experience!
    thanks again!
     
    Kurt-Dekker likes this.