2

为了从 Unity 的启动画面创建动态淡入效果,我试图在运行时获取启动画面背景的颜色。

在编辑器中,可以在Edit > Project Settings > Player > Splash Image > Background找到颜色。

在研究如何获得这种颜色时,我偶然发现了 PlayerSettings.SplashScreen.backgroundColor. 但是,PlayerSettings该类包含在UnityEditor命名空间中,在运行时无法访问。

我如何在运行时动态获取初始屏幕背景的颜色?


编辑:使用 IL 反编译器,我发现 UnityEditor 程序集通过外部方法解决了这个问题。但是,我仍然看不到从编辑器程序集中获取背景颜色的方法。

public static Color backgroundColor
{
    get
    {
        Color result;
        PlayerSettings.SplashScreen.INTERNAL_get_backgroundColor(out result);
        return result;
    }
    // ...
}

private static extern void INTERNAL_get_backgroundColor(out Color value);
4

1 回答 1

4

Unity 的构建假设您在运行时永远不需要此值,因此您需要使用一些技巧来解决这个问题。为了解决这个使编辑器专用变量可访问的特殊问题,我经常做的事情是编写一个预构建步骤,将任何想要的数据保存到一个资源文件中,然后可以在运行时读取该文件。

您需要执行此操作的唯一 API 是IPreprocessBuild接口、Resources.LoadMenuItem属性(MenuItem是可选的,但会使您的工作流程更容易一些)。

首先,实现一个IPreprocessBuild(这个进入“编辑器”目录和引用UnityEditor)以将设置保存到资源中:

class BackgroundColorSaver : IPreprocessBuild
{
    public int callbackOrder { get { return 0; } } // Set this accordingly
    public void OnPreprocessBuild(BuildTarget target, string path)
    {
        SaveBkgColor();
    }

    [MenuItem("MyMenu/Save Background Splash Color")]
    public static void SaveBkgColor()
    {
        // Save PlayerSettings.SplashScreen.backgroundColor to a
        // file somewhere in your "Resources" directory 
    }
}

此类将在SaveBkgColor()任何时候开始构建时调用,并且该MenuItem标签使您可以选择在任何时候调用该函数(使测试/迭代更容易)。

之后,您将需要编写一个运行时脚本,该脚本仅用于Resources.Load加载您的资产并将其解析/转换为Color对象。


这些是在运行时使“仅限编辑器”资源可用的基础知识。使用 a 执行此操作的最直接方式的一些细节Color

另请记住,由于您希望这是初始屏幕的混合,因此您需要立即运行此代码(可能在Awake()第一个场景中某些行为的函数中)。


旁注:有更有效的方法将颜色保存/加载为二进制 blob 而不是原始文本资产,但这是直截了当的,该部分可以轻松地交换进出,同时保持IPreprocessBuild实现不变。

于 2018-03-06T20:07:19.487 回答