0

I'm beginner in c#, and I'm trying to get a list of values but I get a null object reference.

I have a dictionary

var stripes = new Dictionary<int, List<Transform>>(); 

and I'm trying to get the list of transforms

 foreach (var stripe in stripes) { List<Transform> transforms = stripe.Value; foreach (var treeTransform in transforms) { float distance = DistanceToCameraPlane(treeTransform.position); TreeObject treeObject = new TreeObject(); treeObject.distance = distance; treeObject.tree = treeTransform; sortedTrees.Add(treeObject); } } 

However I get a null object references in treeTransform.position

2
  • Your problem is not iterating your dictionary, your problem is that the value added to the dictionary is null and when you try to used it throw a null reference exception. Commented Mar 4, 2015 at 13:11
  • you should check why you have null elements inside your transforms collection. Since you get the NullReferenceException on the treeTransform.position line, which means treeTransform is null somehow Commented Mar 4, 2015 at 13:12

2 Answers 2

1

Try to change this line:

foreach (var stripe in stripes) 

to this instead:

foreach (List<Transform> transforms in stripes.Values) 

and remove this:

List<Transform> transforms = stripe.Value; 
Sign up to request clarification or add additional context in comments.

1 Comment

Consider explaining why that helps.
0
foreach (var stripe in stripes) { List<Transform> transforms = stripe.Value; if (transforms != null && transforms.Count > 0) { foreach (var treeTransform in transforms) { if (treeTransform != null) { float distance = DistanceToCameraPlane(treeTransform.position); TreeObject treeObject = new TreeObject(); treeObject.distance = distance; treeObject.tree = treeTransform; sortedTrees.Add(treeObject); } } } } 

1 Comment

Adding the null checks was the first thing I thought too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.