- Home /
Question by
JonK · Jul 19, 2013 at 08:13 PM ·
multipleinheritanceaccessing from any scriptanother script
Instantiating scripts inheriting from a base class
I have two scripts for activating two types of buttons. What I would like to do is have a script (that for example changes the color of the object its attached to) that can access either of the button scripts to see if they are active. I would place this new script on a button object (which will only have one of the button scripts attached) and it would be able know figure out which button script to use.
i.e. instead of doing this:
LeverButton LB;
PushButton PB;
void Start () {
LB = transform.GetComponent<LeverButton>();
PB = transform.GetComponent<PushButton>();
}
I have some understanding of base classes but I'm unsure of how I would go about this.
Comment
Best Answer
Answer by supercouge · Jul 19, 2013 at 10:01 PM
abstract public class MyButton : MonoBehaviour {
public bool isActive = false;
}
// derived from MyButton
public class LeverButton : MyButton {
}
// derived from MyButton
public class PushButton : MyButton {
}
public class YourOtherScript : MonoBehaviour {
protected myButton; // either LeverButton or PushButton
void Start() {
myButton = GetComponent<MyButton>();
if(myButton == null) Debug.Log("button has not been found");
//test if button is "active"
if(myButton.isActive == true)
Debug.Log("button is active");
}
}
This should do the trick. ;) Note that MyButton is an abstract class.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110446im_/https://answers.unity.com/themes/thub/images/avi.jpg)