- Home /
monobehaviour class (javascript)
so far i was using components, i want to try with classes now. i made a simple class, but it seems that i do not know how to use it. here is the example:
class test extends MonoBehaviour{
var show : boolean=false;
function OnGUI(){
if(show){
GUI.Label(Rect(200,200,200,200),"Label");
}
if(Input.GetMouseButtonDown(0)){
show=!show;
}
}
}
so pressing the button, label should show, but when i try to instantiate the object of this class in other script i do not get the desirable result. i tried to do something like this: var test : test=new test();
//this does not work on monobehaviours then i tried this: var test : test;
// this does not automatically start the OnGUI function in the class i even tried this test.OnGUI
in other scripts OnGUI, that clearluy did not work.
so can somebody explain how to use the monobehaviour class and all basic things related to it. thanks!!
Answer by Seregon · Mar 01, 2011 at 12:33 PM
Monobehaviour classes need to be attached to a GameObject to work - only then will it's member functions (Awake, Start, Update, OnGUI etc.) be called.
So you either need to create a GameObject (probably an empty, if all it does is contain gui scripts) and attach your script in the editor, or if you want to create it later on, make a prefab containing this script, and instantiate it from code.
Another alternative, which may fit more closely to what your trying to achieve, is to add your test class as a component to an existing object:
var testclass : test;
testclass = gameObject.AddComponent("test");
Your answer
![](https://koobas.hobune.stream/wayback/20220613110806im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Component Class Hierarchy 2 Answers
Extending MonoBehavior and GameObject? 1 Answer
many "characters" data 3 Answers
Serializable class variables loose Gameobject reference in inspector 0 Answers
Question about classes C# 1 Answer