Home > Unity3d > Unity3d javascript native array base redim

Unity3d javascript native array base redim

October 11, 2009

In my recent pathfinding glory and javascript discoveries I unearthed the native array which is very different from the Array type.

First off the Array type will never show objects in the inspector.

If for example you have a class with some simple variables like the following :

class Custom extends Object
{
    public var p1:Vector3;
    public var p2:Vector3;
}

When you declare an Array and you Push values of class Custom inside it, you will not be able to edit it like you do with animation arrays and materials. Both of the last two are what is called builtin arrays. The Unity3d documentation specify that builtin arrays can easily precess 2 millions vector3 in 1 second. While this speed is nice they could have given it a little bit more power, like resizing …

Resizing a javascript native array

Like always, this is an exploratory example and you may find other more optimized ways to do it, but this is pretty much the most basic form of resizing.

class Graph extends Object
{
	public static var nodes:Node[];
	public static var builtinAllocBlock:int = 30;
	public static var nodeCount:int = 0;

	public function Graph()
	{}

	function CheckToReallocBuiltinNode()
	{
		//Check if we potentially hit the end of the array
		var sizeCheck:int = ((nodeCount + 1) % builtinAllocBlock);
		Debug.Log("Size check - count: " + nodeCount + " sizecalc: " + sizeCheck);
		if( sizeCheck  == 0 )
		{
			var newSize:int = (((nodeCount + 1) / builtinAllocBlock) + 1) * builtinAllocBlock;
			Debug.Log("Reallocation of node builtin array from size: " + nodeCount + " to: " + newSize);
			//We need a more space.
			var temp: Node[] = new Node[newSize];

			//Crude copy
			for(var i:int = 0; i < nodeCount; i++)
			{
				temp[i] = nodes[i];
			}

			//Overwrite old
			nodes = temp;
		}
	}

	function Clear()
	{
		nodes = new Node[builtinAllocBlock];
		nodeCount = 0;
	}
}

Now with the above code you would have to call Clear() to initialize for the first time the array. This is because Unity tends to call the constructor of MonoBehaviour when you switch from the app to another app (code editing for example). This would lead to the graph being always re-initialized. In any case study the above CheckToReallocBuiltinNode. Its a simple case of if you attain the next maximum reallocate and recopy.

Update me when site is updated
Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Slashdot
  • PDF
  • Twitter
Categories: Unity3d
  1. No comments yet.
Comments are closed.