- Home /
vector2D Array initialization not working.
I need to store a bunch of 2d mouse/touch position. So I created an array container which will store these positions. How many positions will be stored, is not fixed;it depends on another public variable which will be manipulated by user at editor. The code looks like this:
public int points=10;
private Vector2[] positionBox;
I get warning, that I should initialize my array variable. If I initialize array with one member, array got its size fixed(which I do not want). If I do not initialize it, warning pops up. And in play-mode I get a nice "nullException".
What is the proper way of declaring varying sized array? or I can not declare an array of varying size?
Answer by jonnyhopper · Oct 28, 2013 at 09:03 PM
You want to use a List of Vector2 instead. To do this you add
using System.Collections.Generic;
at the top of your file and then declare
List< Vector2 > positionBox = new List< Vector2 >()
then you can call positionBox.Add() and positionBox.Remove() etc
Answer by robertbu · Oct 28, 2013 at 09:08 PM
The declaration for 'positionBox' is not an array. It is a variable that can be pointed to some memory that can be used as an array. If you know at edit time the size of the array, you can put this in Awake() or Start():
positionBox = new Vector2[points];
This will allocate the memory for the array and set 'positionBox' as a reference to the array. Another possibility is to make 'positionBox' public. This would allow someone to set both the size of the array and the array entries to specific values.
If you are going to be doing actions at runtime that change the size of the array...adding additional elements, removing elements and the like...then you want to use a different kind of collection. The typical one used is generic Lists. You can read about the many different collection types available here:
http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F
This is the best way to go if the number of points is known in advance and does not change after the game starts.
Another way to go is make the array public ins$$anonymous$$d of private, which will allow you to set its size directly in the inspector, without adding a points
variable at all.
public Vector2[] positionBox = new Vector2[10];
please accept his answer if it solves your problem. Thanks
Answer by VesuvianPrime · Oct 28, 2013 at 09:05 PM
If the array is going to change size, your best bet is to use Lists.
using System.Collections.Generic;
private List<Vector2> positionBox = new List<Vector2>();
positionBox.Add(new Vector2(0, 0));
Dot Net Pearls is an excellent resource for learning C#:
Your answer
![](https://koobas.hobune.stream/wayback/20220613120821im_/https://answers.unity.com/themes/thub/images/avi.jpg)