首页 > 解决方案 > 团结 | 未知类的调用方法

问题描述

我有Health.cs我所有的enemy对象。

enemy受到伤害时,我想在不同的类别中提醒这一点。(取决于enemy类型)

所以在Health.cs我添加public UnityEngine.Object alertInScript;

alertInScript通过 Unity Editor 进行更改。我把我想提醒的课程放在那里。

每个alertInScript类都有相同的方法DamageAlert

但我不能调用它,因为 c#alertInScript在游戏开始之前看不到这个类。

所以我总是出错。

我在 c# 和统一中是 noobo,请告诉我这是否可能。

或者我如何使用其他方法获得相同的结果?

在此处输入图像描述

标签: c#unity3d

解决方案


引用 EnemyBear.cs(源代码文件)是无效的。永远不要这样做,因为它们只是在编辑器中作为源(代码)资产存在。您需要做的是改为引用特定的组件或编写代码,以便某些特定的 GetComponent 模式可以找到这些组件


接口是这里的方式:

public interface IHealthAlert
{
    void Alert ( Health health );
}

实现这样的接口:

public class AlertedComponent : MonoBehaviour, IHealthAlert
{
    void IHealthAlert.Alert ( Health health)
    {
        Debug.Log( "alerted!" , gameObject );
    }
}

并将其添加AlertedComponentHealth(完全相同的游戏对象)旁边

然后在 Health.cs 中这样调用它:

var components = GetComponents<IHealthAlert>();
foreach( var comp in components )
{
    comp.Alert( this );
}

推荐阅读