从持久数据路径加载精灵



我正在从我的服务器下载一些精灵并将它们存储在Application.persistentDataPath中。

但是,我无法使用Resources.Load (controllerPath)加载控制器,因为路径位于资源文件夹之外。

此外,当我尝试将动画控制器添加到GameObject时,我得到了MissingComponentException

这是我的代码:

private GameObject SideSprite;
// ...
string controllerPath = Application.persistentDataPath+"/"+aux+"/"+aux+"Controller";
controller = (RuntimeAnimatorController)Resources.Load (controllerPath);  // Returns null
// Below I get:
// MissingComponentException: There is no 'Animator' attached to the
// "Missing Prefab (Dummy)" game object, but a script is trying to access it.
SideSprite.GetComponent<Animator> ().runtimeAnimatorController = controller;

如何从持久数据路径加载资源?

persistentDataPath 用作任何常规文件夹。我不会存储精灵,但更有可能存储纹理,下次您需要它时,您可以展开将纹理应用于精灵的过程:

public static void StoreCacheSprite(string url, Sprite sprite)
{
    if(sprite == null || string.IsNullOrEmpty(url) == true) { return; }
    SpriteRenderer spRend = sprite.GetComponent<SpriteRenderer>();
    Texture2D tex = spRend.material.mainTexture;
    byte[] bytes = tex.EncodeToPNG();
    string path = Path.Combine(Application.persistentDataPath, url);
    File.WriteAllBytes(Application.persistentDataPath, bytes);
}
public static Sprite GetCacheSprite(string url)
{
    if( string.IsNullOrEmpty(url) == true) { return; }
    string path = Path.Combine(Application.persistentDataPath, url);
    if(File.Exists(path) == true)
    {
        bytes = File.ReadAllBytes(path);
        Texture2D texture = new Texture2D(4, 4, TextureFormat.RGBA32, false);
        texture.LoadImage(bytes);
        Sprite sp = Sprite.Create(texture, new Rect(0,0 texture.width, texture.height, new Vector2(0.5f,0.5f));
        return sp;
    }
    return null;
}

第一种方法使用 .NET 中的 File 类存储纹理。它将字节数组转换并写入设备的ROM上(File.WriteAllBytes)。你需要一个雪碧的路径和一个名字。该名称需要符合文件和文件夹路径命名。

第二种方法执行反向过程,检查它是否已存储,并将 RAM 上的字节数组转换为可用的精灵。

您也可以简单地使用 WWW 来获取数据。

string controllerPath = Application.persistentDataPath+"/"+aux+"/"+aux+"Controller";
    IEnumerator Start ()
    {
        WWW www = new WWW("file:///" + controllerPath);
        yield return www;
        Debug.Log(www.texture); //or www.bytes
    }

最新更新