Lets play with some code…
This code defines a class… This class wont do a single thing but take up space until we create a new object from it.
public class NewBehaviourScript : MonoBehaviour {
// NOTE: we are using a monobehavior here because we want the advantage of things starting and updating during the game.
public junk myClass;
// Use this for initialization
void Start () {
junk myClass = new junk();// create a usable object from the class
myClass.Start();// forces the object to "Start"
}
// Update is called once per frame
void Update () {
myClass.Update();// forces the object to "Update"
}
}
using UnityEngine;
using System.Collections;
public class junk{
void junk(){
Debug.Log("New Junk Constructed.")
}
public void Start(){
Debug.Log("This function is not called because we do not extend the MonoBehaviour base class.")
}
public void Update(){
}
}
Ok, what we do here is to first, create an object in our scene called “Bob” Drag the NewBehaviourScript on top of Bob. That makes the NewBehaviourScript a component of Bob. (very important)
Now, bob starts, he calls on all his scripts to Start which are based off the MonoBehaviour class. So NewBehaviourScript.Start runs. Because it runs, it creates the Object myClass which is NOT based off a MonoBehavior class. Even if it was, because it is not a Component of Bob, it will NOT Start.
We force the Start function in the junk object where we write some debug information.
now, every frame, Bob updates all of its components, which, in this case NewBehaviourScript forces the Update for myClass.
Now, if we drug the junk class to Bob, it would do nothing because it is not based on the MonoBehaviour.
Say we have a different GameObject with a different script, and we want to then “see” Bob, and “see” the NewBehaviourScript script. We have to ask Unity to get it for us.
NewBehaviourScript otherScript = GameObject.Find("Bob").GetComponent<NewBehaviourScript>();
// the JavaScript function works perfect even when calling C# objects.
var other : NewBehaviourScript= GameObject.Find("Bob").GetComponent(NewBehaviourScript);
NOTE: JavaScript is a little less type dependent, so its a little easier on the eyes… for me that is.
You can then access all public components of Bob’s NewBehaviourScript through script. (Including the junk myClass, since it is public.) By virtue, you will also be able to access myClass’s public functions.
A big not e to remember is that Unity… is C#, even if you are in JavaScript. Just because it looks a little different doesn’t make any difference…
System.BitConverter is the same in C# and JS, and you can use it just the same as if you were in C#… And so does (almost) every other .net component