- Home /
Initializing an array of Vector3 in c sharp #
Currently I'm initializing an array of Vector3 in C# like so :
Vector3[] positionArray = new Vector3[4];
positionArray[0] = new Vector3(0.0f,0.0f,0.0f);
positionArray[1] = new Vector3(0.1f,0.1f,0.1f);
positionArray[2] = new Vector3(0.2f,0.3f,0.4f);
positionArray[3] = new Vector3(0.5f,0.5f,0.5f);
I've tried initializing the array using shorter methods, but all have failed. Heres an example of one that I tried :
Vector3[] positionArray = new Vector3((0f,0f,0f),(1f,1f,1f));
And here is the error that Unity reports back :
A field or property `UnityEngine.Vector3' cannot be initialized with a collection object initializer because type `UnityEngine.Vector3' does not implement `System.Collections.IEnumerable' interface
Answer by whydoidoit · Sep 23, 2012 at 07:39 PM
The other way to initialize the array is like this:
Vector3[] positionArray = new [] { new Vector3(0f,0f,0f), new Vector3(1f,1f,1f) };
Answer by Dave-Carlile · Sep 23, 2012 at 09:14 PM
You can also use object initializer syntax:
Vector3[] positions = { new Vector3 { x = 0, y = 0, z = 0 },
new Vector3 { x = 1, y = 1, z = 1} };
In this case using the constructor (as Mike did) is more concise.
Thank you! You helped me with my a little bit more complex question with custom class array Here it is for others who are seeking same or similar answer:
public class Sapling
{
public saplingSortField[] saplingSort = { new saplingSortField() {name = "A"},
new saplingSortField() {name = "B"},
new saplingSortField() {name = "C"},
new saplingSortField() {name = "D"},
new saplingSortField() {name = "E"},
new saplingSortField() {name = "F"}};
}
public class saplingSortField
{
public string name;
public int value = 1;
}
my problem was - I wanted to preset these 6 fields every time "Sapling" is called with no other possible field options. When I call "new Sapling()" I'll get these fields without 'manually' adding them after making new Sapling
Exact problem I had when I was making ingame resources (gold, wood, stone,...) I wanted them to be in same Array but they need name, value, icon,.... also there must not be option for calling "resources" and getting different names, they all must be exactly same in every unit/building/player script which works with resources. I did it in some other way that solved the problem but now I need to remake it in this - correct way.
Answer by DuckOfDoom · May 13, 2014 at 11:31 AM
Or, if you need fixed array length for copying (like you would use in mesh.vertices) you could do this:
var newVerts = new Vector3[verts.Length - 10];