lufydad
lufydad

Reputation: 285

Settings buttons from a script in inspector

I'm trying to create an RTS on UnityEngine. Like the age of empire series there is a menu at the bottom of screen that depends of the object that you select. Therefore, I created a class SObject (for selectable object) from which all objects inherit. For example, there is a class SHarvester, a class SAnimals, etc... The class SObject has an attribute :

[SerializeField]
private List<UnityAction> m_buttonCreation = new List<UnityAction>();

This list contains the methods specific to the object which will be linked to the buttons of the menu at the bottom of the screen.

Buttons which will be linked to a method defined by the List above

Everything is working well if you defined the list from the script.

But I would like to have prefabs of unit or building in the editor and to define the list of method directly from the inspector. But the unityAction types doesn't displayed in inspector.

Is there a way of displaying the UnityAction type in inspector ? Something like the button component :UnityAction serialized field in button component

I apologize if I didn't make myself clear.

Upvotes: 0

Views: 351

Answers (1)

Menyus777
Menyus777

Reputation: 7007

If you are not sticking to a UnityAction you could just use:

[SerializeField]
List<UnityEvent> m_buttonCreation = new List<UnityEvent>();

Which will show up like this in your inspector enter image description here

The default UnityButton component has UnityEvents and not UnityActions anyway:

Button.cs

namespace UnityEngine.UI
{
    [AddComponentMenu("UI/Button", 30)]
    public class Button : Selectable, IPointerClickHandler, IEventSystemHandler, ISubmitHandler
    {
        protected Button();

        public ButtonClickedEvent onClick { get; set; }

        public virtual void OnPointerClick(PointerEventData eventData);
        public virtual void OnSubmit(BaseEventData eventData);

        public class ButtonClickedEvent : UnityEvent
        {
            public ButtonClickedEvent();
        }
    }
}

and ofcourse the UnityEvent works with a UnityAction so IMHO you should just change Action to Event.

UnityEvent.cs

public class UnityEvent : UnityEventBase
{

    [RequiredByNativeCode]
    public UnityEvent();

    // This is what runs when you click on the (+) sign
    public void AddListener(UnityAction call);
    public void Invoke();
    // This is what runs when you click on the (-) sign
    public void RemoveListener(UnityAction call);
    protected override MethodInfo FindMethod_Impl(string name, object targetObj);
}

Upvotes: 1

Related Questions