如何收集我所有腳本(通用)的名稱(在串列或陣列中?)如下所示?
public class inputdata
{
public Component com;
public int index;
public inputdata(Component newcom,int newindex)
{
com = newcom;
index = newindex;
}
}
inputdata[] data = {new inputdata(component1, 1),inputdata(component2, 1),inputdata(component3, 1)}
foreach (inputdata ft in data)
{
movefunc <ft.com> (ft.index);
}
void movefunc <T> (int index){
gameobject.GetComponent<T>()
}
它顯示“component1”是一種型別,在給定的背景關系中無效。
component1 是我的 c# 腳本,我用它來檢測光線投射。
像這樣
hitInfo.collider.gameObject.GetComponent <component1 > ()
uj5u.com熱心網友回復:
似乎不清楚您要實作的目標。如果它有幫助,您可以像這樣獲得游戲物件中的組件串列:
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class GetComponets : MonoBehaviour {
public GameObject goWithComponets; //attach in the inspector
void Start() {
getComponets().ToList().ForEach(component => {
Debug.Log(component.GetType().ToString());
});
}
private IEnumerable<Component> getComponets() {
return goWithComponets.GetComponents<Component>().ToList(); ;
}
}
您的組件不會是通用的,它們肯定會從Component型別繼承,因此如果需要,您可以從 gameObject 獲取所有組件,從基類獲取所有組件Component,如果您需要處理特定型別,請稍后處理用一些代碼。
uj5u.com熱心網友回復:
聽起來像你不想要一個通用的,而是像例如
public class inputdata
{
public Type Type;
public int Index;
public inputdata(Type type, int index)
{
Type = type;
Index = index;
}
}
inputdata[] data = new []
{
new inputdata(typeof(component1), 1),
new inputdata(typeof(component2), 1),
new inputdata(typeof(component3), 1)
};
接著
foreach (inputdata ft in data)
{
movefunc (ft.type, ft.index);
}
和
void movefunc (Type type, int index)
{
// ... whatever happens before and where you get the hitInfo from
if(hitInfo.collider.TryGetComponent(type, out var component))
{
// component of given type exists on the hit object
// "component" will contain a reference to it in the base type "Component" -> if you need it in its actual type you will need to cast
}
else
{
// there is no component of given type on the hit object
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/403248.html
標籤:
上一篇:如何將png轉換為字體
