0
\$\begingroup\$

I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this:

public string PlayerPrefsName;

public GameObject Button;

public string GadgetForSkin;

private void Start()
{
    GadgetChanged = PlayerPrefs.GetInt(PlayerPrefsName);
    if (GadgetChanged == 0)
    {
        Button.SetActive(false);
    }
    GadgetForSkin = "GadgetForSkin" + GadgetChanged;
}

public void GadgetChecker()
{
    GadgetForSkin();
}

public void GadgetForSkin1()
{

}

If it's not possible, how can I achieve something similar?

\$\endgroup\$
2
\$\begingroup\$

You can do this with MonoBehaviour.Invoke or GameObject.SendMessage, like so:

Invoke(GadgetForSkin, 0f);             // Calls method on the next frame's update.
// Or 
gameObject.SendMessage(GadgetForSkin); // Calls method on every script on this object.

...but I would recommend strongly against using these in a modern project.

We have much better options now that don't result in "stringly-typed" code or costly reflection and search in the middle of your gameplay code.

Instead I'd recommend doing something like this...

[System.Serializable]
public struct Gadget {
    public string name;
    public Sprite icon;
    public UnityEvent onUse;
}

public Gadget[] gadgets;

int selectedGadget;

public void UseSelectedGadget() {
    gadgets[selectedGadget].onUse.Invoke();
}

This gives you a handy list of gadgets you can configure in the inspector, setting up the name/icon or other properties each one might need, and also lets you hook up any number of functions to call when the gadget is used. No mucking with strings required (and no garbage created from said string mucking).

You could even use one of the UnityEvent<T> options if you want to pass arguments to your gadget methods. That might help you avoid duplicated code. Say you have 4 different "grenade" gadgets that differ only in the elemental type of damage they do. You could pass that damage type as an argument, and have all 4 grenade gadgets call the same UseGrenade(DamageType damageType) function with their own arguments configured in the inspector, instead of needing a separate FragGrenade(), FrostGrenade(), LightningGrenade(), etc.

\$\endgroup\$
0

Your Answer

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

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