c# - 从父对象调用方法 C# Unity3d

标签 c# unity-game-engine


我正在 Unity 中创建塔防游戏,但遇到了问题。
我有单位类,其中我的怪物有生命值、伤害、类型、速度等参数和方法 Hit(int Damage) (损害单位)。我为每种类型的单位都有一个类:战士,游侠,法师等,继承单位类
当生物进入其触发区域时,塔开始射击。塔楼没有子弹、导弹或其他任何东西可以发射。问题是,如何从 tower 的脚本中调用该 Hit 方法?
对于每个单元,我都有预制件,上面有 2 个脚本:单元和坦克。我想这是不对的,因为我有 2 个单位类:一个只是单位,另一个由坦克等继承。 所以这似乎不对:

    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.

那么调用 Hit 的正确方法是什么?

最佳答案

以下代码将检索 Unit 对象,即使它是继承类型。

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

但是,

For every unit I have prefab with 2 scripts on it: Unit and, for example, Tank. I guess it's not right because thus I have 2 Unit classes: one just Unit and one inherited by, for example, Tank.

这听起来不对 - 你不应该在同一个游戏对象上拥有 Unit Unit 的继承类。我认为您可能需要重新审视自己的做事方式。有很多方法可以实现我认为您想要实现的目标。这是我最近使用的一个:


接口(interface)

这是我个人首选的方法。您将接口(interface)应用于每个类 - 战士、法师等。其中一个接口(interface)可以是 IDamagable,它将定义一些属性,例如 Health、TakeDamage(int) 等。

如果你以前没有使用过界面,我发现了这个Unity3D特定的video tutorial here .

我还使用了这个奇妙的扩展方法,您可以将其放入Utilities类中的某个位置:

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();
}

关于c# - 从父对象调用方法 C# Unity3d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252849/

相关文章:

ios - 在 iOS 中找不到模块 'GoogleMobileAds'

c - 如何用C语言集成语音到字符串检测器

c# to vb using Sync Framework 奇怪的错误

c# - 构造函数可访问性 C# 编译器错误 CS0122 与 CS1729

android - Unity项目导出到android项目异常(多个dex文件定义Lcom/qualcomm/QCARUnityPlayer/BuildConfig)

c++ - 统一3D :access to Unity 3D API from C/C++ code

unity-game-engine - unity "Broken text PPtr - Local file identifier doesn' t 合并后场景文件中存在“错误”

c# - 使用 C# 和 Json.Net 进行解析

c# - revEng 命令现在需要提供程序。应该通过什么?

c# - IIS 日志问题