I have a simple function attached to a button. I then decided to change it by adding an input. The problem is that the function won’t run unless I specify the input in Unity via the inspector. I don’t want to do that because it will affect the function and I have already changed it inside. I already set the input when I run the function so there’s no need to set it again in Unity; this is a problem because the input is going to be different depending on different scenarios. How can I overcome this?

public void Eruption(string biome)
{
    if (biome == “sea”) {
        // do something
    }
}
up vote 1 down vote accepted

Unfortunately you can not tell Unity buttons to call methods with parameters. If you want different buttons to call the same method with different parameters, you will have to take one of several possible workarounds:

Option 1: Create a wrapper-method for each one which takes no arguments and then calls the method you want with the correct argument:

public void ErruptionAtSea()
{
    Erruption("sea");
}
public void ErruptionAtLand()
{
    Erruption("land");
}
// ...and so on.

Option 2: Add a script to the button which says which biome this button is for. Wire the onclick-event of the button to that script:

public class EruptionButton : MonoBehaviour {

    public string biomeName;

    public void DoEruption () {
        Eruption(biomeName)
    }
}

Option 3: If you don't want to set up the click handling for each button individually, you can have that script take care of this automatically by assigning a newly created anonymous method as a click handler to the button on the same game object:

[@RequireComponent(typeof (UnityEngine.UI.Button))]
public class EruptionButton : MonoBehaviour {

    public string biomeName;

    void Start () {
        UnityEngine.UI.Button button = GetComponent<UnityEngine.UI.Button>();
        button.onClick.AddListener(() => { Eruption(biomeName); } );
    }
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.