- Home /
Instantiated enemies not adding to kill count
Hello, I've seen a few posts about this, but nothing seems to be working
I have an "enemy" preFab and a "bullet" preFab, the bullets fire out when you click fire1, and the enemies die (Destroy) when the bullets collide with them. The enemies are being created with IEnumerator + StartCoroutine
I'm trying to retrieve when the enemy is destroyed - 6 enemies spawn at once
void OnCollisionEnter (Collision other)
{
rigidbody.useGravity = true;
rigidbody.AddForce(0,-100,0);
if(other.gameObject.tag == "enemy")
{
newKill = true;
Debug.Log("HIT");
killCount = 1;
}
}
That returns 6 "HIT"'s when the 6 enemies die, however the bool "newKill" doesn't change from false to true in the inspector - I initialize it like so:
public bool newKill = false;
which I think is the problem, I can't get this data to cross classes, which would allow me increment a killCounter in another class - "GameData"
if(newKill)
{
killCounter += 1;
newKill = false;
}
I think the problem is because the objects are instantiated and destroy to quickly??
Any thoughts?
I adjusted the size of the sphere collider surrounding my enemies, and only a few add to the kill count when they die - so I know data is being sent to my killCounter, but why not all of them?
here is the code i'm using to spawn the enemies
void Play() /**/ { StartCoroutine (SpawnWaves()); }
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds (wait);
while(true)
{
for(int i = 0; i <= enemyCount; i++)
{
Vector3 spawnPosition = new Vector3 (Random.Range (48, 55), spawnValues.y, Random.Range (-spawnValues.z, spawnValues.z));
Quaternion spawnRotation = Quaternion.identity;
Instantiate (enemy, spawnPosition, spawnRotation);
//yield return new WaitForSeconds (delay * Time.time);
}
yield return new WaitForSeconds (waveDelay);
wave++;
}
}
Answer by xt-xylophone · May 07, 2014 at 11:54 PM
In your killCounter class just create a public function that can be called by your enemies in their OnCollisionEnter function.
Something like:
public void incrementKillCounter() {
killCounter += 1;
}
And in your enemy class simply call that function. You will need to save an instance of GameData for your enemy to call it though or make everything static.
Your answer
Follow this Question
Related Questions
Y value wont work? 1 Answer
Enemy Health Damage 2 Answers
Cloning Problem Script 0 Answers
Prefab connection problem 1 Answer
Instantiate prefabs working in editor but not in builds 0 Answers