Unity UGUI中,RawImage混用Sprite的问题

2023/03 24 12:03

一、场景行为:
RawImage使用Sprite资源

二、后果:
打包Assetbundle时,同一个Sprite文件,会被打包成2个资源
1个是Sprite资源,1个是Texture2D资源
这样在加载Assetbundle的Asset时,有机率加载错误

三、解决:
禁止RawImage使用Sprite资源

// ugui1.0
// RawImageEditor.cs

using UnityEngine;
using UnityEngine.UI;

namespace UnityEditor.UI
{
 ...

// 防止RawImage 使用 Sprite
private void CheckUseTextureFormat()
{
    var textureObj = m_Texture.objectReferenceValue as Texture2D;
    if (textureObj == null)
    {
        return;
    }

    var assetPath = UnityEditor.AssetDatabase.GetAssetPath(textureObj);
    TextureImporter importer = TextureImporter.GetAtPath(assetPath) as TextureImporter;
    if (importer != null && importer.textureType != TextureImporterType.Default)
    {
        m_Texture.objectReferenceValue = null;
        UnityEngine.Debug.LogError($"{assetPath}不是纹理, {importer.textureType}格式不支持");
    }
}

public override void OnInspectorGUI()
{
    serializedObject.Update();

    EditorGUI.BeginChangeCheck();
    EditorGUILayout.PropertyField(m_Texture);
    if (EditorGUI.EndChangeCheck())
    {
        CheckUseTextureFormat();
    }

    AppearanceControlsGUI();
    RaycastControlsGUI();
    MaskableControlsGUI();
    EditorGUILayout.PropertyField(m_UVRect, m_UVRectContent);
    SetShowNativeSize(false);
    NativeSizeButtonGUI();

    serializedObject.ApplyModifiedProperties();
}