Home > Enterprise >  How do I add serialized field for a function in Unity?
How do I add serialized field for a function in Unity?

Time:10-10

I need to put a function from one class into another. And I want to put in the serialized field not the whole GameObject of the desired class, but one function from this class. How should I do it?
For example, I have a class GameActions describing game events.

public class GameActions : MonoBehaviour
{
    public void actionStart()
    {
        SceneManager.LoadScene("Game");
    }
}        

And I want to be able to fire a function actionStart in another class by putting it into serialized field (inside of toggleEnd, for example).

public class Countdown : MonoBehaviour
{
    [SerializeField] private SomeType toggleEnd;

    [SerializeField] private float currTime;
}

CodePudding user response:

To use the Unity Inspector to store and serialise classes, you would expose the class as a field. The Inspector will then let you drag and drop a class into the object field.

public class Countdown : MonoBehaviour
{
    // A reference to the GameActions class is serialised here.
    [SerializeField] private GameActions _gameActions;
    [SerializeField] private float currTime;

    // This is an example of a countdown timer.
    private void Update ( )
    {
        currTime -= Time.deltaTime;
        if ( currTime < 0 )
        {
            // This is how you call the GameActions actionStart method.
            _gameActions.actionStart ( );
            this.enabled = false;
        }
    }
}
  • Related