Answer the question
In order to leave comments, you need to log in
How to find multiple objects in List without loop?
There is such a pool of objects . Let's
say 30 objects in itpublic List<Enemy> enemyPool = new List<Enemy>();
public class Enemy
{
public int Id { get; set; }
public int ParentRoomId { get; set; }
public GameObject GameObj { get; set; }
}
foreach (Enemy enemy in enemyPool)
{
if (amount > 0)
{
if (enemy.ParentRoomId == 0)
{
enemy.ParentRoomId = roomId;
enemy.GameObj.transform.position = spawnPosition.position;
enemy.GameObj.transform.rotation = spawnPosition.rotation;
enemy.GameObj.SetActive(true);
amount--;
}
}
}
Answer the question
In order to leave comments, you need to log in
I suspect you want something like this
enemyPool
.Where(e => e.ParentRoomId == 0)
.Take(amount)
.ToList()
.ForEach(e =>
{
e.ParentRoomId = roomId;
e.GameObj.transform.position = spawnPosition.position;
e.GameObj.transform.rotation = spawnPosition.rotation;
e.GameObj.SetActive(true);
});
count = 0;
for(vat i = 0; i < enemyPool.Count; i++)
{
if(enemyPool[i].ParentRoomId == 0)
{
count ++;
if(count >= amount)
break;
enemyPool[i].ParentRoomId = roomId;
enemyPool[i].GameObj.transform.position = spawnPosition.position;
enemyPool[i].GameObj.transform.rotation = spawnPosition.rotation;
enemyPool[i].GameObj.SetActive(true);
}
}
It is not very clear what you need and most importantly why.
The cycle will be one way or another. The word "find" already implies a search of options. The loop can be hidden (Where from LINQ). It may not go through the entire array, but only until the required amount is found (we just exit the loop when we have found everything we need.
Without a loop, you can only add the necessary objects somewhere in advance. But in my opinion this is not what you need ...
You can of course sort the array by parentRoomId and take the first 3 elements - but sorting is also a cycle.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question