目录
1.Mono扩展
public static class MonoPlus
{
/// 给组件设置物体激活的能力
public static void SetActive(this Component com, bool flag)
{
if (com != null && com.gameObject.activeSelf != flag)
{
com.gameObject.SetActive(flag);
}
}
/// 判断string 是不是null
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
/// <summary>
/// 异步重载
/// </summary>
/// <param name="asyncOp"></param>
/// <returns></returns>
public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
{
var tcs = new TaskCompletionSource<object>();
asyncOp.completed += obj => { tcs.SetResult(null); };
return ((Task) tcs.Task).GetAwaiter();
}
}
2.缓存生成对象
public Transform content;
public ListItem listOri;
private List<ListItem> listItems = new List<ListItem>();
public void InitList(List<DataStuct> listDatas)
{
int count = listDatas.Count;
int count2 = listItems.Count;
//关闭多余的对象
for (int i = count2 - 1; i >= 0; i--)
{
if (i >= count)
{
listItems[i].gameObject.SetActive(false);
}
}
//重置数据
for (int i = 0; i < count; i++)
{
ListItem temp;
if (i >= listItems.Count)
{
//新建
temp = Instantiate(listOri, content);
listItems.Add(temp);
}
else
{
//赋值
temp = listItems[i];
}
//重新给数据
temp.SetData(i + 1, listDatas[i].name, listDatas[i].time);
temp.gameObject.SetActive(true);
}
}
3.事件回调工具
新版本请看这里 点我点我。(2022-0808)
新版本在上边连接。下方代码已过时,大概思路如下:
public class TimeCallBack
{
public class TimeItem
{
public bool cancle = false;
public Action<TimeItem> OnOver;
private float timeCounter = 0;
public async void Invoke(float timecount, Action callback)
{
cancle = false;
timeCounter = timecount * 100;
while (timeCounter > 0)
{
if (cancle)
{
return;
}
timeCounter -= 1;
await Task.Delay(10);
}
cancle = true;
OnOver?.Invoke(this);
callback?.Invoke();
}
}
private List<TimeItem> runningList = new List<TimeItem>();
private List<TimeItem> storeList = new List<TimeItem>();
public void CreateInvoke(float timecount, Action callback)
{
TimeItem temp;
if (storeList.Count > 0)
{
temp = storeList.Last();
}
else
{
temp = new TimeItem();
temp.OnOver += OnOver;
Debug.Log("new one timer");
}
temp.Invoke(timecount, callback);
runningList.Add(temp);
}
private void OnOver(TimeItem obj)
{
obj.cancle = true;
runningList.Remove(obj);
storeList.Add(obj);
}
public void Dispose()
{
int count = runningList.Count;
for (int i = count - 1; i >= 0; i--)
{
var temp = runningList[i];
temp.OnOver?.Invoke(temp);
}
}
}
4.通过IsAssignableFrom 获取接口对象
MonoBehaviour[] monoScripts = FindObjectsOfType(typeof(MonoBehaviour)) as MonoBehaviour[];
foreach (MonoBehaviour monoScript in monoScripts)
{
if(typeof(KinectGestures.GestureListenerInterface).IsAssignableFrom(monoScript.GetType()) &&monoScript.enabled)
{
gestureListeners.Add(monoScript);
}
}
5.C#获取本地IP地址 local
var ip= Dns.GetHostEntry(Dns.GetHostName()).
AddressList.FirstOrDefault
(ip => ip.AddressFamily ==
System.Net.Sockets.AddressFamily.InterNetwork);
Debug.Log(ip);