unity載入場景和切換場景
阿新 • • 發佈:2018-11-07
因為公司沒什麼大牛,所以很多東西只能自己摸索。
好像網上載入場景和切換場景有2種主流的方式
1)用Scenemanager載入和切換scene
2)將scene做成prefab,載入和切換prefab
我用的是第二種方式
1)將preafab打包成assetbundle
程式碼如下 :
// Builds an asset bundle from the selected objects in the project view. // to build the Asset Bundle using UnityEngine; using UnityEditor; public class ExportAssetBundles { [MenuItem("Assets/Build AssetBundle From Selection - Track dependencies -Android")] static void ExportResource () { // Bring up save panel string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d"); if (path.Length != 0) { // Build the resource file from the active selection. Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets); BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets,BuildTarget.Android); Selection.objects = selection; } } }
當然也可以用新增AssetBundle Name 的方式來統一打包。
不建議用第一種方式,好像會把依賴的資源全打進去,而且官方已經放棄
2)載入和切換
程式碼如下:
IEnumerator CoChangeScene(GameScene _scene ) { //銷燬當前場景 for(int i=0;i<sce_scene.Length;i++) { if(sce_scene[i]!=null&&i!=(int)_scene) { DestroyImmediate(sce_scene[i]); sce_scene[i]=null; } } Resources.UnloadUnusedAssets(); GC.Collect(); if ((pf_scene [(int)_scene]) != null) { sce_scene [(int)_scene] = Instantiate (pf_scene [(int)_scene]) as GameObject; } else { yield return StartCoroutine (StResource.GetInstance ().CoLoadScene (_scene)); sce_scene [(int)_scene] = Instantiate (StResource.GetInstance ().GetScene (_scene)) as GameObject; } sce_scene[(int)_scene].transform.SetParent(this.transform.parent.transform); sce_scene[(int)_scene].transform.localPosition=new Vector3(0,0,0); sce_scene[(int)_scene].transform.localScale=new Vector3(1,1,1); this.transform.SetAsLastSibling(); StResource.GetInstance().UnLoadScene( _scene,false); yield return null; }
這就是我的切換邏輯了,很簡陋,但也勉強能用,