通过代码检索内置UI精灵

Pro*_*mer 5 c# resources unity-game-engine

Unity中包含大约7个精灵,用于创建UI.我想通过代码访问这些.这些包括UISprite,UIMask,Knob,Background和下面的截图中圈出的其他内容.

在此输入图像描述

我深入挖掘了UI源代码,发现在MenuOptions.cs脚本中声明了所有位置.

private const string kStandardSpritePath = "UI/Skin/UISprite.psd";
private const string kBackgroundSpritePath = "UI/Skin/Background.psd";
private const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd";
private const string kKnobPath = "UI/Skin/Knob.psd";
private const string kCheckmarkPath = "UI/Skin/Checkmark.psd";
private const string kDropdownArrowPath = "UI/Skin/DropdownArrow.psd";
private const string kMaskPath = "UI/Skin/UIMask.psd";
Run Code Online (Sandbox Code Playgroud)

在编辑器中,我能够使用GetBuiltinExtraResource函数检索它们:

Sprite img = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/InputFieldBackground.psd");
Debug.Log(img); //NOT NULL
Run Code Online (Sandbox Code Playgroud)

不幸的是,AssetDatabase.GetBuiltinExtraResource它来自UnityEditor命名空间,不能在构建或独立程序中工作.它甚至无法编译.


我试图Resources.GetBuiltinResource用于构建和独立但它总是返回null.它找不到内置的精灵.

UnityEngine.Object img = Resources.GetBuiltinResource(typeof(UnityEngine.Object), "UI/Skin/InputFieldBackground.psd");
Debug.Log(img); NULL
Run Code Online (Sandbox Code Playgroud)

尝试typeof(Sprite)而不是typeof(UnityEngine.Object)但也失败了.

如何在独立构建而不是编辑器中访问这些内置精灵?

注意:

我不想使用预制件或公共变量来执行此操作,这需要先手动执行操作.这是我目前正在做的这种方式.我只想访问已经打包在构建中的内置sprite.

Pri*_*ens 0

嗯...只是复印。只有七个文件,将它们复制到资源/纹理(如果需要的话,制作它),然后使用以下命令调用它们:

Sprite knob = Resources.Load<Sprite>("Textures/Knob.psd") as Sprite;
Run Code Online (Sandbox Code Playgroud)

这将是简单的方法..但为了好玩,让我们看看这个

static void CreateMaterial()
{
    // Create a simple material asset

    Material material = new Material(Shader.Find("Specular"));
    AssetDatabase.CreateAsset(material, "Assets/MyMaterial.mat");

    // Add an animation clip to it
    AnimationClip animationClip = new AnimationClip();
    animationClip.name = "My Clip";
    AssetDatabase.AddObjectToAsset(animationClip, material);

    // Reimport the asset after adding an object.
    // Otherwise the change only shows up when saving the project
    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(animationClip));

    // Print the path of the created asset
    Debug.Log(AssetDatabase.GetAssetPath(material));
}
Run Code Online (Sandbox Code Playgroud)

我在统一文档中找到了它。现在我知道它正在谈论一种材质...但在我看来,您可以手动将有问题的精灵添加到您的资产中,这样可以确保它们被引用并将包含在构建中。