True does not equal true

Hello,I was able to break boolean algebra in Unity.

private static void BoolField(string label, bool value, bool configValue, Action<bool> onChange,
    bool disabled = false)
{
    var modified = value != configValue;
    if (label == "Test Version") Debug.Log($"{label}: value: {value}, config: {configValue}, modified {modified}");

resulted in printing:

Test Version: value: True, config: True, modified True

Turns out configValue came from a ScriptingObject loaded from an asset where a field TestVersion used to be an int (with value 5) but now it is a bool. configValue.GetType() gives System.Boolean and it was not boxed, it was simply a broken value and set the entire program into an error state.

The issue was that Unity can deserialize a 5 as a bool which yields a C# property that looks like true, but isn’t quite.

I could fix it by unchecking and checking the checkbox of the asset in Unity, overwriting the 5 with a 1. But is was really hard to find.

I nominate you for a Nobel price in .. uh … can we have a Nobel price for Serialization? :wink:

How bool are represented numerically in C# is an implementation detail that may change between platforms.

Though technically, this should be true:

A CLI Boolean type occupies 1 byte in memory. A bit pattern of all zeroes denotes a value of false. A bit pattern with any one or more bits set (analogous to a non-zero integer) denotes a value of true.

However, this value also passes through Unity’s C++ layer during deserialization (and possibly endianness conversions) so no idea how that might change things, but I’m almost certain it wouldn’t be a problem in pure C# if you cast a “5” byte using unsafe to bool.

Please post enough code so that we can reproduce the issue on our end. Code speaks louder than a paraphrase.

Wow, OP wasn’t kidding. Please check my work… I did it in Unity6000.0.27f1 just now.

If this was only in IL2CPP it wouldn’t be quite as surprising. This is just in editor.

First the program.

// @kurtdekker
// recreating: https://discussions.unity.com/t/true-does-not-equal-true/1690793

// step 1 - get this serialized as an non-1 int (save it in the scene)

#define STEP1

// step 2 - comment out the line above and press run.

// note how the Variable is checkmarked (X) true in the inspector
// note how it compares false below

using UnityEngine;

public class TrueNotTrue : MonoBehaviour
{
#if STEP1
	public int Variable = 5;
#else
	public bool Variable;

	void Start()
	{
		bool troo = true;

		Debug.Log($"troo == {troo} and Variable == {Variable}... equality is {troo==Variable}");
	}

#endif
}

First pass , with #define STEP1, place on GameObject and save this in a scene:

Now recompile with #define STEP1

Now observe scene without resaving… Note Variable is true

And press PLAY…

Playing more with the serialization, toggling something else in the scene and resaving does not write the correct 0 / 1 boolean. You have to actually toggle that bool in the inspector, then the underlying backing data becomes 1 / 0

Would be nice to see a print of the actual bit representation of each value for each step. I recall there are ways to do “unsafe casts” or something to that effect which doesn’t alter the underlying bits.

I’m sure the underlying values are either 1 or 5 in the case above… what surprises me is that C#, which one might argue is “modern,” would allow two different representations of true to not test the same.

Oldskool C does not guarantee this, as it is just integers after all, but you can achieve the same thing by dual nots in your comparison to “sanitize” the integers into bools before comparison:

#include <stdlib.h>
#include <stdio.h>

int	main( int argc, char **argv)
{
	int bool1 = 1;
	int bool2 = 2;

	if (!bool1 == !bool2)
	{
		printf( "same bool\n");
	}
	else
	{
		printf( "different bool\n");
	}
	return 0;
}

If I was doing a lot of that stuff I would probably make a C macro…

#define CMP_BOOL(A,B) (!(A)==!(B))

I’m sorry if my reply sounds like that. I was just reminding them that their actual code is more helpful. Because we can’t reliably compose test code on our site with just their description of the code.

In modern .Net you have Unsafe.BitCast but in Unity you’ll have to do with MemoryMarshal.Cast:

using System.Runtime.InteropServices;
var nonstandardBool = MemoryMarshal.Cast<int, bool>(new int[1] { 5 })[0];
Debug.Log($"nonstandardBool is {nonstandardBool}, `nonstandardBool == true` is {nonstandardBool == true}");
// Logs: nonstandardBool is True, `nonstandardBool == true` is False

I guess it comes down to a performance question. .Net guarantees the internal consistency of the language, you cannot create one of these bools without resorting to unsafe or marshaling methods. Should .Net slow down the equality comparison for almost all booleans for the rare edge case where data is marshaled incorrectly?

It’s up to the code interfacing with the runtime that needs to make sure the data it loads into it matches the expectations. Here in this case, it’s up to Unity to make sure the data it loads into the runtime matches its rules.

Thanks, I understand the issue now. It looks like a bug to me. Do you mind reporting it to Unity?

This is less of a bug and more of a result of how C# defines and handles booleans during serialization. I modified Kurt’s code to inspect the underlying byte values of booleans before and after conversion.

// step 1 - get this serialized as an non-1 int (save it in the scene)

#define STEP1

// step 2 - comment out the line above and press run.

// note how the Variable is checkmarked (X) true in the inspector
// note how it compares false below

using System;
using UnityEngine;
using UnityEngine.Rendering;

public class TrueNotTrue : MonoBehaviour
{
#if STEP1
	public int Variable = 5;
#else
	public bool Variable;

	void Start()
	{
		bool troo = true;

		int trooInt = Convert.ToInt32(troo);
		int VariableInt = Convert.ToInt32(Variable);
		bool result = troo == Variable;
		int resultInt = Convert.ToInt32(result);
		
		Debug.Log(trooInt); // 1
		Debug.Log(VariableInt); // 1
		Debug.Log($"troo == {troo} and Variable == {Variable}... equality is {result}"); // true, true, false
		Debug.Log(resultInt); //0 

		int anInteger = 42;
		bool convertedInteger = Convert.ToBoolean(anInteger);
		int revertedInteger = Convert.ToInt32(convertedInteger);
		
		Debug.Log($"An integer: {anInteger}, converted Integer: {convertedInteger}, reverted Integer: {revertedInteger}"); // 42, true, 1
		Debug.Log($"Comparing Variable to true: {Variable.CompareTo(true)}"); // 1 !!!!!!!
		Debug.Log($"Comparing troo to true: {troo.CompareTo(true)}"); // 0 
		
		unsafe
		{
			bool value = Variable;
			bool* boolPtr = &value;
			byte* bytePTr = (byte*)boolPtr;
			byte boolByte = *bytePTr;
			Debug.Log($"Underlying value of Variable: {boolByte}"); // 5

			bool resultValue = result;
			bool* resultPtr = &resultValue;
			byte* byteResultPTr = (byte*)resultPtr;
			byte boolResultByte = *byteResultPTr;
			Debug.Log($"Underlying value of result: {boolResultByte}"); // 0

			int anIntegerValue = anInteger;
			int* anIntegerPtr = &anIntegerValue;
			byte* anIntegerBytePtr = (byte*)anIntegerPtr;
			byte anIntegerByte = *anIntegerBytePtr;
			Debug.Log($"Underlying value of anInteger: {anIntegerByte}"); // 42 
			
			bool convertedIntValue = convertedInteger;
			bool* convertedIntPtr = &convertedIntValue;
			byte* byteConvertedInt = (byte*)convertedIntPtr;
			byte convertedIntByte = *byteConvertedInt;
			Debug.Log($"Underlying value of converted Integer: {convertedIntByte}"); // 1
		}
	}

#endif
}

Here’s the result of my findings:

  1. C# treats any underlying value of zero for a bool as false, and unlike C/C++ any nonzero value as true (C/C++ only treats 1 as true, while other nonzero values are undefined).

  2. Because C# is strongly typed and doesn’t allow explicit or implicit casts from integer types to bool, it performs the check by comparing the underlying byte value for equality.

  3. Despite point 1, whenever there’s a conversion from an integer type to bool, C# changes the underlying value to 1 if the integer is nonzero. This ensures that boolean equality checks produce consistent results and that’s why it uses what is described in 2 for comparison

  4. If, for external reasons, the underlying value of a bool becomes something other than 1, it’s still considered true, not undefined. This can occur due to low-level byte manipulation or serialization issues, as in this case.

  5. The problem with point 4 is that when this happens, the equality operator may not yield the correct result. Any internal conversion in C# would have normalized a nonzero integer to 1 during a bool conversion.

  6. In cases where point 5 occurs, the correct result can be obtained using the CompareTo() method. In the example above, troo.CompareTo(true) returns 0 (meaning equal), while Variable.CompareTo(true) returns 1, meaning Variable is greater than true (5 > 1).

Really interesting findings, although it is fabulously niche.

And that’s just for the true and false values. What’s even more niche and strange is that C# also defines true and false operators that can be overloaded independently, they don’t have to be complementary. This means we can create a type that is true, false, or neither, similar to a nullable boolean.

Even more bizarre, we can design a type that can be true, false, or both true and false at the same time.

I’m not sure how such a type could be useful, except maybe to represent quantum objects that exist in superposition. My blog post where I create a Schrödinger’s cat example is probably my least read one, but it’s also the one I enjoyed writing the most. Here’s the link if anyone is curious about some really weird boolean logic in C#: A Deep Dive Into Boolean Operator Overloading - C# and Unity development

No apology necessary! I agree that code to demonstrate a problem is always best.

I’m surprised too. I get that its an edge case because Unity is “slanging” a five into that slot by some magic of its deserialization.

But it even seems like that simply shouldn’t be possible with a bool.

But I get that performance would suffer, since extra checks would need to happen and a straight copy is always gonna be faster.

I cut my teeth on 6502 assembly language where generally you used the Z flag (set if all bits were 0, cleared if any were 1) to determine true/false.

  ; in 6502 the simple act of loading conditions the Z flag
  LDA MyVariable
  BNE VariableIsTrue

And in less RISC-y chips (eg, 8080/85/Z80/x86) it needed an explicit OR with itself to drive CPU flags.

  LD A,MyVariable
  OR A         ; necessary to condition Z flag to contents of A
  JP NZ,VariableIsTrue

I guess ARM doesn’t implicitly set flags but they have so many different varieties of test-and-branch, I haven’t even tried to keep up!

And of course in C you just check everything that way: integers, pointers, etc.

Hello and thanks for showing interest!

I did make a dummy program to showcase the issue and created a bug report (IN-121175).

Since I already found a work-around I just thought I might make a post here explaining when the issue can appear and how to fix it, in case someone else has the same problem and searches here before the issue has been resolved by Unity.

I couldn’t think of a concise way to describe this in code since it requires code changes to appear, but @Kurt-Dekker was able to do this nicely here: True does not equal true - #4 by Kurt-Dekker

I marked it as a Solution so people can find it more easily!

You can also use a struct with layout explicit and a field offset for each field:

[StructLayout(LayoutKind.Explicit)]
public struct Cast_Bool_Int
{
    [FieldOffset(0)] public int integer
    [FieldOffset(0)] public bool boolean;
}

With FieldOffset we can actually let the fields “overlap” the same memory area. Note that this does only work with value types. The CLR / compiler will complain when you try to mix in reference types as this would be potentially catastrophal since the value of a reference type is the reference / pointer.

Though back to the topic, Unity really should fix this “bug”. Though it’s probably easier said than done. Unity’s internal serializer on the C++ side is extremely optimised. It’s of course not possible to fix all serialized values when the class definition changes. So that leaves only the deserializer who could do the fixing. Though for performance reasons they probably don’t do much type checking. Unity could do a type sanity check when building.

I guess the designers of C# put their trust in the proper handling of the type bool higher up and that usually works fine. The alternative would be that literally every boolean operation requires something like a (val & 1) before further processed. So the CLR assumes that boolean values are always 0 or 1. That’s generaiily true as the usual runtime safeguards does not allow other values assigned. You have to use either a lowlevel / unsafe trick to mess this up. So the responsibility is on the serializer in this case to get it “right”.