[SLOVED]targeting system need some help

Hi guys!
Here is a code:

public void OnTriggerEnter(Collider targetColBubble){
       
        if(targetColBubble.gameObject.tag == "enemy"){

            newlist.Add (GameObject.FindGameObjectWithTag("enemy").transform);

        }
    }

    public void OnTriggerExit(Collider targetColBubble){
        if(targetColBubble.gameObject.tag == "enemy"){

            newlist.Remove(GameObject.FindGameObjectWithTag("enemy").transform);

        }
    }

My goal is when enemy OnTriggerEnter add to the list, onExit remove from list. in this code should add a “enemy” but sometimes add all enemies when enters collider sometimes one or two not added to the list.
Second question - any tips how to do add object to scene(button) for each entered enemy? eg one enemy enters then button appear on screen, when second enemy enters second button appears and so on.

Sorry for my english.
Thank you!

Hi, you should try replacing

GameObject.FindGameObjectWithTag("enemy").transform

by

targetColBubble.transform

So you list the actual enemy that entered your trigger and not another one at random.

Then you should probably consider checking if the enemy isn’t already in the list before adding it (newList.Contains(…)) thus avoiding to end up with the same enemy listed several times !

thank you!
so What I did so far

foreach(Transform go in newlist){

                GameObject enemyList = (GameObject)Instantiate (targetSlot);

                enemyList.gameObject.transform.SetParent (targetSlotParent.transform, false);
            }

now I’m closer to my goal and enemies appears in the list but when I instantiate slot I getting 2 slots for one enemy :). where is the problem?

Np, did you add a check before adding stuff to your list, to ensure there’s no duplicate entries ?

if (!newList.Contains(targetColBubble.transform))
{
     newList.Add(targetColBubble.transform);
}

Other considerations would be about your foreach block, firstly you shouldn’t use foreach with lists but whatever let’s not get into this just yet. I don’t know how you’ve set this up but you should make sure you don’t call it several times, or if you do, remove enemies from the list otherwise each time you’ll be creating new targetSlot for each enemy.

thank you for reply I just found a solution and all working now :slight_smile: Thank you anyway!