第八章 游戏中的数据(Data in Game)
在之前的章节中,我们进行地图对象的生成,移动等操作。
这一章本来可以进行战斗的编写,不过数据缺失是一个问题。
所以这一章我们先来建立一些数据,以及如何编辑它们,是否需要生成配置文件等。
文章目录
七 数据的容器(Data Container)
之前我们有了物品与角色,从文件读取的数据很多都只是模版。在真正生成一个物品或者一个角色时,我们是使用这些模板的。而这些模板需要一个保存的位置。
1 模型接口(IModel)
这个接口只用于初始化模型,使用接口可以更好的进行扩展:
using System;
namespace DR.Book.SRPG_Dev.Models
{
public interface IModel : IDisposable
{
void Load();
}
}
建立我们的基类:
using System;
namespace DR.Book.SRPG_Dev.Models
{
public class ModelBase : IModel
{
private bool m_Loaded = false;
public bool loaded
{
get {
return m_Loaded; }
}
void IModel.Load()
{
if (m_Loaded)
{
return;
}
OnLoad();
m_Loaded = true;
}
protected virtual void OnLoad()
{
}
void IDisposable.Dispose()
{
if (!m_Loaded)
{
return;
}
OnDispose();
m_Loaded = false;
}
protected virtual void OnDispose()
{
}
}
}
2 管理器(Manager)
管理器我们写过很多,和“事件系统”有点类似,我们只需要作为以下几点:
-
单例;
-
注册与注销;
-
获取。
这里不再过多的说明,直接使用一个字典就可以了:
#region Field
private readonly Dictionary<Type, IModel> m_ModelDict = new Dictionary<Type, IModel>();
#endregion
#region Method
public T Get<T>() where T : class, IModel, new()
{
Type type = typeof(T);
IModel model;
if (!m_ModelDict.TryGetValue(type, out model))
{
RegisterModel<T>();
model = m_ModelDict[type];
}
return model as T;
}
public void RegisterModel<T>() where T : class, IModel, new()
{
Type type = typeof(T);
if (!m_ModelDict.ContainsKey(type))
{
IModel model = new T();
model.Load();
m_ModelDict.Add(type, model);
}
}
public void UnregisterModel<T>() where T : class, IModel
{
Type type = typeof(T);
IModel model;
if (m_ModelDict.TryGetValue(type, out model))
{
model.Dispose();
m_ModelDict.Remove(type);
}
}
public void UnregisterAllModels()
{
foreach (IModel model in m_ModelDict.Values)
{
model.Dispose();
}
m_ModelDict.Clear();
}
#endregion
3 物品模型(Item Model)
就像之前说的,我们的物品模型主要用来存储我们的模板,同时还有生成的物品。
首先,先创建我们的类:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace DR.Book.SRPG_Dev.Models
{
public class ItemModel : Mode