unity加载场景和切换场景

因为公司没什么大牛,所以很多东西只能自己摸索。

好像网上加载场景和切换场景有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;
        
    }

这就是我的切换逻辑了,很简陋,但也勉强能用,

猜你喜欢

转载自blog.csdn.net/write_the_code/article/details/82377739