一、起因:
沒啥,看到了,寫寫而已。
二、實現方式:
首先貼一下代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TryGetComponentTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("GetKeyDown KeyCode.Space");
if (gameObject.transform.TryGetComponent<BoxCollider>(out BoxCollider boxC))
{
Debug.Log($"we get boxCollider:{boxC}");
}
else
{
Debug.Log("we not get boxCollider。");
}
if (gameObject.transform.TryGetComponent<Transform>(out Transform tran))
{
Debug.Log($"we get Transform:{tran}");
}
else
{
Debug.Log("we not get Transform。");
}
}
}
}
運行結果如圖:
其次說明一下,這個方法必須要在2019.2以後才能用。
另外,據說是這個方法不會分配內存。原文如下:
Using TryGetComponent will not allocate memory in case it fails and is available since 2019.2.
三、反編譯:
反編譯看了下c#層的代碼,如圖:
// UnityEngine.GameObject
[SecuritySafeCritical]
public unsafe bool TryGetComponent<T>(out T component)
{
CastHelper<T> castHelper = default(CastHelper<T>);
this.TryGetComponentFastPath(typeof(T), new IntPtr((void*)(&castHelper.onePointerFurtherThanT)));
component = castHelper.t;
return castHelper.t != null;
}
// UnityEngine.GameObject
[FreeFunction(Name = "GameObjectBindings::TryGetComponentFastPath", HasExplicitThis = true, ThrowsException = true), NativeWritableSelf]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern void TryGetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue);