Overall Question: How do I get enemy's childgameobject(1) to be setactive(false) when the player finds a new closest enemy?
Details:
I've been attempting to do this for 2 days now and can't find any answers on here or youtube, google search or anything.
So basically the script below is almost done... Currently when my player's attack range is within range of enemy the enemy's childgameobject(2) will be setactive(true) and when out of that range it'll be set false.
I also have a childgameobject(1) that gets set true if that enemy is closest to player.
This is also working...
However the real question here is how do I get that childgameobject(1) to be set active false when the player finds a new closest enemy? Currently it'll be set active when the player finds a new closest enemy that enemy will now have childgameobject(1) to be set active true and obviously that's not the intended effect I'd like. I do deactivate childgameobject(1) when it's out of attack range but would like it to deactivate whenever a new closest enemy has been found.
Please let me know if there is a better way to implement a targetting system. the objects are just circles that when are active are above the enemies.
============================================================================
Current Script Below
============================================================================
public class Player : MonoBehaviour
{
bool EnemyMark = false;
protected override void Update()
{
//Find closest enemy
float distanceToClosestEnemy = Mathf.Infinity;
FindEnemy closestEnemy = null;
FindEnemy[] allEnemies = GameObject.FindObjectsOfType();
foreach (FindEnemy currentEnemy in allEnemies)
{
float distanceToEnemy = (currentEnemy.transform.position - this.transform.position).sqrMagnitude;
if (distanceToEnemy < distanceToClosestEnemy)
{
distanceToClosestEnemy = distanceToEnemy;
closestEnemy = currentEnemy;
EnemyMark = true;
}
//Activates childgameobject 2 with Enemy mark based on attackRange
if (Vector2.Distance(transform.position, closestEnemy.transform.position) <= attackRange)
{
closestEnemy.transform.GetChild(2).gameObject.SetActive(true);
}
//De-Activates childgameobjects 1 & 2 with Enemy mark based on attackRange
if (Vector2.Distance(transform.position, currentEnemy.transform.position) >= attackRange)
{
currentEnemy.transform.GetChild(1).gameObject.SetActive(false);
currentEnemy.transform.GetChild(2).gameObject.SetActive(false);
}
}
//Activates childgameobject 1 with Enemy mark based closest enemy
if (EnemyMark == true)
{
closestEnemy.transform.GetChild(1).gameObject.SetActive(true);
}
//De-Activates childgameobject 1 with Enemy mark based closest enemy
else
{
closestEnemy.transform.GetChild(1).gameObject.SetActive(false);
}
if (closestEnemy == null) { return; }
}
}
↧