How can I define a new variable as a component of a game object?

I need to create a new variable that will be individually defined for each object in the game. I need it to work similarly to transform variables that are attached automatically.

What would be the best way to do this?

You cannot directly extend a Unity class, but there are some work arounds. The easiest is to add a script that stores the variables you want to extend to your component then just access those.

If you want to give the appearance of methods on the class then you could use an extension method which I just learned about the other day.

//extension methods       
public static class ExtensionClass {

    public static int getSomeVar(this Transform t) {
        SomeClass sC = t.GetComponent<SomeClass>();
        return sC.someVar;
    }

    public static void setSomeVar (this Transform t, int value) {
        SomeClass sC = t.GetComponent<SomeClass>();
        sC.someVar = value;
    }
}


//Add this to your object
public class SomeClass : MonoBehaviour {
    public int someVar = 5;     
}


//And finally access it in another script.  
//Sorry, I could not get this working in js.
void Start() {
      Debug.Log(transform.getSomeVar();
      transform.setSomeVar(3);
      Debug.Log(transform.getSomeVar();
}
//outputs
//5
//3