从碰撞体访问游戏对象属性



所以我有一枚导弹。当它击中目标时,导弹爆炸。
爆炸有一个半径,里面可能有很多敌人。
敌人有一个"脚本/公共变量"爆炸预制件。
我发现所有敌人都在使用导弹移动类中的碰撞体:

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

如何通过变身进入敌人的爆炸预制件?

编辑 - 阅读后...

我的问题是爆炸预制件(敌方移动类(被定义为变换。它现在是一个游戏对象。它有效:(

但是,实例化爆炸会引发"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);
}

例外:

无效强制转换

异常:指定的强制转换无效。
(包装演员表(System.Object.__castclass_with_cache(object,intptr,intptr(
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation( (at C:/
buildslave/unity/build/Runtime/Export/Scripting/UnityEngineObject.bindings.cs:276(BulletMove.Damage (UnityEngine.GameObject enemy( (at Assets/Scripts/BulletMove.cs:60(BulletMove.HitTarget (( (at Assets/Scripts/BulletMove

.cs:49(
BulletMove.Update (( (at Assets/Scripts/子弹移动.cs:26(

使用Physics.OverlapSphere时,你可以在敌人中使用GetComponentInChildrenGetComponent,然后从该职业中获得相应的爆炸。

最新更新