Build texture atlas and assign texture to material

I want to build an atlas of my textures at the start of my iPhone game and than assign textures from this atlas to various GameObjects with the same material to reduce draw calls.

My idea was to attach a AssignTexture script to the GameObjects and set the ImageNumber in the Inspector which takes the coords from the atlasArray.

I have this AtlasBuilder script in my scene:

#pragma strict

static var atlasArray : Array;
var atlas : Texture2D;
var textures : Texture2D[];
var padding : int = 0;
var maximumAtlasSize : int = 1024;

function Start(){
	atlas = new Texture2D(1024,1024);
	atlasArray = atlas.PackTextures(textures, padding, maximumAtlasSize);
	// Get coords
	print(atlasArray[0]);
	// How many images
	print(atlasArray.length);
}

And this AssignTexture script on a GameObject:

#pragma strict

var ImageNumber : int;
var NewTexture : Texture2D;

function Start () {
	NewTexture.GetPixels(AtlasBuilder.atlasArray[ImageNumber]);
	renderer.material.mainTexture = NewTexture;
}

It gives this error: NullReferenceException: Object reference not set to an instance of an object
AssignTexture.Start () (at Assets/AssignTexture.js:7)

It says the error occurs in line 7 but I assume here in your post it could be line 8. Have you assigned a texture to

??

No i have no texture assigned to the NewTexture var. I want to load this NewTexture from the atlasArray.

but you have textures in your atlasArray? Or do have assigned a numbver to your ImageNumber?