GetComponent(Type customType) 的行为不同于 GetComponent<customType>

GetComponent(Type customType) behaving differently than GetComponent<customType>

我有这个方法 'SetStats',它是 class 的一部分。

public class HeroUnit: MonoBehaviour {
    public virtual void SetStats(Stats stats) => Stats = stats;
}

当我通过指向预制件来实例化游戏对象,然后将已知类型的组件 'HeroUnit' 附加到它时,我可以毫无问题地调用 SetStats 方法。

void SpawnUnit(Vector3 pos) {
    var spawnedGameObject = Instantiate(unitPrefab, pos, Quaternion.identity,transform) as GameObject; 
    var spawned = spawnedGameObject.GetComponent<HeroUnit>();

    spawned.SetStats(stats);
}

但是,当我不强制使用已知的组件类型时,我宁愿将它动态地提供给 GetComponent() 方法:实例化有效,但我不能再调用 SetStats 方法。

void SpawnUnit(String myUnit, Vector3 pos) {
    var spawnedGameObject = Instantiate(unitPrefab, pos, Quaternion.identity,transform) as GameObject; 
    Type unitType = Type.GetType(myUnit);
    var spawned = spawnedGameObject.GetComponent(unitType);

    spawned.SetStats(stats);
}

这个returns下面的编译错误:

错误 CS1061:'Component' 不包含 'SetStats' 的定义并且没有可访问的扩展方法 'SetStats' 接受类型 'Component' 的第一个参数可以找到

知道如何让编译器在代码为 运行 时理解 'spawned' 不是 'Component' 吗?我在运行时检查了 'spawned' 类型,它应该是 'HeroUnit'。

去掉var,看看它是否能编译。我不认为你得到 HeroUnit,我认为你得到 Component

尝试转换 GetComponent 的结果,例如

HeroUnit spawned = (HeroUnit) spawnedGameObject.GetComponent(unitType);

我还要说,将类型作为字符串传递是个坏主意。您从某处获得了字符串,因此只需使用类型而不是字符串。

你可能会回来抱怨你的 unitType 不一定是 HeroUnit,对此我会回答,“那你怎么知道它有一个 SetStats 方法?”。 =15=]

转换为基础 class 或接口可能会更好,但字符串业务同样对您没有帮助。