c# - 团结 | 未知类的调用方法
问题描述
我有Health.cs
我所有的enemy
对象。
当enemy
受到伤害时,我想在不同的类别中提醒这一点。(取决于enemy
类型)
所以在Health.cs
我添加public UnityEngine.Object alertInScript;
我alertInScript
通过 Unity Editor 进行更改。我把我想提醒的课程放在那里。
每个alertInScript
类都有相同的方法DamageAlert
但我不能调用它,因为 c#alertInScript
在游戏开始之前看不到这个类。
所以我总是出错。
我在 c# 和统一中是 noobo,请告诉我这是否可能。
或者我如何使用其他方法获得相同的结果?
解决方案
引用 EnemyBear.cs(源代码文件)是无效的。永远不要这样做,因为它们只是在编辑器中作为源(代码)资产存在。您需要做的是改为引用特定的组件或编写代码,以便某些特定的 GetComponent 模式可以找到这些组件
接口是这里的方式:
public interface IHealthAlert
{
void Alert ( Health health );
}
实现这样的接口:
public class AlertedComponent : MonoBehaviour, IHealthAlert
{
void IHealthAlert.Alert ( Health health)
{
Debug.Log( "alerted!" , gameObject );
}
}
并将其添加AlertedComponent
到Health
(完全相同的游戏对象)旁边
然后在 Health.cs 中这样调用它:
var components = GetComponents<IHealthAlert>();
foreach( var comp in components )
{
comp.Alert( this );
}
推荐阅读
- python - 尝试将 BufferedReader 上传到 Python 中的 Azure Blob 存储时,base64 编码的字符串无效
- spring-kafka - 创建消费者绑定失败;30 秒后重试:BinderException
- php - WP All Import - 在属性项中从函数编辑器映射值
- r - 理解 R 中的警告信息
- c# - 我可以知道谁与我的 TCP 服务器断开连接吗?C#
- c# - 异步合理性检查会导致出现竞争条件吗?
- flutter - 如何在 Flutter 应用程序中使用 ListTile 记住和突出显示选定的抽屉项目?
- google-analytics - 如何禁用/启用使用 GTM 动态实现的 Google 分析
- python - 谷歌趋势历史数据如何变化?
- robots.txt - AASA 文件验证问题