Resources.Load:使用這種方式加載資源,首先需要下Asset目錄下創建一個名為Resources的文件夾(可以不在一級目錄,二級目錄也可以),這個命名是U3D規定的方式,然后把資源文件放進去,當然也可以在Resources中再創建子文件夾,代碼加載時需要添加相應的資源路徑。
下面是一個簡demo,兩個預設場景,Cube和scene,其中Cube放在Resource中的Prebs中,而scene放在Resources跟目錄下,而Herarchy面板里沒有這兩個場景。
具體看下圖:
在二級目錄:
下面實現Resources.Load資源的加載。
代碼如下:
- using UnityEngine;
- using System.Collections;
- public class LoadResDemo : MonoBehaviour
- {
- private string cubePath = "Prebs/Cube";
- private string spherePath = "scene";
- void Start()
- {
- //把資源加載到內存中
- Object cubePreb = Resources.Load(cubePath, typeof(GameObject));
- //用加載得到的資源對象,實例化游戲對象,實現游戲物體的動態加載
- GameObject cube = Instantiate(cubePreb) as GameObject;
- //以下同理實現scene的動態實例化
- //把資源加載到內存中
- Object scene = Resources.Load(spherePath, typeof(GameObject));
- //用加載得到的資源對象,實例化游戲對象,實現游戲物體的動態加載
- GameObject aa = Instantiate(scene) as GameObject;
- Debug.Log(aa+"sss");
- }
- }
這樣把腳本綁定到Herarchy面板的相機上運行就可以實現動態加載了。
如圖:
聲明:
上面的方法在unity5.3.2f1版本中使用會出錯(上面方法版本忘記了但一定是unity5.3.2f1之前的版本)。所以后來的方法換成了這種(如下代碼):
GameObject vrgiftsall = Resources.Load("Prefab/VR/biggiftsvr")as GameObject;
GameObject biggiftvrload = Instantiate (vrgiftsall) as GameObject;
------------------------------------------------------------------------------------------
下面講如何加載圖片(Texture)並轉為sprite.用的依舊是unity5.3.2f1版本。
如下面代碼:
1.在Resources目錄下有ic_heng_touxiangda這張sprite,首先用Texture2D的方式加載到aa上。
2.然后再定義一個Sprite將Textrue2D轉為sprite。Sprite.Create()這個方法括號里第一個參數是一張Texture2D圖片,第二個是生成sprite的Rect(也就是位置和大小),第三個是生成的pivot位置(中心點)。
3.之后將sprite(也就是下面的kk)賦值給一個Image組件上就 OK。
- Texture2D aa = (Texture2D)Resources.Load("FullScreenfild/ic_heng_touxiangda") as Texture2D;
- Sprite kk = Sprite.Create(aa, new Rect(0, 0, aa.width, aa.height), new Vector2(0.5f, 0.5f));
- UIinit.CAVA.transform.FindChild("Panel/head_portrait_bg/head_portrait/Image").GetComponent<Image>().sprite = kk;
或者是下面方法:(注意Resources的路徑中是不能有下划線的不然是無法識別的)
this.GetComponent<Image>().sprite = Resources.Load<Sprite>("78");
this.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("78");