Hi,
i have a strange problem. The first few objects of my gameobject array which contains the asset previews from the specified folder return none or a missing texture. And every second time building the scene the textures from Element 10 to 20 are none or missing and the textures that were none before are assigned properly.
My code:
using UnityEngine;
using System.Collections;
using UnityEditor;
public class Items : MonoBehaviour {
public GameObject[] item;
public Texture2D[] itemIcon;
void Start () {
itemIcon = new Texture2D[item.Length];
for(int i = 0; i < item.Length; i++)
itemIcon _= AssetPreview.GetAssetPreview(item*);*_
* }* } [12535-unbenannt0.png|12535]_
_[12536-unbenannt.jpg*|12536]*
_*
_* I’m using Unity 4. Sorry for my english
GetAssetPreview is really running asynchronously in the background, and if the preview you want is not available when you ask for it you will get a null instead of a texture. You can work around this by polling the preview multiple times:
However this does give a lag time of as much as 1 second for each preview. On my machine I rarely see more than 30 or 45 ms but disk access, processor speed, and other hidden stuff will all affect that. Use with caution.
For 2021, I think the best way to do this is probably set off a Coroutine to just query until an image is found. In my code I’m looking to set the thumbnail of some canvas objects but they aren’t setting.
I did this and it seems to work.
IEnumerator SetThumbnail()
{
Texture2D thumbnail = null;
while (thumbnail == null)
{
thumbnail = AssetPreview.GetAssetPreview(myPrefab);
yield return new WaitForSeconds(.5f);
}
var sprite = Sprite.Create(thumbnail, new Rect(0.0f, 0.0f, thumbnail.width, thumbnail.height), new Vector2(0.5f, 0.5f), 100.0f);
SetImage(sprite);
}