以下代码将检索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