Tileable perlin noise terrain

I have been trying to make an infinite terrain over the last couple of weeks but I can’t make it work, here is my current code:

 function GenerateTile(nw : int, nh : int) {
	if (GameObject.Find("Chunk "+nw+","+nh)) { 
    	return;
	}
 		
	var freq : float = Frequency;
	var td = new TerrainData();
	td.heightmapResolution = 513;
	td.size = new Vector3(500,200,500);

	var ChunkPosX : float = td.size.x * nw;
	var ChunkPosY : float = td.size.z * nh;

	var t = Terrain.CreateTerrainGameObject(td);
	var hw : float = Terrain.activeTerrain.terrainData.heightmapWidth;
	var hh : float = Terrain.activeTerrain.terrainData.heightmapHeight;
	var heights = new float[hw, hh];
	for (var x = 0; x < hw; x++) {
		for (var y = 0; y < hh; y++) {
			//           World Pos Divided by heightmap height
    		var xCoord = ((ChunkPosX + x) / (Mathf.PI * scale));
			var yCoord = ((ChunkPosY + y) / (Mathf.PI * scale));
			if (x == 0 && y == 0) {
				Debug.Log(xCoord);
				Debug.Log(yCoord);
			}
			heights[x,y] = Mathf.PerlinNoise(xCoord, yCoord);
		}
	}
	Terrain.activeTerrain.terrainData.SetHeights(0,0,heights);
	t.transform.position = new Vector3(ChunkPosX, 0,ChunkPosY);
	t.name = "Chunk "+nw+","+nh;
}

Does this video help you…