[英]Get components that derive from base class c#
我在ac#環境中工作,正在創建基類,並且希望擁有其他類,如StormyWeather.cs
或SunnyWeather.cs
並讓這些類從基類BaseWeather.cs
public class BaseWeather: MonoBehaviour{
public ParticleSystem particleSystem;
public AudioClip weatherAudio;
public string Name;
public float AudioFadeTime = 0.25f;
public float LightDimTime = 0.1f;
public float MinimumIntensity = 0f;
public float MaximumIntensity = 1f;
public float Intensity = 0.25f;
private void Start(){
particleSystem.enableEmission = false;
}
public virtual void Weather (){
if (WeatherSystem.Instance._debugState == DebugLevel.Full) {
Debug.Log (Name + " Starting at: " + Time.timeSinceLevelLoad);
}
particleSystem.enableEmission = true;
}
}
因此, SunnyWeather.cs
可能看起來像這樣
public class SunnyWeather : BaseWeather {
public override void Weather(){
base.Weather ();
}
}
我如何查找/獲取從BaseWeather.cs
派生的BaseWeather.cs
上的第一個腳本
為了闡明我使用的是統一性, SunnyWeather.cs
將附加到gameObject上,我想知道如何在從BaseWeather.cs
類繼承(更好地講)的BaseWeather.cs
上找到第一個組件
原因是對於每種天氣SunyWeather.cs, StormWeather.cs, SnowWeather.cs
我將有多個腳本,如SunyWeather.cs, StormWeather.cs, SnowWeather.cs
,它們均源自BaseWeather.cs
類
編輯:
我目前正在使用它來調用它,但是不知道這樣做是否正確GetComponent<BaseWeather>().Weather();
為了回答您的大多數擔憂,我可以說是的,您目前正在以正確的方式進行操作,但前提是它符合您的需求 。
GetComponent
將返回與您的查詢匹配的第一個組件,在這種情況下,該類型可以由組件類型分配。 這意味着,如果您將基類放入查詢中,它將返回您首次出現的派生類型或該類型。
為了確保這是正確的組件,您可以使用檢查器視圖將其放置在其他組件之上,或者通過調用GetComponents
對其進行過濾,然后遍歷所有匹配的組件。
BaseWeather
,如果您有多個BaseWeather
組件,則應使用GetComponents<BaseWeather>
方法,而在任何其他情況下,只要使用GetComponent<BaseWeather>
方法就可以過濾出BaseWeather
組件。
如果我理解這個問題,則可以使用以下方法來識別繼承:
(from assemblies in AppDomain.CurrentDomain.GetAssemblies()
from types in assemblies.GetTypes()
where typeof(IWeatherState).IsAssignableFrom(types)
select types
).ToArray();
但是,要獲得“第一”,您將需要做一些硬編碼,例如隊列或堆棧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.