Resources加载资源

注意

  • 资源必须放在Resources目录下
  • 资源路径相对于Resources目录,且不加后缀名
  • 即使是后缀不同的资源,也不要重名,否则加载的时候要指定类型。
  • 路径使用正斜杠”/”
  • Resources中的所有资源,都会被打到客户端中
void Start()
{
    GameObject go = GameObject.CreatePrimitive(PrimitiveType.Plane);
    Renderer rend = go.GetComponent();
    rend.material.mainTexture = Resources.Load("glass") as Texture;
}

Resources.Load

public static Object Load(string path, Type systemTypeInstance);
void Start()
{
    // cube.mat 与 cube.prefab重名,所以加载时要指定类型
    Object objMat = Resources.Load("Materials\cube", typeof(Material));

    Object objGO = Resources.Load("Prefabs\cube", typeof(GameObject));

    GameObject go = Instantiate(objGO) as GameObject;
    go.getComponent().material = objMat;
}

Resources.LoadAll

public static Object[] LoadAll(string path);
public static Object[] LoadAll(string path, Type systemTypeInstance);
public static T[] LoadAll(string path);
void Start()
{   
    GameObject[] arr = Resources.LoadAll("Prefabs");
    foreach(GameObject go in arr)
    {
        Instantiate(go);
    }
}

Resources.LoadAsync

public static ResourceRequest LoadAsync(string path);
public static ResourceRequest LoadAsync(string path, Type type);
void Start () {
    StartCoroutine(Load(new string[]{"Prefabs/Cube", "Prefabs/Sphere"}));
}    

// 使用协程异步加载
IEnumerator Load(string[] arr)
{
     foreach(string str in arr)
     {
         ResourceRequest rr = Resources.LoadAsync(str);
         yield return rr;

         Instantiate(rr.asset).name = rr.asset.name;
      }
}

Resources.UnloadUnusedAssets

卸载所有不在引用到的Assets

你可能感兴趣的:(Resources加载资源)