I'm trying to convert this code from UnityScript (Unity's version of JavaScript) to C#:

var polys = new Array(); // array to collect vertex locations
polys.Push((scanpoint + padding) + Vector2(0.5, 0.5) * Pixel_vs_Unit_Scale);
var poly:Vector2[] = polys.ToBuiltin(Vector2);

I converted the first two lines like so, with no errors:

var polys = new List<Vector2>();
polys.Add((scanpoint + padding) + new Vector2(0.5f, 0.5f) * Pixel_vs_Unit_Scale);

But when I try to adapt the last line like this:

Vector2[] poly = polys.ToBuiltin(Vector2);

I get two errors:

ToBuiltin does not exist.

And also an error on the Vector2 inside the ():

Vector2 is a type which is not valid in the given context.

How can I convert this code to C# correctly?


In Unity's JavaScript implementation (sometimes called UnityScript), there are two types of array: JavaScript-style arrays, which have no particular type or length, and "Builtin" (native .NET arrays), which have a specific type and length.

In C#, we usually prefer to work with statically typed variables, so the usual equivalents we'd use would be:

  • Generic Lists (List<SomeType>) if we want to be able to grow & shrink the collection dynamically

  • Typed Arrays (SomeType[]) if we want to work with a fixed-size collection.

A list can produce a fixed-size typed array copy of its current contents with the .ToArray method. So, we can translate your code like so:

var polys = new List<Vector2>();
var poly = polys.ToArray();

But this is a little silly - poly in this case will only ever contain that one item - we don't need the dynamically-sized intermediate to build it up. So unless we're reusing polys later in the code, we might as well define the poly array directly and then assign that one item to it:

var poly = new Vector2[1];
poly[0] = (scanpoint+padding)+Vector2(0.5,0.5)*Pixel_vs_Unit_Scale;

or even shorter:

var poly = new Vector2[]{(scanpoint+padding)+Vector2(0.5,0.5)*Pixel_vs_Unit_Scale};

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .