#region 单例
public interface ISingleton
{
}
public abstract class Singleton<T> where T : class, ISingleton
{
private static T mInstance;
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = MyExtension.GetMonoOrPrivateClass<T>();
}
return mInstance;
}
}
}
#endregion
public static T GetMonoOrPrivateClass<T>() where T : class
{
T obj = default(T);
var type = typeof(T);
var monoType = typeof(MonoBehaviour);
if (monoType.IsAssignableFrom(type))
{
obj = GetMonoClass<T>();
}
else
{
obj = GetPriClass<T>();
}
return obj;
}
以下为GetMonoClass分支:
[AttributeUsage(AttributeTargets.Class)]
public class PathInHierary : Attribute
{
private string mPath;
public PathInHierary(string path)
{
mPath = path;
}
public string Path { get { return mPath; } }
}
[MyExtension.PathInHierary("GameFramework/Examples/Test11")]
public class Test1
{
}
private static T GetMonoClass<T>() where T : class
{
GameObject game = FindGameobject<T>();
if(game == null)
{
game = new GameObject(typeof(T).Name);
}
return game.AddComponent(typeof(T)) as T;
}
private static GameObject FindGameobject<T>()
{
string path = string.Empty;
var type = typeof(T);
var cus = type.GetCustomAttributes(true);
foreach (var c in cus)
{
var monoPath = c as PathInHierary;
if(monoPath != null)
{
path = monoPath.Path;
}
}
GameObject obj = FindGameobject(path);
return obj;
}
private static GameObject FindGameobject(string path, bool isNew = true)
{
string[] subPaths = path.Split('/');
GameObject obj = FindGameobject(null,subPaths,0,isNew);
return obj;
}
private static GameObject FindGameobject(GameObject root,string[] subPaths, int index, bool isNew)
{
GameObject tmep = null;
if(root == null)
{
tmep = GameObject.Find(subPaths[index]);
}
else
{
var trans = root.transform.Find(subPaths[index]);
if(trans != null)
{
tmep = trans.gameObject;
}
}
if (tmep == null)
{
if (isNew)
{
tmep = new GameObject(subPaths[index]);
if (root != null)
{
tmep.transform.SetParent(root.transform);
}
}
else
{
throw new Exception("没有该游戏对象");
}
}
root = tmep;
return ++index < subPaths.Length ? FindGameobject(root, subPaths, index, isNew) : root;
}
以下为私有的普通类
private static T GetPriClass<T>() where T : class
{
var type = typeof(T);
var cons = type.GetConstructors(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var employCon = Array.Find(cons, c => c.GetParameters().Length == 0);
return employCon.Invoke(null) as T;
}
使用方法:
public class Test2 : MonoBehaviour
{
void Start()
{
Test11 test11 = Test11.Instance;
Test12 test12 = Test12.Instance;
test12.Print();
}
void Update()
{
}
}
public class Test12 : ISingleton
{
public static Test12 Instance => Singleton<Test12>.Instance;
private Test12()
{
}
public void Print()
{
Debug.Log("私有类的输出");
}
}
[MyExtension.PathInHierary("GameFramework/Examples/Test11")]
public class Test11 : MonoBehaviour, ISingleton
{
public static Test11 Instance => Singleton<Test11>.Instance;
private void Start()
{
Debug.Log("成功被创建");
}
}
|