【问题标题】:Access gameobjects properties from collider从对撞机访问游戏对象属性
【发布时间】:2019-09-12 11:31:31
【问题描述】:

所以我有一枚导弹。当它击中目标时,导弹会爆炸。
爆炸有一个半径,里面可能有很多敌人。
敌人有一个“脚本/公共变量”爆炸预制件。
我在 MissileMove 类中找到所有使用对撞机的敌人:

Collider[] colliders = Physics.OverlapSphere( transform.position, explosionRadius );
    foreach (Collider coli in colliders)
        if (coli.tag == "Enemy")
            Damage( coli.gameObject);

我如何通过变换访问敌人的爆炸预制件?

编辑 - 阅读后...

我的问题是explosionPrefab(enemyMove 类)被定义为一个Transform。它现在是一个游戏对象。它有效:)

但是,实例化爆炸会引发“invalidCastException”并退出函数。爆炸运行(!),但函数的其余部分被跳过 - 敌人幸存下来!

但如果我将相同的爆炸预制件“附加”到本地脚本 (MissileMove),并改为使用它,它会正常运行(不抛出异常) - 有什么区别?

void Damage( GameObject enemy )
{
    GameObject exp = enemy.GetComponent<EnemyMove>().explosionPrefab;

    Debug.Log("Start EnemyExplosion");

    // Below throws exception, runs, then quits function
    GameObject explosion = Instantiate( exp, enemy.transform.position, enemy.transform.rotation);

    // Below runs perfectly
    GameObject explosion = Instantiate( enemyExplosion, enemy.transform.position, enemy.transform.rotation);

    Destroy(explosion, 2f);

    Debug.Log("EnemyExplosion startet");

    Destroy(enemy);
}

例外:

InvalidCastException:指定的强制转换无效。
(wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 位置, UnityEngine.Quaternion 旋转) (at
C:/buildslave/unity/build/Runtime/Export/Scripting/UnityEngineObject.bindings.cs:276)
BulletMove.Damage(UnityEngine.GameObject 敌人)(在 Assets/Scripts/BulletMove.cs:60)
BulletMove.HitTarget () (在 Assets/Scripts/BulletMove.cs:49)
BulletMove.Update () (在 Assets/Scripts/BulletMove.cs:26)

【问题讨论】:

  • 不太清楚你在问什么......你想要coli.gameObject?或coli.transform.gameObject(基本相同,但第一个 API 调用较少)。或使用coli.GetComponent&lt;YourClass&gt;().explosionPrefab
  • 啊,这就是 getComponent 的用途:) - 我会尝试...
  • enemyExplosionexp 有什么区别?这一行是否抛出异常?或者他们可能在发生这种情况的地方附加了一些组件?你能发布完整的异常输出吗?
  • 没有区别 - 它是同一个预制件

标签: unity3d transform gameobject


【解决方案1】:

您可以在使用Physics.OverlapSphere 时在敌人中使用GetComponentInChildrenGetComponent,然后从该类中获取相应的爆炸。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多