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?

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

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

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#: