- Home /
Destroy when out of range issue
Okay so this should be easy enough right? There's a enemy and if when searching for a gameObject with a player tag we find that it's far enough away that this enemy can despawn, it should destroy itself, so here's my code (The function is called on short intervals):
function WithinDistance()
{
Heroes = GameObject.FindGameObjectsWithTag("Player");
HeroInRange = false;
for (var Hero : GameObject in Heroes)
{
if(HeroInRange == false)
{
if(Mathf.Abs(Hero.transform.position.x - transform.position.x) < 8 && Mathf.Abs(Hero.transform.position.y - transform.position.y) < 5 && Mathf.Abs(Hero.transform.position.z - transform.position.z) < 5)
{
if(Hero.transform.position.x < transform.position.x && Moving == false)
{
Reverse();
}
//networkView.RPC("Unlock",RPCMode.All);
HeroInRange = true;
//print("Hero in Range is true" + Hero.name);
//Moving = true;
}
if(MovementType == "Constant")
{
if(Mathf.Abs(Hero.transform.position.x - transform.position.x) > 8 && Mathf.Abs(Hero.transform.position.y - transform.position.y) > 5 && Mathf.Abs(Hero.transform.position.z - transform.position.z) > 5)
{
//networkView.RPC("Unlock",RPCMode.All);
if(HeroInRange == false)
{
//print("Inside the death" + Hero.name);
Network.Destroy(gameObject);
}
}
}
if(MovementType == "Fly")
{
if(Mathf.Abs(Hero.transform.position.x - transform.position.x) > 8 && Mathf.Abs(Hero.transform.position.y - transform.position.y) > 5 && Mathf.Abs(Hero.transform.position.z - transform.position.z) > 5)
{
//networkView.RPC("Unlock",RPCMode.All);
if(HeroInRange == false)
{
//print(gameObject.name + "Die After a while away");
Network.Destroy(gameObject);
}
}
}
}
//STILL NOT QUITE WORKING? IN MULTI IT ONLY RECOGNIZES SERVER.
}
}
However because this is a multiplayer game there are multiple objects with the player tag, and that's causing some problems. If one player is far away from an enemy but another is right next to it, that enemy will still despawn. I would have thought how I coded it would make it so it would stop looping through once it found a hero close enough, but the enemies are still being destroy, and I have no idea why. And yes, this is the code where the enemies are being destroyed. Also this code is only called by the server, not by the clients (I'm 99% sure).
I would love some help on this, it's driving me crazy.