Ben*_*bin 2 c# unity-game-engine
GetComponent如果请求的组件没有附加到对象,我对返回值感到困惑.根据Unity文档,GetComponent应该返回null.但是,似乎正在发生的GetComponent是返回所请求类型的"null"对象,而不是值null.
在这个例子中,我的游戏对象没有CircleCollider2D附加到它.当我在线上设置断点时CircleCollider2D x = GetComponent<CircleCollider2D>();,我得到了这个结果
为什么返回的值不是null?
编辑:
另一个编辑:
是不是Unity已经重载了==运算符以便GetComponent总是返回一个对象,但是对象可以有一个内部的"null"状态,当它与null?相比时返回true .我可以在UnityEngine命名空间中看到以下声明
public static bool operator ==(Object x, Object y);
public static bool operator !=(Object x, Object y);
Run Code Online (Sandbox Code Playgroud)
似乎GetComponent<T>()没有返回TRUE null.相反,它返回新T,其默认值MissingComponentException在使用任何空字段时触发.GetInstanceID()并且GetHashCode()工作,因为他们只使用int m_InstanceID设置为默认值0.不确定如何ToString()工作,但它可能返回"null"时m_InstanceID == 0.
证明:
void Start()
{
CircleCollider2D getComponent = GetComponent<CircleCollider2D>();
CircleCollider2D empty = null;
CircleCollider2D newCC = new CircleCollider2D();
Debug.LogFormat("getComponent.GetInstanceID() {0}", getComponent.GetInstanceID());
Debug.LogFormat("newCC.GetInstanceID() {0}", newCC.GetInstanceID());
try
{
Debug.LogFormat("empty.GetInstanceID() {0}", empty.GetInstanceID());
}
catch (System.NullReferenceException e)
{
Debug.Log("empty.GetInstanceID() doesnt work, im true null");
}
try
{
string t = getComponent.name;
}
catch (System.Exception e)
{
Debug.Log(string.Format("getComponent fires {0} when any field is null",
e.ToString()));
}
try
{
string t = newCC.name;
}
catch (System.Exception e)
{
Debug.Log(string.Format("newCC fires {0} when any field is null",
e.ToString()));
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
getComponent.GetInstanceID() 0
newCC.GetInstanceID() 0
empty.GetInstanceID() doesnt work, im true null
getComponent fires UnityEngine.MissingComponentException
newCC fires System.NullReferenceException
Run Code Online (Sandbox Code Playgroud)
也:
getComponent.GetHashCode() = 0
getComponent.ToString() = "null"
Run Code Online (Sandbox Code Playgroud)
为什么getComponent == null是真的?通常它只是:
`getComponent.GetInstanceID() == otherComponent.GetInstanceID()`
Run Code Online (Sandbox Code Playgroud)
在o == null情况下,它是:
return !(
o.GetCachedPtr() != IntPtr.Zero || (!(o is MonoBehaviour) &&
!(o is ScriptableObject) &&
Object.DoesObjectWithInstanceIDExist(o.GetInstanceID())));
Run Code Online (Sandbox Code Playgroud)
所以我认为InstanceID = 0的对象永远不会存在.如果您想了解更多信息,请搜索反编译的UnityEngine/UnityEngine/Object.cs.
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |