Editing custom class' variable in IENumerable

I am current writing a terrain generator that creates terrain using unity’s inbuild terrain manager. I have, however run into problems with creating the individual chunks. All of the chunks work and generate, but there is a small line between them. I know this to be my problem, and i started to organise a system for saving each individual chunk that has been generated in an array, so that I can connect them together using Terrain.SetNeighbors. So I created a custom class to organise this, the class Chunk.

You can see this code I have here this is the code with the creation of the chunks, and the pass through to the individual chunk generators. This code doesn’t work.

function ChunkAtPos(Position : Vector2)
	{
	var ChunkObject = Instantiate(ChunkPrefab, Vector3(Position.x*256, 0, Position.y*256), Quaternion.identity);
	
	ChunkObject.transform.parent = transform;
	var CurrentChunk : Chunk;

    CurrentChunk.Position = Position;
	
	yield ChunkObject.GetComponentInChildren(TerrainGen).GenerateTerrain(Position);
	}

class Chunk
	{
	var Position : Vector2;
	var ChunkObject : GameObject;
	}

I get an error:

NullReferenceException: Object reference not set to an instance of an object
ChunkGen+$ChunkAtPos$113+$.MoveNext () (at Assets/Scripts/ChunkGen.js:59)
UnityEngine.MonoBehaviour:StartCoroutine_Auto(IEnumerator)
$:MoveNext() (at Assets/Scripts/ChunkGen.js:24)

So, if I remove line 59,

CurrentChunk.Position = Position;

The code runs fine and my terrain generates.
This also happens if i try edit any other part of my CurrentChunk variable. I have also tried having a constructor inside my class, among other things.

tl;dr:
Editing the class of a custom variable in my terrain generation script, which uses yields and IENumerables gives an error

Thanks for your help!

You don’t initialize your currentChunk, so it gets its default value. The default value for reference types is null.

Because Chunk is not a MonoBehaviour class, you have a constructor in it (default is empty constructor) and can create a new instance of Chunk by

var CurrentChunk : Chunk = new Chunk();

I think in UnityScript the new keyword is optional.

Another thing I noticed worth mentioning is that you don’t (seem to) store your CurrentChunk anywhere, as CurrentChunk is created as a local variale. Essentially you’re just creating needless garbage on the heap every time you call this function, which will cause Garbage Collection to run more frequently, decreasing performance.