[英]Unity C# : custom Object is null BUT I can access its properties
I found a way to get around this issue in the code, but I would like to understand why this is happening because I want to learn C# well. 我在代码中找到了解决此问题的方法,但是我想了解为什么会这样,因为我想很好地学习C#。 I´ve searched a lot and could simplify the problem, here's the simplified code:
我进行了很多搜索,可以简化问题,这是简化的代码:
/*MyCustomComponent.cs, this is attached to a game object in the scene*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MyCustomComponent : MonoBehaviour {
void Start () {
Test testInstance = new Test();
Debug.Log (testInstance);
Debug.Log (testInstance == null);
Debug.Log (testInstance.Equals(null)); //Also tried the same with Equals()
Debug.Log (testInstance.value);
}
}
/*Test.cs*/
using UnityEngine;
using System.Collections;
public class Test : Object {
public int value = 7;
public Test(){
}
}
Console Output: 控制台输出:
null
true
7
Why is this happening? 为什么会这样呢? How can be possible an Object is null but returns a property value?
Object如何可能为null但返回属性值?
Because Unity.Object
works in a very peculiar way, basically it contains data regarding the managed object while pointing to the native object (crudely speaking). 因为
Unity.Object
工作方式非常特殊,所以基本上它包含指向托管对象的数据,同时指向本地对象(粗略地说)。
Let's make an example: you create a new object inheriting from MonoBehaviour
. 让我们举个例子:您创建一个继承自
MonoBehaviour
的新对象。 Now you have two objects, one on the native side and one on the managed side. 现在,您有两个对象,一个在本机端,一个在托管端。 You can access the
instanceID
propriety of the managed object thanks to the fact that MonoBehaviour
inherits from Unity.Object
. 由于
MonoBehaviour
继承自Unity.Object
,因此您可以访问托管对象的instanceID
适当性。 Basically, the latter is used to show all the relative data of the object in the Inspector. 基本上,后者用于显示检查器中对象的所有相关数据。
Now, you want to Destroy
this game object by calling the same named method. 现在,您要通过调用相同的命名方法来
Destroy
此游戏对象。 The native object is actually destroyed, but the managed object is not, since all managed objects can only be destroyed by the garbage collector. 实际上,本机对象已被销毁,但托管对象并未被销毁,因为所有托管对象只能由垃圾收集器销毁。 It's at this point that
Unity.Object
becomes null
: it's a trick of the Unity engine uses in order to avoid that you try to access a native object which doesn't exist anymore. 此时,
Unity.Object
变为null
:这是Unity引擎使用的技巧,以避免您尝试访问不再存在的本机对象。 Eventually, when the GC is called, this Unity.Object
will be destroyed too. 最终,当调用GC时,该
Unity.Object
也将被销毁。
And this is why you should never create an Unity object which inherits directly from Unity.Object
, but only from MonoBehaviour
or ScriptableObject
. 这就是为什么永远不要创建直接继承自
Unity.Object
,而只能继承自MonoBehaviour
或ScriptableObject
的Unity对象的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.