How do I create an ‘Instance’ in JavaScript for my other scripts to reference ?
C# example :
using UnityEngine;
using System.Collections;
public class TP_Controller : MonoBehaviour
{
public static TP_Controller Instance;
void Awake() {
Instance = this;
}
}
My js workaround for where the C# script creates an ‘Instance’ to read and write vars from , I found the other scripts and stored them in local vars.:
public var TP_Motor : Script_TP_Motor;
function Awake() {
TP_Motor = GetComponent("Script_TP_Motor") as Script_TP_Motor;
}
Any help or info would be greatly appreciated.
This is the same as my other question , but it was answered with (helpful) information not specific to my question. http://answers.unity3d.com/questions/235181/help-with-creating-a-class-in-javascript.html
I shall remove the duplicate when I hopefully have an answer to help clean up the system. Thanks.
2 Answers
2
Just to clarify, static class and instances are opposite concepts. From the look of things, I’d say you’re interested in the Singleton pattern.
EDIT: Well you could either have a static class or a regular class with static variables. Here’s a quick example:
//MyScript.js
public class MyScript extends MonoBehaviour
{
public static var myName:String = "By0log1c";
public var myLocation:String = "Quebec, Canada";
}
//MyStaticScript.js
//static class must extend from object (just leave it blank)
public static class MyStaticScript
{
//myAge is static since its within MyStaticScript
public var myAge:int = 23;
}
//SomeScript.js
public class SomeScript extends MonoBehaviour
{
function Start():void
{
Debug.Log(MyScript.myName); //MyScript.myName is static
Debug.Log(MyStaticScript.myName); //MyStaticScript is static
Debug.Log(MyScript.myLocation); //nothing static here = error!
}
}
Frankly, the singleton pattern is what really taught me what static is. Here’s a JS example:
//let's combine the best of both world!
public class MySingleton extends MonoBehaviour
{
private static var instance:MySingleton;
public static function Instance():MySingleton
{
return instance;
}
var nonStaticVariable:boolean = false;
function Awake():void
{
instance = this;
}
}
//SomeScript.js
public class SomeScript extends MonoBehaviour
{
function Start():Void
{
//we access MySingleton through its static Instance
//function and use a MonoBehaviour like it was static!
Debug.Log(MySingleton.Instance().nonStaticVariable);
}
}
That’s a lot of reading but trust me, you’ll love singleton.
The JS equivalent of the C# code you posted is:
static var Instance : TP_Controller;
function Awake() {
Instance = this;
}
In my example I am trying to show : C# creates an Instance of TP_Controller which TP_Motor can read from. My method loads TP_Motor into a var which through that var TP_Controller commands direct statements to TP_Motor . This works , but what if I want another script to read from TP_Controller ?
– AlucardJay