- Home /
Unity - UI Dropdown uses constructor for DropDownItem
As many of you will know, Visual Studio makes it possible to see metadata of scripts by ctrl + left click on the script in your class, here the Dropdown class of UnityEngine.UI;
using UnityEngine.UI;
public class MyClass : MonoBehaviour
{
Dropdown dd;
}
So I wanted to create my own UI Element and kind of used the metadata as an "inspiration". ;) But then I saw, at the bottom of the DropdownScript, the new Class "DropdownItem" which derives from MonoBehaviour and has a constructor.
protected internal class DropdownItem : MonoBehaviour, IPointerEnterHandler, ICancelHandler, IEventSystemHandler
{
public DropdownItem();
public Text text { get; set; }
public Image image { get; set; }
public RectTransform rectTransform { get; set; }
public Toggle toggle { get; set; }
public virtual void OnCancel(BaseEventData eventData);
public virtual void OnPointerEnter(PointerEventData eventData);
}
The problem is if you try to do something similiar, you will get the warning that you are not allowed to create MonoBehaviours with the "new" keyword (okay, maybe the constructor is for something else here), but also the forums say, constructors in MonoBehaviours are a bad thing, because they tend to be called multiple times and u should always use the Awake() / Start() method. My question is: Why does Unity itself use a constructor in their UI class for a MonoBehaviour class?
my interpretation is the following. The UI does not have a native representation on the C++ engine side. It's still the engine to use this class though. So the engine uses the constructor to build an instance of this, but the user still needs to call instantiate as that triggers that process internally.
Your answer
Follow this Question
Related Questions
AndroidJavaObject Builder Class 1 Answer
How to add GameObject to List using a constructor method 1 Answer
Error trying to createMonoBehaviour using the 'new' keyword in cSharp script 4 Answers
How can I call a new class function with InvokeRepeating ? 1 Answer
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. 2 Answers