unity動態載入場景Resources.Load方法
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。
[csharp] view plain copy- 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");
來自為知筆記(Wiz)