单例基类
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class MonoSignal<T> : MonoBehaviour where T : MonoSignal<T>
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType(typeof(T)) as T;
if (instance == null)
{
instance = new GameObject("Chinar Single of " + typeof(T).ToString(),
typeof(T)).GetComponent<T>();
}
}
return instance;
}
}
private void Awake()
{
if (instance==null)
{
instance = this as T;
}
}
private void OnApplicationQuit()
{
instance = null;
}
}
对象池单例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoSignal<ObjectPool>
{
private Dictionary<string, List<GameObject>> cache = new Dictionary<string, List<GameObject>>();
private int i = 0;
public GameObject CreateObject(string key, GameObject go, Vector3 position, Quaternion quaternion)
{
GameObject tempgo = cache.ContainsKey(key) ?
cache[key].Find(p => !p.activeSelf) : null;
if (tempgo != null)
{
tempgo.transform.position = position;
tempgo.transform.rotation = quaternion;
tempgo.name = key;
}
else
{
tempgo = Instantiate(go, position, quaternion);
tempgo.name = key;
print("实例化物体数量:" + i++);
if (!cache.ContainsKey(key))
{
cache.Add(key, new List<GameObject>());
}
cache[key].Add(tempgo);
}
tempgo.SetActive(true);
return tempgo;
}
public void CollectObject(GameObject go)
{
go.SetActive(false);
}
public void CollectObject(GameObject go, float delay)
{
StartCoroutine(Collect(go, delay));
}
private IEnumerator Collect(GameObject go, float delay)
{
yield return new WaitForSeconds(delay);
CollectObject(go);
}
public void Clear(string key)
{
if (cache.ContainsKey(key))
{
for (int i = 0; i < cache[key].Count; i++)
{
Destroy(cache[key][i]);
}
cache.Remove(key);
}
}
public void ClearAll()
{
var list = new List<string>(cache.Keys);
for (int i = 0; i < list.Count; i++)
{
Clear(list[i]);
}
}
}