Unity3D 中的 C# 脚本环境(在 Mono 下运行)在销毁对象时具有良好的行为。所有指向被销毁对象的引用都会自动变为 null :
GameObject ref1 = (GameObject)Instantiate(obj);
GameObject ref2 = ref1;
if (ref1 != null)
Debug.Log("ref1 is not null");
DestroyImmediate(ref1);
if (ref1 == null)
Debug.Log("ref1 is null");
if (ref2 == null)
Debug.Log("ref2 is null");
输出:
ref1 is not null
ref1 is null
ref2 is null
关于如何实现这一点有什么想法吗?
谢谢
最佳答案
也许相等运算符已被覆盖?这可以解释您的评论:“只是发现如果 ref1 和 ref2 不是 GameObject 而是 System.Object,那么它就不会工作。”
关于C# 自动引用分配 - 使引用为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128964/