Unity Editor 不用反射访问编辑器内部方法

Q:

该问题来自Game Framework 官方群(216332935), Liuyi的提问.

Timeline 里引用了 UnityEditor.TimeArea 是个 internal 的类型

Timeline 所在的代码就能正常访问, 但是自己扩展的编辑器类就无法访问

本文参考了:

https://blog.csdn.net/akof1314/article/details/111773851

在使用 Unity Editor 制作编辑器工具的时候

经常无法对 Editor 内的 internal 类和方法进行访问

需要使用反射方式

反射方式写起来比较麻烦, 如果 Unity 升级了版本, 内部接口变化, 会导致反射失效

A:

参考官方代码

https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/AssemblyInfo/AssemblyInfo.cs

我们可以发现其中有大量

[assembly: InternalsVisibleTo(“Unity.InternalAPIEditorBridge.00x”)]

这部分就是官方提供出来以供我们扩展我们自己的编辑器类

实践

在 Editor 下新建一个文件夹

文件夹内包含如下文件:

TestTimeArea.cs文件

using UnityEditor;

public class TestTimeArea : EditorWindow
{
    
    
    private TimeArea m_timeArea = null;

    private void OnEnable()
    {
    
    
        if (this.m_timeArea == null)
        {
    
    
            this.m_timeArea = new TimeArea(true)
            {
    
    
                hRangeLocked = false,
                vRangeLocked = true,
                hSlider = true,
                vSlider = false,
                margin = 10f,
                scaleWithWindow = true,
                ignoreScrollWheelUntilClicked = true
            };
        }
    }
}

TestTimeArea.asmdef文件

{
    
    
    "name": "Unity.InternalAPIEditorBridge.001",
    "references": [],
    "optionalUnityReferences": [],
    "includePlatforms": ["Editor"],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": []
}

现在就可以看到TestTimeArea.cs文件能正常编译, 同时也可以正常使用的UnityEditor.TimeArea

猜你喜欢

转载自blog.csdn.net/zxsean/article/details/118973229