2016-02-29 41 views
1

我從我的服務器下載一些精靈並將它們存儲在Application.persistentDataPath中。從永久數據路徑加載精靈

但是,我無法使用Resources.Load (controllerPath)加載控制器,因爲路徑在Resources文件夾之外。

此外,當我嘗試將動畫控制器添加到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; 

我應如何從持久性數據路徑加載的資源?

回答

2

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質感。它將字節數組轉換並寫入設備的ROM中。你需要爲它指定一個Sprite和一個名字。該名稱需要符合文件和文件夾路徑命名。

第二種方法執行翻轉過程,檢查是否已經存儲並將ROM上找到的字節數組轉換爲可用的Sprite。

0

你也可以簡單地使用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 
    }