- Home /
Monobehaviour class variables not shown on inspector
Assume I have two classes:
[Serializable]
public class A : Monobehaviour
{
public int _myInt;
public B _classB;
}
[Serializable]
public class B : Monobehaviour
{
public int _myInt;
public string _myString;
}
Is there an easy way to make class B variables appear on the inspector on the script of class A?
Answer by SirPaddow · Jun 08, 2019 at 08:20 PM
No, and there shouldn't be a way, since MonoBehaviours shouldn't exist if not bound to a gameObject (same reason why you shouldn't do new B();).
But maybe you don't need it to be a MonoBehaviour? If you remove the inheritance, attributes of B will appear in the inspector of A.
Unfortunately I use updates so they have to derive from monobehaviour.
Well, it's difficult to understand what you want your code to do, but don't forget you can always do somthing like that:
[Serializable]
public class A : $$anonymous$$onoBehaviour
{
public int _myInt;
public B _classB;
public void Update()
{
_classB.Update();
}
}
[Serializable]
public class B
{
public int _myInt;
public string _myString;
public void Update()
{
// do stuff
}
}
I said in the original post the class has to derive from monobehaviour ,because it uses methods that derive from monobehaviour like update and start. And isn't this a very bad practise? To update an object from another one?
Answer by itaielidan · Jun 08, 2019 at 09:34 PM
The fastest way is to do something like this:
[Serializable]
public class A : MonoBehaviour
{
public int _myInt;
public B _classB;
private void Start(){
_classB = GameObject.Find("gameObject name that has class b attached").GetCompoment<B>();
}
public void Update()
{
_classB.Update();
}
}
[Serializable]
public class B
{
public int _myInt;
public string _myString;
public void Update()
{
// do stuff
}
}
No, it will throw an exception. If B is no longer a $$anonymous$$onoBehaviour, you can't use it in "GetComponent()"
Your answer
Follow this Question
Related Questions
Large serializable field in a MonoBehaviour causing poor performance in Inspector 1 Answer
How can I reference a specific script inside a GameObject from another MonoBehaviour. 2 Answers
Which function is called when i selected something on the Inspector? 0 Answers
Add a button in the component inspector 2 Answers
Binding component with MonoBehaviour so they are added together by inspector's "Add Component". 1 Answer