Prevent object creation using new ()

In the Unity game engine, all classes derived from the MonoBehaviour class cannot be constructed using the new () operator, despite the fact that their default constructors are public. This returns a warning in the Unity log and no object is created, leaving the pivot zero.

I'm curious how they managed to prevent the object from being created when the constructor was called. I did some research and heard that an exception from the object constructor might prevent it from being created, so I tried it myself and it worked when the exception was handled outside of the constructor. However, I still don't understand how they actually instantiate the class using the correct ( AddComponent<T>()

) method .

Any ideas?

+3


source to share


1 answer


In plain vanilla C #, the operator new

cannot return null

. It will either return a valid non-empty reference or 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 customized for their own purposes.



Compiler and runtime control means you can do various non-standard things. For example, provide a mechanism to allow an operator to new

return null

a result if used with an invalid type (i.e., any subclass MonoBehavior

). And, for example, provide an alternative distribution mechanism that can be used AddComponent<T>()

.

A detailed description of the inner workings of all of this would be too broad for Stack Overflow (and I don't know the specifics head-on anyway). But given that Mono is open source, my guess is that the license is one that requires the Unity modifications of that open source to be available as well. That is, if you really wanted to know all the little things, you can just look at the actual source code and see how they do it in particular.

+4


source







All Articles