我们打开上一篇36C#拓展 - 优化冗余脚本的项目,

本章要做的事情是编写单例模式基类,让继承其基类的子类在运行时只存在一个,共有两个单例基类框架,分别是不继承MonoBehaviour的单例和继承MonoBehaviour的单例框架
首先编写不继承MonoBehaviour的单例框架
创建你脚本文件夹:

创建脚本:Singleton.cs

cs
using System;
public class Singleton<T> where T : Singleton<T> {
protected Singleton() { }
static object locker = new object();
static T instance;
public static T Instance {
get {
if (instance == null) {
lock (locker) {
if (instance == null)
instance = Activator.CreateInstance(typeof(T),true) as T;
}
}
return instance;
}
}
}
将状态模式的状态执行者设置为运行时只有一个 则继承该单例基类脚本

创建脚本:SingletonMono.cs

cs
using UnityEngine;
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour{
protected SingletonMono() { }
public static bool IsExisted { get; set; } = false;
static T instance;
public static T Instance {
get {
if (instance == null) {
instance = FindObjectOfType<T>();
if (instance == null) {
GameObject go = new GameObject(typeof(T).Name);
instance = go.AddComponent<T>();
IsExisted = true;
}
}
return instance;
}
}
protected virtual void OnDestroy(){
IsExisted = false;
}
protected virtual void Awake(){ }
}
将场景中既继承MonoBehaviour的类又在运行时只有一个对象存在的类继承自SingleMono.cs


运行项目 - 无报错即可
本章做了让场景中的单一脚本只能存在一个的功能
下篇文章的内容:
1.管理器基类
2.窗口可拖拽脚本
3.点击名称寻找地点功能
4.隐藏怪物的生成
5.怪物I攻击范围内的主动攻击
6.掉落坐骑蛋的获取
7.异步传送转换场景
以及开放回合制、坐骑系统、宠物系统、背包系统、神炼系统、商城系统、Boss的目标跟随任务导航系统以及UI播放3D动画效果等等。
具体项目运行效果请关注water1024的b站视频项目演示《破碎纪元》
