GetAssetPreview始终为UnityEngine.UI.Image返回null

时间:2017-06-09 14:04:22

标签: unity3d unity3d-editor

我有一系列预制件,我想在自定义编辑器中显示预览。这适用于具有网格渲染器的游戏对象,例如基本四边形。但是当我尝试在带有UnityEngine.UI.Image和画布渲染器的游戏对象上使用AssetPreview.GetAssetPreview(tilePrefab.gameObject);时,它总是返回null。

以下是绘制预览的代码部分。

public class MapEditor : Editor
{
    public override void OnInspectorGUI()
    {
        for (int prefabIndex = 0; prefabIndex < TileSet.TilePrefabs.Count; prefabIndex++)
            DrawIconTexture(prefabIndex, columnCount);
    }

    private void DrawIconTexture(int prefabIndex, int columnCount)
    {
        TileBehaviour tilePrefab = TileSet.TilePrefabs[prefabIndex];
        Texture iconTexture = AssetPreview.GetAssetPreview(tilePrefab.gameObject);
        Rect iconRect = GetIconRect(prefabIndex, columnCount);

        if (iconTexture != null)
            GUI.DrawTexture(iconRect, iconTexture);
        else if (AssetPreview.IsLoadingAssetPreview(tilePrefab.gameObject.GetInstanceID()))
            Repaint();
    }
}

我知道GetAssetPreview加载资产异步,这是通过重绘来解决的。我也试过

while(iconTexture == null)
    iconTexture = AssetPreview.GetAssetPreview(tilePrefab.gameObject);

但那永远不会结束。

我也尝试使用Image的纹理

if (iconTexture == null)
    iconTexture = tilePrefab.GetComponent<Image>().sprite.texture;

但是这不起作用,因为精灵在地图册中并且显示了所有地图集。

1 个答案:

答案 0 :(得分:0)

编辑:误读了这个问题。我实际上尝试使用IsLoadingAssetPreview和IsLoadingAssetPreviews几个小时,但没有成功。我最后使用了一个悲伤的小技巧

if (_previews.All(pair => pair.Value != null)) return;
_previews = GeneratePreviews();

我把它放在EditorWindow的Update()循环中。这很糟糕,如果AssetPreview方法确实有效,我会问Unity。

旧答案,无关紧要:

您没有正确使用while循环和GetAssetPreview。

GetAssetPreview将启动异步加载预览。要了解预览是否已完全加载,您需要致电AssetPreview.IsLoadingAssetPreview

一种非常简单而残酷的做法(它会阻止执行)是:

var preview = AssetPreview.GetAssetPreview(item);
while (AssetPreview.IsLoadingAssetPreview(item.GetInstanceID())) {
     // Loading
}

像往常一样,小心while循环。请注意,还有一个没有参数的AssetPreview.IsLoadingAssetPreviews方法。