- Home /
How to access useful Unity Editor/Engine internal methods?
I was trying to figure out how to manipulate a sprite image, so I looked at the code for the Sprite Editor. I noticed that it accessed some internal Unity Editor methods, including the one I really wanted: UnityEditor.SpriteUtility.CreateTemporaryDuplicate
.
The Unity 2D methods seem to have no problem accessing these internal methods through an InternalBridge
class. But when I copy over the code, including the assembly def's and assembly info's, I still get errors saying unable to access due to protection level.
Unity packages can do it, why can't I?
Answer by sacredgeometry · Apr 01 at 10:01 PM
Decompile unity and recompile it with looser access modifiers?
Sounds like a bad idea? Yeah thats why they are internal. They arent meant to be used by you.
Answer by ThomasODell · Apr 09 at 06:43 AM
Okay, I figured out how Unity does it. If you look at the Visual Studio Assembly Browser for UnityEditor.CoreModule, you see that there are a number of [assembly: InternalsVisibleTo ()]
directives. This includes Unity.InternalAPIEditorBridge001
up to Unity.InternalAPIEditorBridge024
. (There are also Unity.InternalAPIEngineBridge001
up to (I think--it's harder to tell) Unity.InternalAPIEngineBridge024
for engine internals. )
The internal bridge class for plug-in com.unity.2d.common
is in the DLL Unity.InternalAPIEditorBridge.001
according to its asmdef. So that's how Unity can access its internals from its plugins!
So, to access the Unity Internals (if you're desperate for them), you create an asmdef for an unused editor bridge DLL, and--presto!--you have the same access.
The problem would be in release code to figure out which internal bridges are already taken. Since I'm not making release code (only a plug-in for the editor that would be used in specific, controlled circumstances), that's not my concern.
(The better solution would be for Unity to move CreateTemporaryDuplicate()
to the public API, hint, hint.)
Answer by Bunny83 · Apr 09 at 08:02 AM
Uhm, you could always use reflection to access internal or private classes / methods / fields. There are only very few things you could not access through reflection. Of course you would create an unwanted dependency which may break in any future update since it's only meant for internal use.
Though the specific method you're talking about only uses public available APIs as far as I can tell. Note that the method goes through some detours to create a duplicate of the texture. If the texture is marked readable you should be able to simply instantiate the texture. You only would need to go though this convoluted process if the source texture is not readable. So it actually creates a temporary render texture, uses blit to copy the texture content on the GPU and then does a readback from the render texture into a new texture.
Thanks @Bunny83. Yes, this method is only needed if the texture is not readable. Nice to find out how it works internally.