以下代碼將檢索Unit對象,即使它是繼承類型。
if (obj.GetComponent<Unit>()) obj.GetComponent<Unit>().Hit(dmg);
然而,
對於每一個單位我有預製有2個腳本就可以了:單位,並且對於 例如坦克。我想這是不對的,因爲我有2個單位 職業:一個只是單位,一個例如坦克繼承。
這不健全的權利 - 你不應該有單位和在同一個遊戲對象繼承的類股。我想你可能需要重新審視自己如何做事。有很多方法可以實現我認爲你想實現的目標。這是一個我最近使用:
接口
這是我個人的首選方法。您可以將接口應用到每個類 - 戰士,法師等等。一個這樣的接口可以是IDamagable,它將定義一些屬性,如Health,TakeDamage(int)等。
如果您之前沒有使用過接口,我發現這個Unity3D具體video tutorial here。
我也用這個夢幻般的擴展方法,你可以拖放到公用事業類的地方:
using System.Linq;
using UnityEngine;
public static class Utilities {
public static T GetInterface<T>(this GameObject inObj) where T : class {
if (!typeof (T).IsInterface) {
Debug.LogError(typeof (T).ToString() + ": is not an actual interface!");
return null;
}
return inObj.GetComponents<Component>().OfType<T>().FirstOrDefault();
}
public static IEnumerable<T> GetInterfaces<T>(this GameObject inObj) where T : class {
if (!typeof (T).IsInterface) {
Debug.LogError(typeof (T).ToString() + ": is not an actual interface!");
return Enumerable.Empty<T>();
}
return inObj.GetComponents<Component>().OfType<T>();
}
}
您可以使用此代碼如下所示:
var item = someGameObject.GetInterface<IItem>();
if (item != null) {
// Access a Property from IItem in here:
item.Drop();
}
感謝。我剛分裂單位和其他人。可能不是很好的解決方案,但在我的情況下完美。並感謝您的鏈接。我甚至沒有聽說過Unity的這種事情。 – user3043365