hi,
i am creating a randomizing script for 16 objects, i believe the randomizing functions work well, except that i want to place each object at a certain index in the list which corresponds with the object number,
the object are balls of a billiards rack up.
for example i want to place object 2 the two ball, at index position 2 of the list. this object may be the fourth object to be instantiated…
at the start i created the list with the length i wanted in the form of:
private List<GameObject> ball = new List<GameObject>(16);
but after the first object is instantiated, which occurs, i think then the error is being thrown…
ArgumentOutOfRangeException: Index must be within the bounds of the List.
Parameter name: index
any idea why this happens?
do i need a dictionary or is it due to another issue…
Debug your function. What index are you passing?
Would you post your code? Otherwise we’re just guessing what your issue is.
I uploaded my code
im passing an index from 0-15, i use the insert method.
5083226–500228–BallInstantiator.cs (8.03 KB)
What is the exact error message, what line number does it point to?
When you make a new list by saying new List<GameObject>(16)
, the “16” there isn’t the size of the new list, it’s the capacity of the new list. Those might sound like the same thing, but they’re not. Your new list has 0 entries, and you need to add stuff to it by calling the List.Add method.
To get a list with 16 “blank” spaces, you’d so something like this:
List<GameObject> myList = new List<GameObject>();
for (int i = 0; i < 16; ++i)
{
myList.Add(null);
}
“Capacity” doesn’t have to do with what’s actually in the list, it has to do with how the list manages memory “behind the scenes”. It’s a performance-optimization thing.
1 Like
Ok thanks allot Anitstone… if i create the null gameobjects to populate the list as u said above, and then i use for example insert, can i replace null index number 8 with a gameobject while keeping at index 8 and keeping everything else null?
ie replace the values… i tried this with this update and got
NullReferenceException: Object reference not set to an instance of an object
i dont understand why it would create this error, because through my script i can see that it is not a NullReferece.or maybe im missing something
here is the updated version of the script, it creates the null reference around line 93, on the first instantiation of center ball
i added the loop for the null objects in awake
5083988–500381–BallInstantiator.cs (8.11 KB)
i was able to solve this, i just put all the functions to be called in the start and it worked…
If you want to replace item #8 with a different value, you write
myList[8] = newValue;
Using Insert means that the previous #8 will get moved to #9, and the old #9 will get moved to #10, etc., and the total length of the list will be increased by 1.
2 Likes