【发布时间】:2021-07-19 20:13:42
【问题描述】:
我有一个 inv 系统,您可以在其中创建项目并为它们提供脚本以在满足某些条件时执行。问题是我尝试使用 UnityEvents,但我对项目使用了 Scriptable 对象,所以我不能只调用运行时函数。然后,我尝试使用一个空的游戏对象来保存所有项目脚本,基本上,如果你给出项目脚本的名称,inv 系统将调用项目脚本上的一个函数。但问题是我不能只将字符串转换为可以调用函数的类。
所以很久以后我想出了这个
try
{
// scriptHolder = the gameobject where all the item scripts are
Type type = scriptHolder.GetComponent(ondrop[i]).GetType();
object instance = Activator.CreateInstance(type);
type.GetMethod("onDropInv").Invoke(instance, null);
}
catch { }
但问题是我需要在统一使用的脚本的当前实例上调用该函数。所以我尝试了最后 24 小时,现在我放弃了。我只是想不出任何解决方案或替代方案。
【问题讨论】:
-
你已经这样做了:type.GetMethod("onDropInv")
-
如果您希望函数使用现有实例,请传递现有实例并停止使用
Activator创建新实例。 -
例如
instance = scriptHolder.GetComponent(ondrop[i]); type = instance.GetType();