Search code examples
c#unity-game-engineassert

Why the Debug.Assert show the error message even if the Length is 1 all the time?


private GameObject GetDoorShaderPrefab()
    {
        string[] shieldPrefab = AssetDatabase.FindAssets(c_doorShieldFxLocked);
        Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");
        string shieldGuid = shieldPrefab[0];
        string prefabPath = AssetDatabase.GUIDToAssetPath(shieldGuid);
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
        Debug.Assert(prefab != null, "Expected prefab to load");
        return prefab;
    }

I used a break point on the line :

Debug.Assert(shieldPrefab.Length != 1, "Expected exactly 1 shield like this...");

The Length of shieldPrefab is all the time 1 but it's still showing the error message "Expected exactly 1 shield like this..."

The method GetDoorShaderPrefab is being called many times in other place in the script. But each time the Length is 1 and it keep showing the error message.


Solution

  • I think your condition should be == 1 so:

    Debug.Assert(shieldPrefab.Length == 1, "Expected exactly 1 shield like this...");
    

    The message is displayed when the condition is false. From the docs:

    Assert(Boolean, String)

    Checks for a condition; if the condition is false, outputs a specified message and displays a message box that shows the call stack.

    The idea is that the asserts checks some conditions and it will only complain is your assertion is wrong.

    To remember it easily, the condition and text should tell you the same, not the opposite.