Add animtion clip through editor

I am trying to create and then add animation clips to selected game objects through the editor using js. I have the following code:

@MenuItem ("Custom/AddClip")

static function AddAnimationClip(){

for (var obj : GameObject in Selection.gameObjects){
	anim = obj.GetComponent.<Animation>();

	// Animates the x coordinate of a transform position.
	// Create the curve.
	var curve : AnimationCurve = AnimationCurve.Linear(0, 1, 2, 3);

	// Create the clip with the curve.
	var clip : AnimationClip = new AnimationClip();
	clip.legacy = true;
	clip.SetCurve("", Transform, "localPosition.x", curve);
	
	// Add and play the clip
	anim.AddClip(clip, "test");
	anim.Play("test");
     }
}

This adds the newly create animation clip to “Animations” area of the animation component as “Element 0” but does not add it to the “Animation” area. This means the animation clips does not play when running in game mode but will play if you press play in the animation window with the game object selected. I’m using Unity 5 but the same happens in 4.6.

I have attached an image to help explain what I am trying to do.

42258-addinganimationclips.jpg

Any help would be appreciated.

I believe that animation.clip = sets the desired animation as the selected animation.
So you need to add this:

anim.clip = clip;

I’m certain that this works while playing. Not sure if this works in editor updating the window.