我正在為某些物件使用組件系統(就像 Unity 中的組件一樣)。每個組件都繼承自Component類。然后這些物件有一個組件串列。
我想要實作的是一個GetComponent()方法。如果存在則回傳型別T的組件,否則回傳 null。假設一個物件具有渲染器組件。我希望能夠在 Renderer 類中呼叫 Draw 方法:
Object.GetComponent<Renderer>().Draw();
問題是當我呼叫這個函式時,我得到了父類(型別:Component)而不是子類。因此,當我嘗試上面的代碼時 ^^ 我得到了錯誤;“組件”不包含“繪圖”的定義(...)
代碼:
internal abstract class GameObject : Object
{
//Props
public string name;
public GameObject? parent;
public Transform transform
{
get
{
return (parent == null) ? transform : parent.transform;
}
private set
{
transform = value;
}
}
public bool isActive = true;
private List<Component> components = new List<Component>();
//Constructer
public GameObject(string name, GameObject? parent = null)
{
this.name = name;
transform = new Transform(this);
components.Add(transform);
this.parent = parent;
}
public void AddComponent(Component component)
{
components.Add(component);
}
//Method that is not working properly
public Component GetComponent<T>()
{
foreach (Component component in components)
{
if (typeof(T) == component.GetType())
return component;
}
return null;
}
}
}
uj5u.com熱心網友回復:
與其回傳Component,不如回傳T。此外,is用于型別檢查和強制轉換:
public T GetComponent<T>() where T : Component
{
foreach(var component in components)
{
if(component is T value) return value;
}
return default;
}
順便說一句,如果您有兩個相同型別的組件怎么辦?您可能要考慮OfType<T>()在這里使用 Linq而不是foreach.
uj5u.com熱心網友回復:
方法的回傳值需要是 T
public T GetComponent<T>()
{
// your code
}
GetComponent<Renderer>().Draw() 是 2 個陳述句
GetComponent<Renderer>()Draw()
通過這樣寫:
// 'component' is of type 'Component' here, not 'Renderer'
var component = GetComponent<Renderer>();
component.Draw();
很明顯為什么它不適用于您當前的代碼以及為什么它適用于更新的代碼。
PS 我個人還會添加一個約束,以確保我們只能GetComponent<T>使用實際上是組件的型別,如下所示:
public T GetComponent<T>() where T : Component
{
}
隨著where我們強制編譯時檢查這個方法只能用繼承自的型別呼叫Component
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409821.html
標籤:
上一篇:如何保存用戶可以訪問的動態檔案?
下一篇:具有多變數函式的回歸
