user4148144
user4148144

Reputation:

Prevent Construction of object using new()

In the Unity game engine, all classes deriving from a MonoBehaviour class cannot be constructed with the new() operator, despite their default constructors being public. Doing so returns a warning in the Unity log and the object is not instantiated, leaving the reference null.

I'm curious how they managed to prevent the object from being created when the constructor is called. I did some research and heard that throwing an exception in the object's constructor can prevent its creation, so I tried it out myself and it worked when the exception was handled outside the constructor. However, I still do not understand how they actually instantiate the class using the correct method (AddComponent<T>()).

Any ideas?

Upvotes: 2

Views: 478

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70691

In plain vanilla C#, it is not possible for the new operator to return null. It will either return a valid non-null reference, or it will throw an exception.

Note, however, that Unity is not "plain vanilla C#". Unity is based on Mono (which in turn is based on .NET), but is customized for their own purposes.

Having control over the compiler and runtime means you can do a variety of non-standard things. Like, provide a mechanism to allow the new operator to return null as a result if it's being used with an invalid type (i.e. any subclass of MonoBehavior). And, for example, to provide an alternate allocation mechanism that AddComponent<T>() can use.

A detailed description of the inner workings of all this would be too broad for Stack Overflow (and I don't know the specifics off the top of my head anyway). But given that Mono is open-source, I assume the license is one of those that requires Unity's modifications of that open-source to also be made available. I.e. if you really wanted to know all the nitty gritty, you could just browse the actual source code and see how they do it, specifically.

Upvotes: 2

Related Questions