- Home /
How can I target/attack all gameobjects in a certain area?
So it's a little more complex than the title in the grand scheme of it all. I want to have a spell that attacks up to 6 enemies in an area and they can be hit a maximum of 1 times.
So far I had
bool enemyInBounds = false;
bool enemyTargeted = false;
void SpellOne()
{
if (enemyInBounds == true)
{
for (int i = 0; i < 6; i++)
{
//need to make sure they're unique
// apply damage and shoot projectile
}
}
I wasn't sure how to check if they were inside the sphere collider I had on the player besides
void OnTriggerStay(Collider Other) //might work. not sure if enemyInBounds is assigned to the other object or not
{
if (Other.gameObject.tag == "Enemy")
enemyInBounds = true;
}
void OnTriggerExit(Collider Other)
{
if (Other.gameObject.tag == "Enemy")
enemyInBounds = false;
}
I'm not sure if this is even the correct way to go about it. Any ideas on the logic?
Try this method:
https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
Alternativly you can iterate over all enemies and calculate the distance between the enemy and the spell position.
Triggers are updated with physics engine so refresh rate is the same.
Answer by Charmind · Jul 19, 2016 at 03:22 PM
If i didn't got it wrong You can create list of enemy gameobjects and EnemyScript so:
List<GameObject> Enemys = new List<GameObject>();
List<EnemyScript> Temporary = new List<enemyScript>();
Then make script like this:
Temporary = FindObjectsOfType<EnemyScript>();
for(int i = 0; i < Temporary.Count; i++) // Finding all Enemy objects and adding them to list
{
if(Vector3.Distance(Temporary[i].gameObject.transform.position, transform.position) < spellRange) // check if Enemy is at range
{
Enemys.Add(Temporart[i].gameObject);
}
}
int selected;
int Enemycount = Enemys.Count;
for(int i = 0; i<Mathf.Min(6,Enemycount); i++) // selecting random 6 unique enemys also checking if enemy amout is smaller than 6
{
selected = Random.Range(0,Enemys.Count);
Enemys[selected].getComponent<EnemyScript>().spellX(); // send enemy info that he is damaged by your spell
Enemys.RemoveAt(selected); // remove this enemy so it's unique
}
Remember to add using.Systems.Collections.Generic. Hope it helps :)