2013-11-27 25 views
2


我在Unity中创建了塔防游戏,并且遇到了问题。
我有班级单位,我的小怪有类似HP的伤害,伤害,类型,速度等等和方法Hit(int damage)(伤害单位)。而且我还有一种类型的单位:继承单位类的战士,游侠,法师等等。
当暴徒进入触发区时塔开始射击。塔没有子弹,导弹或任何其他射击。问题是,如何从tower的脚本中调用Hit方法?
对于我预先制作了2个脚本的每个单元:单元和例如Tank。我想这是不对的,因为我有2个单位类:一个是单位,一个是坦克继承的单位。 所以这似乎并不正确:来自父对象C#的调用方法Unity3d

if (obj.GetComponent<Unit>()) obj.GetComponent<Unit>().Hit(dmg); 

而且我认为这是不正确的检查是这样的:

if (obj.GetComponent<Tank>()) obj.GetComponent<Tank>().Hit(dmg); 
    else if (obj.GetComponent<Warrior>()) obj.GetComponent<Warrior>().Hit(dmg); 
    else ... etc. 

那么什么是选召,打正确的方式?

回答

2

以下代码将检索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(); 
} 
+0

感谢。我刚分裂单位和其他人。可能不是很好的解决方案,但在我的情况下完美。并感谢您的链接。我甚至没有听说过Unity的这种事情。 – user3043365