簡體   English   中英

GetComponent<"type">() 的類型是什么? 團結一致

[英]what is the type of the GetComponent<"type">()? in unity

我需要寫一個 function 並在其中輸入值我嘗試使用字符串,然后是 GetType,但它不起作用。 並使用 MonoBehaviour 它;沒有用。 我錯過了什么?

void move(MonoBehaviour co){
            Touch screentouch = Input.GetTouch(0);
            Ray ray = camera.ScreenPointToRay(screentouch.position);
            if (screentouch.phase == TouchPhase.Began)
            {
                if (Physics.Raycast(ray, out RaycastHit hitInfo))
                {
                    if (hitInfo.collider.gameObject.GetComponent<co>() != null)
                    {
                        set = true;

                    }
                }
}

GetComponent<T>是一種所謂的泛型方法。

泛型類型參數T需要是編譯時常量類型,例如

Renderer renderer = someGameObject.GetComponent<Renderer>();

將返回Renderer類型的實例。


GetComponent(Type type)GetComponent(string typeName)的其他重載都返回最基本的Component類型,為了正確使用它,您必須在之后鍵入轉換結果。

同樣的例子看起來像

Renderer renderer = (Renderer) someGameObject.GetComponent(typeof(Renderer));

或者

Renderer renderer = (Renderer) someGameObject.GetComponent("Renderer");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM