欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity-地形编辑器-编辑器拓展功能类

程序员文章站 2022-03-26 16:01:30
...
//==========================
// - FileName:      MapTool.cs         
// - Created:       true.	
// - CreateTime:    2020/04/04 23:37:18	
// - Email:         [email protected]		
// - Region:        China WUHAN	
// - Description:   编辑器拓展
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;


#if Tool
[CustomEditor(typeof(MapMaker))]
public class MapTool : Editor
{
    //对象的引用
    private MapMaker mapMaker; 
    //拿到文件、关卡文件列表
    private List<FileInfo> fileList = new List<FileInfo>();
    //名字列表
    private string[] fileNameList;
    //当前编辑关卡索引号
    private int selectIndex = -1;
    
    public override void OnInspectorGUI()
    {
        //添加的东西写在下方
        base.OnInspectorGUI();
        //只有程序在运行的时候
        if (Application.isPlaying)
        {
#region 第一行
            mapMaker = MapMaker.Instance;
            //开始水平
            EditorGUILayout.BeginHorizontal();
            //获取操作的文件名
            fileNameList = GetNames(fileList);
            //下拉列表
            int currentIndex = EditorGUILayout.Popup(selectIndex, fileNameList);
            //判断当前索引是否为选择的索引 、当前选择对象是否改变
            if (currentIndex != selectIndex)
            {
                //更改索引
                selectIndex = currentIndex;
                //实例化地图的方法
                mapMaker.InitMap();
                //加载当前选择的 Level 文件
                mapMaker.LoadLevelFile(mapMaker.LoadLevelInfoFile(fileNameList[selectIndex]));
                //读取关卡列表

            }

            if (GUILayout.Button("读取关卡列表"))
            {
                //读取关卡列表
                LoadLevelFiles();
            }

            //结束
            EditorGUILayout.EndHorizontal();

#endregion

#region 第二行
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("恢复地图编辑器默认状态"))
            {
                mapMaker.RecoverTowerPoint();
            }
            if (GUILayout.Button("清楚怪物路点"))
            {
                mapMaker.ClearMonsterPath();
            }
            EditorGUILayout.EndHorizontal();
#endregion
            
#region 第三行
            if (GUILayout.Button("保存当前关卡数据文件"))
            {
                mapMaker.SaveLevelFileByJson();
            }

#endregion
        }

    }

    //加载关卡数据
    private void LoadLevelFiles()
    {
        ClearList();
        //加载文件列表、关卡数据
        fileList = GetLevelFiles();
    }

    //清楚文件列表
    private void ClearList()
    {
        fileList.Clear();
        selectIndex = -1;
    }

    //获取当前关卡列表
    private List<FileInfo> GetLevelFiles()
    {
        //获取文件
        string[] files = Directory.GetFiles(Application.dataPath + "/Resources/Json/Level/","*.json");
        List<FileInfo> list = new List<FileInfo>();
        //遍历对象
        for (int i = 0; i < files.Length; i++)
        {
            FileInfo file = new FileInfo(files[i]);
            //对象添加进列表
            list.Add(file);
        }
        return list;
    }
    
    //获取关卡文件的名字
    private string[] GetNames(List<FileInfo> files)
    {
        List<string> names = new List<string>();
        //遍历传递的列表
        foreach (FileInfo file in files)
        {
            names.Add(file.Name);
        }
        return names.ToArray();

    }
}

#endif
//==========================
// - FileName:      GridPoint.cs         
// - Created:       true.	
// - CreateTime:    2020/03/16 17:03:43	
// - Email:         [email protected]
// - Region:        China WUHAN	
// - Description:   信息存储、交互
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.EventSystems;

public class GridPoint : MonoBehaviour
{
    //渲染处理(属性)
    private SpriteRenderer spriteRenderer;
    //格子的图片
    private Sprite gridSprite;
    public GridState gridState;
    public GridIndex gridIndex;
    //格子状态(没有建塔的时候建塔、有塔的时候升级塔)
    public bool hasTower;
    //当前格子道具、开始精灵图片
    private Sprite startSprite;
    //不可建塔
    private Sprite coutBuildSprite;
    //引用
    private GameControl gameControl;
    //当前关卡建塔列表
    private GameObject towerListGo;
    //有塔的按钮画布
    private GameObject handleTowerCanvasGo;
    //两个按钮的引用
    private Transform upLevelBtnTrans;
    private Transform sellTowerBtnTrans;
    //按钮的初始位置
    private Vector3 upLevelBtnInitPos;
    private Vector3 sellTowerBtnInitPos;

#if Tool
    //怪物路点图片
    private Sprite monsterPathSprite;
    //所有道具
    public GameObject[] itemPrefabs;
    public GameObject currentItem;
#endif


    [SerializeField]
    //类信息(格子状态)
    public struct GridState
    {
        //是否可以建塔    
        public bool canBuild;
        //是否是怪物路点
        public bool isMonsterPoint;
        //是否有道具
        public bool hasItem;
        //道具 ID
        public int itemID;
    }

    [SerializeField]
    //格子索引(格子的点)
    public struct GridIndex
    {
        public int xIndex;
        public int yIndex;
    }

    private void Awake()
    {
#if Tool
        //获取格子
        gridSprite = Resources.Load<Sprite>("Pictures/NormalMordel/Game/Grid");
        //怪物路点
        monsterPathSprite = Resources.Load<Sprite>("Pictures/NormalMordel/Game/1/Monster/6-1");
        itemPrefabs = new GameObject[10];
        //大关卡索引路径
        string PrefabsPath = "Prefabs/Game/" + MapMaker.Instance.bigLevelID.ToString() + "/Item/";
        for (int i = 0; i < itemPrefabs.Length; i++)
        {
            //加载的游戏物体存储进数组
            itemPrefabs[i] = Resources.Load<GameObject>(PrefabsPath + i);
            //是否加载完成、如果没有该路径
            if (!itemPrefabs[i])
            {
                Debug.Log("加载失败、失败路径" + PrefabsPath + i);
            }
        }
#endif
        spriteRenderer = GetComponent<SpriteRenderer>();
        //初始化格子状态
        InitGrid();
#if Game
        gameControl = GameControl.Instance;
        //格子资源
        gridSprite = gameControl.GetSprite("NormalMordel/Game/Grid");
        startSprite = gameControl.GetSprite("NormalMordel/Game/StartSprite");
        coutBuildSprite = gameControl.GetSprite("NormalMordel/Game/cantBuild");
        //初始化
        spriteRenderer.sprite = startSprite;
        //动画播放
        Tween t = DOTween.To(() => spriteRenderer.color, tocolor => spriteRenderer.color = tocolor, new Color(1, 1, 1, 0.2f), 3f);
        //回调函数动画
        t.OnComplete(ChangeSpriteToGrid);
        towerListGo = gameControl.towerListGo;
        handleTowerCanvasGo = gameControl.handleTowerCanvasGo;
        upLevelBtnTrans = handleTowerCanvasGo.transform.Find("Btn_UpLevel");
        sellTowerBtnTrans = handleTowerCanvasGo.transform.Find("Btn_SellTower");
        upLevelBtnInitPos = upLevelBtnTrans.localPosition;
        sellTowerBtnInitPos = sellTowerBtnTrans.localPosition;
#endif
    }

    //还原样式
    private void ChangeSpriteToGrid()
    {
        //关闭渲染
        spriteRenderer.enabled = false;
        spriteRenderer.color = new Color(1, 1, 1, 1);
        //可以建塔
        if (gridState.canBuild)
        {
            spriteRenderer.sprite = gridSprite;
        }
        else
        {
            //不可建塔
            spriteRenderer.sprite = coutBuildSprite;
        }
    }

    //初始化方法
    public void InitGrid()
    {
        gridState.canBuild = true;
        gridState.isMonsterPoint = false;
        gridState.hasItem = false;
        spriteRenderer.enabled = true;
        gridState.itemID = -1;
#if Tool
        //更改图片
        spriteRenderer.sprite = gridSprite;
        //销毁道具
        Destroy(currentItem);
#endif

    }

#if Game
    //更新格子状态
    public void UpdateGrid()
    {
        //可以建塔
        if (gridState.canBuild)
        {
            spriteRenderer.enabled = true;
            //有道具 的时候
            if (gridState.hasItem)
            {
                CreateItem();
            }
        }
        else
        {
            spriteRenderer.enabled = false;
        }
    }

    //创建物品
    private void CreateItem()
    {
        //加载道具
        GameObject itemGo = GameControl.Instance.GetGameObjectResource(GameControl.Instance.mapMaker.bigLevelID.ToString() + "/Item/" + gridState.itemID);
        itemGo.transform.SetParent(GameControl.Instance.transform);
        //偏移
        Vector3 createPos = transform.position - new Vector3(0, 0, 3);
        if (gridState.itemID <= 2)
        {
            //自身加上偏移
            createPos += new Vector3(GameControl.Instance.mapMaker.gridWidth, -GameControl.Instance.mapMaker.gridHeight) / 2;
        }
        else if (gridState.itemID <= 4)
        {
            createPos += new Vector3(GameControl.Instance.mapMaker.gridWidth, 0) / 2;
        }
        itemGo.transform.position = createPos;
        itemGo.GetComponent<Item>().gridPoint = this;
    }

    private void OnMouseDown()
    {
        //        //选中的时候为 UI return
        //#pragma warning disable CS0472 // 由于此类型的值永不等于 "null",该表达式的结果始终相同
        //        if (EventSystem.current.IsPointerOverGameObject() == null)
        //#pragma warning restore CS0472 // 由于此类型的值永不等于 "null",该表达式的结果始终相同
        //        {
        //            return;
        //        }
        Debug.Log("鼠标点击事件");
        gameControl.HandleGrid(this);
    }

    //建完塔之后的处理方法
    public void AfterBuild()
    {
        spriteRenderer.enabled = false;
        //塔的后续处理
        Debug.Log("隐藏");
    }

    //显示格子
    public void ShowGird()
    {
        //当前有无塔
        if (!hasTower)
        {
            spriteRenderer.enabled = true;
            //显示建塔列表
            towerListGo.transform.position = CorrectTowerListGoPosition();
            towerListGo.SetActive(true);
        }
        else
        {
            handleTowerCanvasGo.transform.position = transform.position;
            
            CorrectHandleTowerCanvasGoPosition();
            handleTowerCanvasGo.SetActive(true);
            //显示攻击范围
            //TODO

        }
    }

    //隐藏上一个格子
    public void HideGrid()
    {
        //没有塔的时候
        if (!hasTower)
        {
            //隐藏建塔列表
            towerListGo.SetActive(false);
        }
        else
        {
            //有塔
            handleTowerCanvasGo.SetActive(false);
            //显示塔的范围

        }
        spriteRenderer.enabled = false;
    }

    //不可建塔
    public void ShowCantBuild()
    {
        spriteRenderer.enabled = true;
        Tween t = DOTween.To(() => spriteRenderer.color, tocolor => spriteRenderer.color = tocolor, new Color(1, 1, 1, 0), 2f);
        t.OnComplete
        (() =>
            {
                //关闭渲染
                spriteRenderer.enabled = false;
                //初始化
                spriteRenderer.color = new Color(1, 1, 1, 1);
            }
        );
    }

    //纠正建塔列表位置
    private Vector3 CorrectTowerListGoPosition()
    {
        Vector3 createPositon = Vector3.zero;
        //左边缘
        if (gridIndex.xIndex <= 3 && gridIndex.xIndex >= 0)
        {
            createPositon += new Vector3(gameControl.mapMaker.gridWidth, 0, 0);
        }
        else if (gridIndex.xIndex <= 11 && gridIndex.xIndex >= 8)
        {
            createPositon -= new Vector3(gameControl.mapMaker.gridWidth, 0, 0);
        }
        if (gridIndex.yIndex <= 3 && gridIndex.yIndex >= 0)
        {
            createPositon += new Vector3(0, gameControl.mapMaker.gridHeight, 0);
        }
        else if (gridIndex.yIndex <= 7 && gridIndex.yIndex >= 4)
        {
            createPositon -= new Vector3(0, gameControl.mapMaker.gridHeight, 0);
        }
        createPositon += transform.position;
        return createPositon;
    }

    //纠正画布
    private void CorrectHandleTowerCanvasGoPosition()
    {
        //初始化位置
        upLevelBtnTrans.localPosition = Vector3.zero;
        sellTowerBtnTrans.localPosition = Vector3.zero;
        if (gridIndex.yIndex <= 0)
        {
            //当前塔在最左边
            if (gridIndex.xIndex == 0)
            {
                //偏移
                sellTowerBtnTrans.position += new Vector3(gameControl.mapMaker.gridWidth * 3 / 4, 0, 0);
            }
            else
            {
                sellTowerBtnTrans.position -= new Vector3(gameControl.mapMaker.gridWidth * 3 / 4, 0, 0);
            }
            //升级按钮处理
            upLevelBtnTrans.localPosition = upLevelBtnInitPos;
        }
        else if (gridIndex.yIndex >= 6) 
        {
            if (gridIndex.xIndex == 0)
            {
                upLevelBtnTrans.position += new Vector3(gameControl.mapMaker.gridWidth * 3 / 4, 0, 0);
            }
            else
            {
                upLevelBtnTrans.position -= new Vector3(gameControl.mapMaker.gridWidth * 3 / 4, 0, 0);
            }
            sellTowerBtnTrans.localPosition = sellTowerBtnInitPos;
        }
        else
        {
            upLevelBtnTrans.localPosition = upLevelBtnInitPos;
            sellTowerBtnTrans.localPosition = sellTowerBtnInitPos;
        }
    }

#endif

#if Tool
    //怪物路点
    private void OnMouseDown()
    {
        //玩家按左键的时候 、 怪物路点
        if (Input.GetKey(KeyCode.P))
        {
            //不能建塔
            gridState.canBuild = false;
            //打开渲染
            spriteRenderer.enabled = true;
            //回调、取非
            gridState.isMonsterPoint = !gridState.isMonsterPoint; 
            //是怪物路点的时候
            if (gridState.isMonsterPoint)
            {
                MapMaker.Instance.monsterPath.Add(gridIndex);
                //控制渲染
                spriteRenderer.sprite = monsterPathSprite;
            }
            else
            {
                //不是怪物路点的时候、删除列表
                MapMaker.Instance.monsterPath.Remove(gridIndex);
                //改变格子渲染
                spriteRenderer.sprite = gridSprite;
                //可以建塔
                gridState.canBuild = true;
            }
        }
        else if(Input.GetKey(KeyCode.I))
        {
            //道具
            gridState.itemID++;
            //超出索引、当前格子从持有道具转换为没有道具
            if (gridState.itemID == itemPrefabs.Length)
            {
                gridState.itemID = -1;
                Destroy(currentItem);
                //是否持有道具
                gridState.hasItem = false;
                return;
            }
            if (currentItem == null)
            {
                //产生道具
                CreateItem();
            }
            else
            {
                //本身挂载有道具
                Destroy(currentItem);
                //产生道具的方法
                CreateItem();
            }
            gridState.hasItem = true;
        }
        else if (!gridState.isMonsterPoint)
        {
            //没有键盘操作的时候且不是怪物路点
            gridState.isMonsterPoint = false;
            //取非
            gridState.canBuild = !gridState.canBuild;
            if (gridState.canBuild)
            {
                spriteRenderer.enabled= true;
            }
            else
            {
                spriteRenderer.enabled = false;
            }
        }
    }


    //生成道具的方法
    private void CreateItem()
    {
        Vector3 createPos = transform.position;
        if (gridState.itemID <= 2)
        {
            createPos += new Vector3(MapMaker.Instance.gridWidth, -MapMaker.Instance.gridHeight) / 2;
        }
        else if (gridState.itemID <= 4)
        {
            createPos += new Vector3(MapMaker.Instance.gridWidth,0) / 2;
        }
        GameObject itemGo = Instantiate(itemPrefabs[gridState.itemID], createPos, Quaternion.identity);
        currentItem = itemGo;
    }

    //更新格子状态
    public void UpdateGrid()
    {
        //判断格子状态能否尖塔
        if (gridState.canBuild)
        {
            spriteRenderer.sprite = gridSprite;
            //渲染打开
            spriteRenderer.enabled = true;
            //是否是道具
            if (gridState.hasItem)
            {
                CreateItem();
            }
        }
        else
        {
            //格子是否是怪物路店点
            if (gridState.isMonsterPoint)
            {
                spriteRenderer.sprite = monsterPathSprite;
            }
            else
            {
                //当前格子点无法建塔
                spriteRenderer.enabled = false;
            }
        }
    }
#endif

}


    
//==========================
// - FileName:      Level.cs         
// - Created:       true.	
// - CreateTime:    2020/04/09 16:41:52	
// - Email:         [email protected]		
// - Region:        China WUHAN	
// - Description:   控制任务链叠加、赋值
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Level
{
    //当前关卡波次怪物
    public int totalRound;
    //
    public Round[] roundList;
    //当前的 round
    public int currentRound;

    public Level(int roundNum, List<Round.RoundInfo> roundInfoList)
    {
        totalRound = roundNum;
        roundList = new Round[totalRound];
        //具体内容、
        for (int i = 0; i < totalRound; i++)
        {
            roundList[i] = new Round(roundInfoList[i].mMonsterIDList, i, this);
        }
        //设置任务链
        for (int i = 0; i < totalRound; i++)
        {
            //是否为最后一个元素
            if (i == totalRound - 1)
            {
                break;
            }
            //设置任务
            roundList[i].SetNextRound(roundList[i + 1]);
        }
    }

    //控制者
    public void HandleRound()
    {
        //当前回合大于等于 最后一关
        if (currentRound >= totalRound)
        {
            //游戏胜利

        }
        else if (currentRound == totalRound-1)
        {
            //最后一波怪 的 UI 、音乐

        }
        else
        {
            //普通波次
            roundList[currentRound].Handle(currentRound);
        }
    }

    //调用最后一回合的 Handle 方法
    public void HandleLastRound()
    {
        roundList[currentRound].Handle(currentRound);
    }

    //
    public void AddRoundNum()
    {
        currentRound++;
    }
}
//==========================
// - FileName:      LevelInfo.cs         
// - Created:       true.	
// - CreateTime:    2020/04/06 17:54:32	
// - Email:         [email protected]		
// - Region:        China WUHAN	
// - Description:   
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LevelInfo
{
    //需要存储的信息

    //大关卡 ID
    public int bigLevelID;
    //小关卡 ID
    public int levelID;
    //所有格子状态、避免使用二维数组
    public List<GridPoint.GridState> gridPoints;
    //怪物路径点、使用索引存储
    public List<GridPoint.GridIndex> monsterPath;
    //当前关卡信息
    public List<Round.RoundInfo> roundInfo;
}

//==========================
// - FileName:      MapMaker.cs         
// - Created:       true.	
// - CreateTime:    2020/03/16 14:27:09	
// - Email:         [email protected]		
// - Region:        China WUHAN	
// - Description:   地图编辑器工具、游戏中作为地图产生工具
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;

public class MapMaker : MonoBehaviour
{

#if Tool
    //开关属性、画线开关
    public bool drawLine;
    //塔的添加点
    public GameObject gridGo;
    
    //在游戏中不是单例、在工具中才是单例
    private static MapMaker _instance;
    public static MapMaker Instance
    {
        get
        {
            return _instance;
        }
    }
#endif
    //地图宽
    private float mapWidth;
    //高
    private float mapHeight;
    [HideInInspector]
    //格子宽
    public float gridWidth;
    [HideInInspector]
    //格子高
    public float gridHeight;
    [HideInInspector]
    //当前关数索引
    public int bigLevelID;
    [HideInInspector]
    public int LevelID;
    //地图的全部格子对象
    public GridPoint[,] gridPoints;
    //行数
    public const int yRow = 8; 
    //列数
    public const int xColumn = 12;

    [HideInInspector]
    //怪物路径点具体位置
    public List<Vector3> monsterPathPos;
    //背景渲染
    private SpriteRenderer bgSR;
    //地图的加载渲染
    private SpriteRenderer roadSR;

    [HideInInspector]
    //怪物路径点、格子索引
    public List<GridPoint.GridIndex> monsterPath;
    //每一波次产生的怪物ID列表
    public List<Round.RoundInfo> roundInfoList;

    [HideInInspector]
    public Carrot carrot;

    private void Awake()
    {
#if Tool
        _instance = this;
        //InitMapMaker();
#endif
    }

    //初始化地图
    public void InitMapMaker()
    {
        CalculateSize();
        //实例化数组
        gridPoints = new GridPoint[xColumn, yRow];
        monsterPath = new List<GridPoint.GridIndex>();
        //生成格子
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRow; y++)
            {
#if Tool
                //生成格子对象
                GameObject itemGo = Instantiate(gridGo, transform.position, transform.rotation);
#endif
#if Game
                GameObject itemGo = GameControl.Instance.GetGameObjectResource("Grid");
#endif
                //设置属性
                itemGo.transform.position = CorretPositon(x * gridWidth, y * gridHeight);
                itemGo.transform.SetParent(transform);
                //获取格子点
                gridPoints[x, y] = itemGo.GetComponent<GridPoint>();
                gridPoints[x, y].gridIndex.xIndex = x;
                gridPoints[x, y].gridIndex.xIndex = y;
            }
        }
        //获取渲染组件
        bgSR = transform.Find("BG").GetComponent<SpriteRenderer>();
        roadSR = transform.Find("Road").GetComponent<SpriteRenderer>();
    }

    //加载地图
#if Game
    public void LoadMap(int bigLevel,int Level)
    {
        bigLevelID = bigLevel;
        LevelID = Level;
        //加载文件
        LoadLevelFile(LoadLevelInfoFile("Level" + bigLevelID.ToString() + "_" + LevelID.ToString() + ".json"));
        monsterPathPos = new List<Vector3>();
        //遍历怪物路径列表
        for (int i = 0; i < monsterPath.Count; i++)
        {
            //位置添加进列表
            monsterPathPos.Add(gridPoints[monsterPath[i].xIndex,monsterPath[i].yIndex].transform.position); 
        }
        //起始点与终止点
        GameObject startPointGo = GameControl.Instance.GetGameObjectResource("startPoint");
        //怪物点的第一个位置
        startPointGo.transform.position = monsterPathPos[0];
        startPointGo.transform.SetParent(transform);
        GameObject endPointGo = GameControl.Instance.GetGameObjectResource("Carrot");
        //怪物点的第一个位置
        endPointGo.transform.position = monsterPathPos[monsterPathPos.Count - 1];
        endPointGo.transform.SetParent(transform);
        carrot = endPointGo.GetComponent<Carrot>();
    }
#endif


    //纠正预制件的起始位置
    public Vector3 CorretPositon(float x,float y)
    {
        return new Vector3(x - mapWidth / 2 + gridWidth / 2, y- mapHeight / 2 + gridHeight / 2);
    }


    //计算地图格子的宽高
    private void CalculateSize()
    {
        //左下角
        Vector3 leftDown = new Vector3(0, 0);
        //右上角
        Vector3 rightUp = new Vector3(1, 1);
        //视口坐标转世界坐标 、 左下角的世界坐标
        Vector3 posOne = Camera.main.ViewportToWorldPoint(leftDown);
        //右上角
        Vector3 posTwo = Camera.main.ViewportToWorldPoint(rightUp);
        //地图宽
        mapWidth = posTwo.x - posOne.x;
        //地图高
        mapHeight = posTwo.y - posOne.y;
        //格子的宽
        gridWidth = mapWidth / xColumn;
        //格子高
        gridHeight = mapHeight / yRow;
    }

#if Tool
    //画格子
    private void OnDrawGizmos()
    {
        //画线
        if (drawLine)
        {
            //计算格子的大小
            CalculateSize();
            //格子的颜色
            Gizmos.color = Color.green;
            //画出行数   这里的值应该是要等于行数的
            for (int y = 0; y <= yRow; y++)
            {
                //起始位置
                Vector3 startPos = new Vector3(-mapWidth / 2, -mapHeight / 2 + y * gridHeight);
                //终点坐标
                Vector3 endPos = new Vector3(mapWidth / 2, -mapHeight / 2 + y * gridHeight);
                //画线
                Gizmos.DrawLine(startPos, endPos);
            }
            //画列
            for (int x = 0; x <= xColumn; x++)
            {
                Vector3 startPos = new Vector3(-mapWidth / 2 + gridWidth * x, mapHeight / 2);
                Vector3 endPos = new Vector3(-mapWidth / 2 + x * gridWidth, -mapHeight / 2);
                Gizmos.DrawLine(startPos, endPos);
            }
        }
        else
        {
            return;
        }
    }
#endif
    //清除怪物路点
    public void ClearMonsterPath()
    {
        monsterPath.Clear();
    }

    //恢复地图编辑默认状态
    public void RecoverTowerPoint()
    {
        //清除怪物路点
        ClearMonsterPath();
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRow; y++)
            {
                //初始化塔点
                gridPoints[x, y].InitGrid();
            }
        }
    }

    //初始化地图
    public void InitMap()
    {
        //大小关卡 ID 置0 
        bigLevelID = 0;
        LevelID = 0;
        RecoverTowerPoint();
        //清除怪物路经
        roundInfoList.Clear();
        //渲染清除
        bgSR.sprite = null;
        roadSR.sprite = null;
    }

#if Tool
    //生成 LevelInfo 对象,保存文件
    private LevelInfo CreateLevelInfoGo()
    {
        LevelInfo levelInfo = new LevelInfo()
        {
            bigLevelID = this.bigLevelID,
            levelID = this.LevelID,
        };
        levelInfo.gridPoints = new List<GridPoint.GridState>();
        //遍历
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRow; y++)
            {
                //添加进信息对象列表
                levelInfo.gridPoints.Add(gridPoints[x, y].gridState);
            }
        }
        levelInfo.monsterPath = new List<GridPoint.GridIndex>();
        //遍历怪物路径
        for (int i = 0; i < monsterPath.Count; i++)
        {
            levelInfo.monsterPath.Add(monsterPath[i]);
        }
        //产生怪物的 ID 列表
        levelInfo.roundInfo = new List<Round.RoundInfo>();
        for (int i = 0; i < roundInfoList.Count; i++)
        {
            levelInfo.roundInfo.Add(roundInfoList[i]);
        }
        Debug.Log("保存成功");
        return levelInfo;
    }
    
    //保存成 Json、保存当前关卡
    public void SaveLevelFileByJson()
    {
        LevelInfo levelInfoGo = CreateLevelInfoGo();
        //路径
        string filePath = Application.dataPath + "/Resources/Json/Level/" + bigLevelID.ToString() + "_" + LevelID.ToString() + ".json";
        //对象转换字符串
        string saveJsonStr = JsonMapper.ToJson(levelInfoGo);  
        //文件流
        StreamWriter sw = new StreamWriter(filePath);
        //写的内容  
        sw.Write(saveJsonStr);
        //关闭文件流
        sw.Close();
    }
#endif

    //读取关卡文件、解析Josn 转换为对象
    public LevelInfo LoadLevelInfoFile(string fileName)
    {
        LevelInfo levelInfo = new LevelInfo(); 
        //完善路径
        string filePath = Application.dataPath + "/Resources/Json/Level/" + fileName;
        //文件读取流、判断路径是否存在
        if (File.Exists(filePath))
        {
            //如果存在
            StreamReader sr = new StreamReader(filePath);
            //读成字符串
            string jsonStr = sr.ReadToEnd();
            //关闭文件流
            sr.Close();
            //取得对象
            levelInfo = JsonMapper.ToObject<LevelInfo>(jsonStr);
            return levelInfo;
        }
        Debug.Log("文件加载失败、失败路径"+filePath);
        return null;
    }

    //信息转换
    public void LoadLevelFile(LevelInfo levelInfo)
    {
        bigLevelID = levelInfo.bigLevelID;
        LevelID = levelInfo.levelID;
        for (int x = 0; x < xColumn; x++)
        {
            for (int y = 0; y < yRow; y++)
            {
                //更新信息
                gridPoints[x, y].gridState = levelInfo.gridPoints[y + x * yRow];
                //更新格子状态
                gridPoints[x, y].UpdateGrid();
            }
        }
        //清除
        monsterPath.Clear();
        //怪物路径
        for (int i = 0; i < levelInfo.monsterPath.Count; i++)
        {
            monsterPath.Add(levelInfo.monsterPath[i]);
        }
        roundInfoList = new List<Round.RoundInfo>();
        for (int i = 0; i < levelInfo.roundInfo.Count; i++)
        {
            roundInfoList.Add(levelInfo.roundInfo[i]);
        }
        //设置地图的图片切换
        bgSR.sprite = Resources.Load<Sprite>("Pictures/NormalMordel/Game/" + bigLevelID.ToString() + "/" + "BG" + (LevelID / 3).ToString());
        roadSR.sprite = Resources.Load<Sprite>("Pictures/NormalMordel/Game/" + bigLevelID.ToString() + "/" + "Road" + LevelID);

    }
    
}
//==========================
// - FileName:      Round.cs         
// - Created:       true.	
// - CreateTime:    2020/04/06 17:24:47	
// - Email:         [email protected]		
// - Region:        China WUHAN	
// - Description:   
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Round
{
    [Serializable]
    //存储信息 
    public struct RoundInfo
    {
        //怪物列表信息
        public int[] mMonsterIDList;
    }
    
    //对象
    public RoundInfo roundInfo;
    //下一个对象
    protected Round mNextRound;
    //当前关卡的编号
    protected int mRoundID;
    //Level 对象
    protected Level mlevel;

    public Round(int[] monsterIDList, int roundID, Level level)
    {
        mlevel = level;
        roundInfo.mMonsterIDList = monsterIDList;
        mRoundID = roundID;
    }

    //下一个任务链
    public void SetNextRound(Round nextRound)
    {
        mNextRound = nextRound;
    }

    //责任链的判定
    public void Handle(int roundID)
    {
        //如果当前回合并不是理想中 的 ID
        if (mRoundID < roundID)
        {
            mNextRound.Handle(roundID);
        }
        else
        {
            //当前任务链大于等于 ID 、产生怪物
            GameControl.Instance.mMonsterIDList = roundInfo.mMonsterIDList;
            GameControl.Instance.CreateMonster();
            
        }
    }

}

//==========================
// - FileName:      Stage.cs         
// - Created:       true.	
// - CreateTime:    2020/03/11 19:05:34	
// - Email:         [email protected]		
// - Region:        China WUHAN	
// - Description:   存储所有的关卡信息
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Stage
{
    //
    public int[] mTowerIDList;
    //具体长度
    public int mTowerIDListLength;
    //当前关卡是否清除所有道具
    public bool mAllClear;
    //萝卜状态
    public int mCarrotState;
    //小关卡ID 
    public int mLevelID;
    //大关卡ID
    public int mBigLevelID;
    //当前关卡是否解锁
    public bool unLocked;
    //当前关卡是否为奖励、隐藏关卡
    public bool mIsRewardLevel;
    //当前怪物波数
    public int mTotalRound;


    //使用构造进行赋值
    public Stage(int totalRound, int towerIDListLength, int[] towerIDList,
        bool allClear, int carrotState, int levelID, int bigLevelID, bool locked, bool isRewardLevel)
    {
        mTotalRound = totalRound;
        mTowerIDListLength = towerIDListLength;
        mTowerIDList = towerIDList;
        mAllClear = allClear;
        mCarrotState = carrotState;
        mLevelID = levelID;
        mBigLevelID = bigLevelID;
        unLocked = locked;
        mIsRewardLevel = isRewardLevel;
    }
}

相关标签: Unity 3D