You can define classes in JavaScript, in a similar way as you do it in C#. The following example is a class that inherits from MonoBehaviour
.
JavaScript:
class MyClass extends MonoBehaviour { var myVar = 1; function Start() { Debug.Log("Hello World!"); } }
C#:
class MyClass : MonoBehaviour { public int myVar = 1; void Start() { Debug.Log("Hello World!"); } }
However in JavaScript, if you're inheriting from MonoBehaviour
, you don't need to write a class body at all. You can also write the following script in JavaScript, which will get a similar result as the preceding JavaScript:
var myVar = 1; function Start() { Debug.Log("Hello World!"); }
Unity will automatically implement an explicit class body for you.
You can also write classes that do not inherit from anything; however, you can't place these scripts on the game objects—you have to instantiate them with the new
keyword.
JavaScript:
class MyClass { var myVar = 1; function MyClass() { Debug.Log("Hello World!"); } }
C#:
class MyClass { public int myVar = 1; void MyClass() { Debug.Log("Hello World!"); } }
3.143.205.136