- Home /
C# Adding Items to list in Foreach not working
I am trying to add items to a list with a foreach method as shown below
foreach (string posi in roomObj.GetComponent<Room>().positions)
{
if (posi != "right") //right is occupied
{
tempList.Add(new Position(roomObj.GetComponent<Room>(), posi));
Debug.Log(tempList.Count);
}
}
availablePositions.AddRange(tempList);
availablePositions.Remove(pos);
The problem is that no matter what I try to do to fix this, I can't get the tempList.Add to work and it appears as though Unity doesn't even execute this code as I can't get the Debug.Log doesn't show. What am I doing wrong?
I have also tried removing the if statement thinking that may be the issue. It appears as though Unity just doesn't execute this code at all
I've tried not using for each and ins$$anonymous$$d using a series of If statements, this doesn't work either. It appears I am doing something wrong with the Add method as even this section of code doesn't work
if(roomObj.GetComponent<Room>().positions.Contains("right"))
{
tempPos = new Position();
tempPos.pos = "down";
tempPos.rom = roomObj.GetComponent<Room>();
availablePositions.Add(tempPos);
}
Answer by jgodfrey · Dec 22, 2014 at 04:23 AM
I'd guess that your GetComponent call is not returning anything, and you therefore don't have anything to foreach through...
I think that would lead to a Null reference exception but I tested this and it is returning a value. Like I said the Debug.Log isn't showing so it appears that for some reason this code isn't executed at all.
Your answer
![](https://koobas.hobune.stream/wayback/20220613174632im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C# Problem Creating List of Texture2Ds 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
foreach a array inside a generic list 1 Answer
How to get variables from a list of a list of gameobjects? 1 Answer