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;
        
    }

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

  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值