Looking for examples of Javascript classes

Hi all!

I’m having a hard time finding documentation of Unity classes (particularly in Javascript, which is the language I am working in).

In other programming languages I have worked in I have always instantiated a class and it would then be that classes responsibility to deal with assets. Unity gives me the impression that it should be backwards: you instantiate the asset and then attach a class to it. Is this correct? it sounds pretty inelegant.

I’m finding myself designing classes like this:

public class Block{

var velocity = new Vector3(0,0,0);
var position = new Vector3(0,0,0);
// etc
var model: GameObject;

// Constructor
function Block(x: int, y: int, z: int){
	// Build the model instance
}

// Deconstructor
function Destroy(){
	// Delete the model instance
}

function Tick(){
	// Move, set the position of the model, etc
}

}

As the game gets more complicated, I’m finding this approach is giving me a lot of problems. I’m having a lot of issues with scope, and what I assume is a problem with referencing/dereferencing.

I suppose what I’m asking is this: is there a good Javascript example out there that makes significant use of classes?

Thanks!

It’s not inelegant at all. Use prefabs with scripts on them, which you can reference using GetComponent. Some built-in components have shortcuts; for example Transform can be accessed by transform rather than GetComponent(Transform). e.g., someGameObject.transform.position.x = 5. Look in the GameObject docs for the variables which function as GetComponent shortcuts.

The class you used as an example has a lot of redundant info that’s already handled by Unity, such as the position and velocity, which are in the Transform and Rigidbody components. You don’t need a constructor, destructor, or Tick function; Unity already has Instantiate, Destroy, and Update. You can use OnDestroy if you need to do additional cleanup when that instance is destroyed.

A JS script is a class by default (which extends MonoBehaviour); you don’t need to specify a class manually. The class is the name of the script.