Call functions via variable, like a button

Hi there, what I want to seems pretty simple, I want to call a function, but be able to change that easily, such as having it like a button: 78787-screenshot-13.png
I can’t really work out how to do it, apart from in a script (just an example I put in):78789-screenshot-14.png

Okay, I’ll clear things up a little. At the moment my script goes:

    if(targets*.hit)*

{
print(“All hit”);
//In here I’d call a function, such as example.DoSomething();
//But I don’t want to hard code this function in ^^
//And do it like a button, where you can change the function in
// The inspector, without it being hard coded
}
If you can understand what I mean that’d be awesome if you could reply, thanks

A simple way is to use SendMessage.

public GameObject targetGo;
public string functionName;

public void DoSendMessage()
{
    targetGo.SendMessage(functionName);
}

If you want to call multiple functions then the two variables can be in a list.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class SendMessageInfo
{
    public GameObject targetGo;
    public string functionName;
}

public class MessageSender : MonoBehaviour {

    public List<SendMessageInfo> sendMessageInfos;

    public void OnClick() {
        foreach(SendMessageInfo smi in sendMessageInfos)
        {
            smi.targetGo.SendMessage(smi.functionName);
        }
    }
}

First make sure you function is public

public void DoSomethingFunction()
{
//Stuff here
}

Then attach it to a GameObject, I usually use GameController

Then click the “+” symbol on the OnClick() component (first image).

Attach the GameObject with the script attached into the component.

Then from the drop down list you will be able to select the function you want to be called when the button is pressed.

You can do something like that

class ButtonBehaviour : MonoBehaviour
    {
        public delegate void CustomFunctionEvent();
        public event CustomFunctionEvent OnCustonFunctionEvent;

        void Awake()
        {
            this.gameObject.GetComponent<Button>().onClick.AddListener(OnButtonClicked);
        }

        void LoadCustomFunction(int id)
        {
            //OnCustonFunctionEvent = null;
            if (id == 1)
                OnCustonFunctionEvent += ButtonAction1;
            else
                OnCustonFunctionEvent += ButtonAction2;
        }

        void ButtonAction1()
        {
            //...do something;
        }

        void ButtonAction2()
        {
            //...do something;
        }

        void OnButtonClicked()
        {
            if (OnCustonFunctionEvent != null)
                OnCustonFunctionEvent();
        }
    }