Reputation: 21
I am trying to get a list of Transforms for a spawn system. I have tried to use GameObject.FindGameObjectsWithTag with an array instead of a list and it seems like the array needs to be GameObjects and not Transforms, since that's what it's looking for. I've also tried another piece of code, but it only returns one random Transform into a list, here it is:
public List<Transform> t;
void Start()
{
t.Add(GameObject.FindWithTag("Spawn").transform);
}
As you can see in my code, it will only add one Transform to my list. I would like to add multiple Transforms instead of just one.
Upvotes: 2
Views: 4601
Reputation: 90659
You can use Linq Select
like
using System.Linq;
...
public List<Transform> t;
void Start()
{
t = GameObject.FindGameObjectsWithTag("Spawn").Select(go => go.transform).ToList();
}
This basically somewhat equals doing
var array = GameObject.FindObjectsWithTag("Spawn");
t = new List<Transform>(array.Length);
foreach(var go in array)
{
t.Add(go.transform);
}
Upvotes: 5
Reputation: 507
Array of gameObject:
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
To get the transform:
gos[0].transform
To make a list of transform:
public List<Transform> t;
foreach (GameObject go in gos)
{
t.Add(go.transform);
}
Upvotes: 2
Reputation: 25
public List<Transform> t;
public List<GameObject> go; //GameObjects where youl look for
void Start()
{
for (int i = 0; i < go.Count; i++)
{
if (go[i].tag == "Spawn")
{t.Add(go[i].transform);}
}
}
Upvotes: -1
Reputation: 19
It might be simpler to add these "spawn" objects to the list at the time of their creation instead of trying to find them afterwards. Is that an option?
For example:
GameObject spawn = Instantiate(spawnObj);
t.Add(spawn.transform);
Upvotes: 0