Last Updated: February 25, 2016
·
570
· pekalicious

Beware of object initializers in Unity3D

using System;
using UnityEngine;

public class ObjectInitializer : MonoBehaviour
{
    public string[] names = { "Hello", "World" };

    void Start()
    {
        Debug.Log("Name: " + GetName(new Settings { mySetting = 1 }));
        Debug.Log("Name: " + GetName(new Settings { mySetting = 0 }));
    }

    private string GetName(Settings sett)
    {
        if (sett.mySetting == Settings.INVALID_SETTING)
            throw new Exception("Error: Setting not set");

        return names[sett.mySetting];
    }
}

public class Settings
{
    public const int INVALID_SETTING = -1;

    public int mySetting = INVALID_SETTING;
}

The second GetName call throws an exception because the mySetting = 0 is removed during compilation. The reason for that removal is probably because 0 is the default value for int, and thus it is assumed that it can be ignored. This would be the same case if mySetting was a boolean that was defaulting to true, but the object initializer was attempting to set it to false, since false is the default value for booleans.

This is not the case for "normal" Mono or .NET.

This is still true as of Unity3D 4.3.4f1