Why is my constructor called 3 times?

Hi, this is a Javascript / Unityscipt question:

This is TestScript.js

static public var concount : int = 0;



class MyClass 

{

	private var temp : int;

		

	function MyClass (ID : int)

	{

		TestScript.concount++;		

		Debug.Log("Constructor called no times: " + TestScript.concount );

		temp = ID;			

	}

}

And this is ExternalScript.js

private var classinst : MyClass = new MyClass(9);

function Start () 
{
		
}

Both scripts are attached to a GameObject.

Q1. According to my console output and my counter, when I execute the program, the constructor is called twice. It is doing my head in why this should be the case. I would have thought a variable declaration/initialization should only be called once, and therefore a constructor only once?

Q2. As if that wasn’t confusing enough, as I stop the execution in Unity, the console log indicates the constructor is called a 3rd time. Why?

By changing the declaration of classinst to inside the MonoBehaviour Start() function, the constructor is only called once and both problems go away.

Q3. Out of interest, I would really like to know how to go about debugging a problem like this in MonoDevelop. I have managed to crash Unity 3 or 4 times whilst trying to step through code in MonoDevelop with this simple example, whilst attached to the Unity Editor process. Should I be using ScriptableObject for my classes? Will this make my life easier?

Cheers for help

Unless you have multiple instances of this class in your scene, I think this has something to do with the funny way that Unity handles things in editor mode, I guess your monobehaviour that creates your test class is suffering from this:

http://unity3d.com/support/documentation/ScriptReference/index.Writing_Scripts_in_Csharp.html

You should write the code like this:

private var classinst : MyClass;

function Start () 
{
	classinst = new MyClass(9);
}

–Eric