1、if做边界或者异常判断的时候,一定不要忘了在else里打上log,加一句log远比出了bug一遍遍的缕代码逻辑的成本低得多。
if (obj != null) { } else { Debug.Log("obj is null"); }
2、在用for循环生成线程时,如果用到了“i”,要给他一个临时变量接收着,不然会出错,如:
void Wrong() { for (int i = 0; i < 10; i++) { new Thread(() => { Debug.Log(i); }).Start(); } }
结果有重复值且并不是每个 i 都被打印了出来
正确的写法是
void Right() { for (int i = 0; i < 10; i++) { int j = i; new Thread(() => { Debug.Log(j); Thread.Sleep(100); }).Start(); } }
可以看出结果是正确的