- Home /
my adding target script wont stop adding targets.
void Update () {
Collider[] cols = Physics.OverlapSphere(transform.position, 10);
foreach (Collider enemy in cols){
if (enemy && enemy.tag == "Enemy"){
targets.Add(enemy.transform);
}
}
(targes is a list that you use to target enemies.)
my problem is that when I stand in distance of the enemy it adds a lot of redundant targets.
does anyone know the problem?
Answer by syclamoth · Nov 09, 2011 at 04:32 AM
Yes, it's simply because you're adding all the targets every single frame!
Now, I only know how to solve this one because I've been looking at your other posts...
if(enemy && enemy.tag == "Enemy" && !targets.Contains(enemy.transform))
{
targets.Add(enemy.transform);
}
That's probably more like what you're looking for, since it checks for the enemy's presence in the list before adding it!
An issue here that you will have to deal with is that the targets will remain even when they are no longer in range (because you never remove them from the list).
Now, as I've said before, this is still not a fantastic way of going about it. If you just used my script the way I'd told you earlier, you wouldn't be getting this problem!
Answer by Bunny83 · Nov 09, 2011 at 04:37 AM
I guess it would make more sense to renew the target list instead of just checking for redundant items. If you add a target it would never be removed. Just clear the target list before you add the current targets:
void Update()
{
Collider[] cols = Physics.OverlapSphere(transform.position, 10);
targets.Clear();
foreach (Collider enemy in cols)
{
if (enemy && enemy.tag == "Enemy")
{
targets.Add(enemy.transform);
}
}
}
ps. for performance reason you should place your enemies on a seperate layer and do the OverlapSphere only for that layer. That would increase the speed and you wouldn't have to check for the enemy tag.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Health Script/Targeting system c# 2 Answers
Distribute terrain in zones 3 Answers
Checking collision between 2 objects on 3rd object 0 Answers
Problem with collision detection 0 Answers