- Home /
Detect clone using FindGameObjectsWithTag method.
Hi guys, long story short I'm looking to find a way to count targets as they appear on the screen. If I have one already in the scene I have no issues, it counts. But since I'm using a spawn script it won't count the clones, any ideas? PS: I'm still new to scripting, this was created using the BurgZerg tutorials, Cheers guys!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerTargets : MonoBehaviour {
public List<Transform> targets;
private Transform selectedTarget;
private GameObject target;
void Start () {
targets = new List<Transform> ();
AddAllEnemies ();
}
// Update is called once per frame
void Update ()
{
}
void OnGUI() {
GUI.Label (new Rect (10, 70, 1000, 20), "Enemies: " + targets.ToString ());
}
public void AddAllEnemies ()
{
targets.Clear ();
GameObject[] go = GameObject.FindGameObjectsWithTag ("enemy");
foreach (GameObject enemy in go)
AddTarget (enemy.transform);
}
public void AddTarget (Transform enemy)
{
targets.Add (enemy);
}
}
Answer by cdrandin · Feb 10, 2013 at 08:54 PM
I don't know I tend to be picky on some thing, but why not dedicate a script solely for focusing on spawning? This is a lot more intuitive and encapsulates it from all other objects. If you insist on your method, then when you create the clone, create a tag "Clone". Then use GameObject.FindObjectsWithTag("Clone") which should find all your clone objects and put them into a list.
So, your clone should obviously be a prefab, just give it a "Clone" tag and it should all work nicely.
I went with your method of adding it to the 'spawn' itself and it works perfectly. Thanks- I don;t know why I didn't go that way in the first place.
It is just experience and now you know and you can expand that simple encapsulation idea to many other routines as well.
Your answer
![](https://koobas.hobune.stream/wayback/20220613092456im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Finding closest object to player 3 Answers