- Home /
Classes in a main class
I have multiple scripts and I want to put them in one main script so I could remove other components, but how do I make the other script support monobehaviour?
@Avash You'll have to provide the scripts, it's impossible to answer your question without them.
Or explain your problem with more details, what would be "the other script"? What do you mean by "support" monobehaviour?
You want a component to contain multiple monobehaviours? Don't think Unity works like that. That goes against the GameObject-Component relationship system.
$$anonymous$$ultiple classes in a script? No problem...
$$anonymous$$ultiple behaviours in a script? Causes problems.
Answer by BMayne · Sep 18, 2015 at 08:00 PM
Hello there,
You have to put each of your class that inherit from Monobahviour in their own file with the same name as the class itself.
Cheers,
Theoretically, you can ($$anonymous$$ainClass.cs):
using UnityEngine;
public class $$anonymous$$ainClass : $$anonymous$$onoBehaviour
{
private void Start()
{
gameObject.AddComponent<InnerClass>();
gameObject.AddComponent<OtherClass>();
}
public class InnerClass : $$anonymous$$onoBehaviour
{
private void Update()
{
Debug.Log("Inner update");
}
}
}
public class OtherClass : $$anonymous$$onoBehaviour
{
private void Update()
{
Debug.Log("Other update");
}
}
But you won't be able to work with them in the editor/inspector. There may be other issues as well, so it's best to avoid it.
Yes you are physically able too but they will not be loaded by Unity and you will not be able to add them using any of Unity UI. If you try to add the component in code you will get a pop up window from Unity saying "Your script name must much the class name".
Yes, that's why I said "you won't be able to work with them in the editor/inspector". But they will be "loaded", that is Unity will still (de)serialize the data. You can do:
using UnityEngine;
[ExecuteInEdit$$anonymous$$ode]
public class $$anonymous$$ainClass : $$anonymous$$onoBehaviour
{
private void Start()
{
if (GetComponent<OtherClass>() == null)
gameObject.AddComponent<OtherClass>().x = 5;
}
}
public class OtherClass : $$anonymous$$onoBehaviour
{
public int x = 0;
}
Add $$anonymous$$ainClass, then remove it. Then save and reload the project. It will have saved the value 5.
I am not saying this is a good way to do it. It's a bad way and no one should do it. But it's not impossible.
Answer by Avash · Sep 19, 2015 at 02:09 PM
So I had some problems with inheriting and now do this: MonoBehaviour.Destroy() or MainClass.transform.parent. I think it's good enought.