Why is my list over writing itself?

Hello all. So i’ve got an issue where the last item added to the list seems to overwrite all spots within the list…
Cant get my head around it…
So this is what i got.

 public class ListOfDistances
    {           
        public  float _distance;
        public int _distanceIndx;
    }

    public List<ListOfDistances> listOfDistances = new List<ListOfDistances>();

    public ListOfDistances listOfStuff = new ListOfDistances();
 void CheckDistance1()
    {
        int queSpot = 0;
        int listLenght = listOfPosition.Count;
        myLocation = transform.position;

        for (int i = 0; i < listLenght; i++) // create list of distances from current pos
        {
            listOfDistances.Add(listOfStuff);

            float tempDistance = Vector3.Distance(myLocation, listOfPosition[i]);

            listOfDistances[i]._distance = tempDistance;
            listOfDistances[i]._distanceIndx = i;
         
            Debug.Log("listOfDistances._distance;  " + listOfDistances[i]._distance + ",  listOfDistances._distanceIndx;  " + listOfDistances[i]._distanceIndx);   
        }

        Debug.Log("listOfDistances[0]._distance;  " + listOfDistances[0]._distance + ",  listOfDistances[0]._distanceIndx;  " + listOfDistances[0]._distanceIndx);
        Debug.Log("listOfDistances[1]._distance;  " + listOfDistances[1]._distance + ",  listOfDistances[1]._distanceIndx;  " + listOfDistances[1]._distanceIndx);
        Debug.Log("listOfDistances[2]._distance;  " + listOfDistances[2]._distance + ",  listOfDistances[2]._distanceIndx;  " + listOfDistances[2]._distanceIndx);
        Debug.Log("listOfDistances[3]._distance;  " + listOfDistances[3]._distance + ",  listOfDistances[3]._distanceIndx;  " + listOfDistances[i]._distanceIndx);

        queSpot = listOfDistances.Capacity;
        Debug.Log("listOfDistances.Capacity  " + listOfDistances.Capacity);
}

Seems like i do add information to the list, and the list is expanding with the information, but doesnt hold anything but the last input in all positions…

7869625--999994--1.jpg


7869625--1000000--3.jpg

Why are you considering .Capacity?? That seems very suspect.

Do you intend to use .Count?

listOfDistances.Add(listOfStuff);
You’re adding the reference (listOfStuff) of the same one ListOfDistances object over and over.
listOfDistances.Add(new ListOfDistances());

BTW, your naming convention isn’t helping you either. Do not call something List if it isn’t a list of things at all.

ListOfDistances should be something like DistanceEntry.
You don’t need the listOfStuff.

2 Likes

aaa yes, missed that, ment .count. Just clicked autofill without looking.

1 Like

Good spot, thank you for that!

haha yes the naming is shit. this is a segment of a much larger piece that ive written many times over to test and had ran out of names to call thing.
Thank again!

1 Like