unity之协程
由于unity是非阻塞运行的程序,所有的物体操作都不会立即执行,而是要在下一帧才开始,所以我们会经常用到协程,尤其是对象操作有前后逻辑的时候,更应该用协成来处理。
//自定义协程方法
public static IEnumerator DestroyComponent<T>(string name,T component, Action onDestroyed = null) where T : Component
{if (component != null){UnityEngine.Object.Destroy(component);// 等待该组件实际被销毁(Unity 是延迟销毁的)while (component != null){yield return null;//等待下一帧}Debug.Log($"{name} 销毁组件");onDestroyed?.Invoke(); //销毁后执行回调方法}
}//启动一个协程
StartCoroutine(DestroyComponent(g.name,g.GetComponent<xxx>(),回调action方法));