Hi guys, I have weird problem.
I'm making a shooter game and pooling some missiles. This is the process:
- Get the pooled missile;
- this clone searches for enemies on screen;
- Sets a random target and pursue it;
- deactivate the target and missile itself (send them back to their own pools) ;
My problems are:
- when I shoot a missile again (reactivate the missile) it moves to the "dead" enemy transform instead of search for new enemy. How can I make it search for new enemy?
- if there are no enemies, I get an Exception "ArgumentOutOfRangeException: Argument is out of range.". It doesn't stop the game, but I'm afraid it can bring some trouble in the future.
Here is my Code:
void OnEnable()
{
SearchEnemyOnScreen();
}
//------------------------------------------------
void FixedUpdate()
{
if (isHazardOnScreen && hazardOnTarget != null)
{
LaunchMissile(hazardOnTarget.transform.position); // Homing Missile
}
else
{
MoveForward()
}
}
//------------------------------------------------
void OnTriggerEnter(Collider other)
{
if (other.tag == "Hazard")
{
other.gameObject.SetActive(false);
gameObject.SetActive(false);
isHazardOnScreen = false;
}
}
//------------------------------------------------
private void SearchEnemyOnScreen()
{
objOnScreen = FindObjectsOfType(typeof(GameObject)) as GameObject[];
List targetsOnScreen = new List();
foreach (GameObject enemy in objOnScreen)
{
if (enemy.tag == "Hazard")
{
targetsOnScreen.Add(enemy);
}
}
if (targetsOnScreen != null)
{
int randomTarget = UnityEngine.Random.Range(0, targetsOnScreen.Count - 1);
hazardOnTarget = targetsOnScreen[randomTarget];
isHazardOnScreen = true;
}
}
↧