0
\$\begingroup\$

I created the following class, that should be used to display numeric text in a UI canvas (score, lives, etc.):

public class NumericField: UnityEngine.UI.Text {
    [SerializeField] int value = 0;

    override protected void Start() {
        base.Start();
        text = value.ToString();
    }

    public int Get() {
        return value;
    }

    public void Set(int newValue) {
        value = newValue;
        text = value.ToString();
    }

    public void Add(int toAdd) {
        Set(value + toAdd);
    }
}

Now, I would like to add a NumericField into my Canvas, instead of adding a Text. But, when I right-click the Canvas object, I do not see my NumericField. How can I add it to the menus, so that I can add it to the canvas?

\$\endgroup\$
  • \$\begingroup\$ Have you tried using the [CreateAssetMenu] attribute? \$\endgroup\$ – Artur Trapp Oct 24 at 13:00
  • \$\begingroup\$ Have you tried the usual AddComponent approach? The options you see in the context menu are just shortcuts to create GameObjects with certain commonly-used components, but they're by no means a limit on what components you can use. \$\endgroup\$ – DMGregory Oct 24 at 13:16
  • \$\begingroup\$ I am not sure if it is even possible to create custom UI components like that. I would usually solve this problem with a MonoBehaviour which implements the API functionality I want by interacting with the UnityEngine.UI.Text component on the same GameObject. \$\endgroup\$ – Philipp Oct 24 at 13:38
  • 1
    \$\begingroup\$ I would second Philipp's recommendation to implement this numeric field using composition over inheritance. But I can confirm that it is possible to derive your own custom Text classes from the built-in Unity version - I've used it to support inline icon display, for example. \$\endgroup\$ – DMGregory Oct 24 at 16:58
  • \$\begingroup\$ @ArturTrapp I added before the class [CreateAssetMenu(menuName ="NumericField")], but it had no effect. \$\endgroup\$ – Erel Segal-Halevi Oct 24 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.