场景管理

场景管理器--框架

1.创建场景基类ISceneName

public class ISceneState{
    private string mSceneName;   //场景名字
    protected SceneStateController mController; //场景控制 
    public ISceneState(string sceneName,SceneStateController controller)
    {
        mSceneName = sceneName;
        mController=controller;
    }
    public string SceneName
    {
        get { return mSceneName; }
    }

    //每次进入状态都会调用、
    public virtual void StateStart() { }
    public virtual void StateEnd() { }
    public virtual void StateUpdate() { }
}

2.创建场景控制类SceneStateController

public class SceneStateController
{
    private ISceneState mState;
    private AsyncOperation mAo;
    private bool mIsRunStart = false;

    /// 
    /// 切换场景
    /// 
    ///  要切换的场景
    ///  是否切换场景()
    public void SetState(ISceneState state, bool isLoadScene = true)
    {
        if(mState!=null)
        {
            mState.StateEnd();//让上一个场景作态做一下清理工作
        }
        mState = state;
        if (isLoadScene)
        {
            mAo = SceneManager.LoadSceneAsync(mState.SceneName);
            mIsRunStart = false;
        }
        else
        {
            mState.StateStart();
            mIsRunStart = true;
        }
    }
    public void StateUpdate()
    {
        if (mAo != null && mAo.isDone == false) return;

        if(mIsRunStart==false&&mAo!=null&&mAo.isDone==true)
        {
            mState.StateStart();
            mIsRunStart = true;
        }

        if(mState!=null && mIsRunStart)
        {
            mState.StateUpdate();
        }
    }
}

3.创建PrejectLoop类,在Unity中新建一个空物体,将PrejectLoop加载上去,使其在场景切换的时候不被删除。

public class ProjectLoop : MonoBehaviour {

    private SceneStateController controller = null;
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
    // Use this for initialization
    void Start() {
        controller = new SceneStateController();
        controller.SetState(new StartSceneState(controller), false);
    }

    // Update is called once per frame
    void Update () {
        if (controller != null)
            controller.StateUpdate();
    }
}

4.场景管理已经创建完毕,如若添加场景,则需新建类,继承与ISceneState,在切换场景的时候,场景名字要与类中SceneName参数相对应,才能正确切换。以下是我继承的一个StartSceneState类(用测试)。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
class StartSceneState : ISceneState
{
    public StartSceneState(SceneStateController controller) : base("startScene", controller)
    {
    }
    public override void StateStart()
    {
        base.StateStart();
        GameObject.Find("Button").GetComponent

基本场景管理差不多已经建造完毕。

你可能感兴趣的:(框架)