So I have a missile. When it hits its target the missile explodes.
The explosion has a radius, inside which may be many enemies.
The enemies have a "scripted/public variable" explosionPrefab.
I find all the enemies using colliders in MissileMove class:
Collider[] colliders = Physics.OverlapSphere( transform.position, explosionRadius );
foreach (Collider coli in colliders)
if (coli.tag == "Enemy")
Damage( coli.gameObject);
How do I access the enemies' explosionPrefabs via their transforms ?
EDIT - after reading...
My problem was that the explosionPrefab (enemyMove class) was defined as a Transform. It is now a GameObject. And it works : )
However, instantiating the explosion throws an "invalidCastException" and exits the function. The explosion runs (!), but the rest of the function is skipped - the enemy survives!
But if I "attach" the same explosionPrefab to the local script (MissileMove), and use that in stead, it runs normally (no exception thrown) - what's the difference?
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);
}
Exception:
InvalidCastException: Specified cast is not valid.
(wrapper castclass) 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/BulletMove.cs:26)