C# Destructor Errors

One of our programmers has discovered a problem since we upgraded to 3.3. He’s not gotten his forum account confirmation email so I’m posting this for him. We would appreciate any help we can get on this. Thanks in advance.

===================================================================================

To whom it may concern,

I’ve recently upgraded to version 3.3 of Unity 3d and am encountering errors with destructors that were working before the uprade. It appears the IDE is Instantiating and Destroying instances of the class without the scene being runned.

Create an empty project, include no standard assets. Create a new C# script and type up the following:
using UnityEngine;

public class TestInitialize : MonoBehaviour
{
~TestInitialize()
{
Debug.Log(“Destructor called”);
}
}

Attach this script to the empty game object that you created and run the scene. On my machine this yields:

Ending execution of the scene results in an additional call:

That has always been the case, Unity will call the constructor, and therefore Destructor afterward to be able to read the values to be input into the inspector. Otherwise it has no real way to determine the values setup by default initializers within the class. They may have refactored in which scenarios they call them however, with regards to MonoBehaviours, constructors and destructors have always been dangerous as they can be arbitrarily called by the editor when not running the scene.

You can use OnDestroy() function of MonoBehaviours to handle actual in game destruction code.

Thanks Ntero. We’ve never had an issue with this before, it’s only reared its head post 3.3 upgrade. We’ll look into OnDestroy().