passing method reference to be called in script using Serializable object

59 Views Asked by At

I have a Serializable object that I'm trying to store a method to be called. From this object, I would like to define a method from ScriptA to be called in ScriptB from SerializableScript.

The Serializable script

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

[CreateAssetMenu(fileName = "NewFieldInput", menuName = "Data/New Field Input Scene")]
[System.Serializable]
public class CallInput {
   public (some type) callMethod; // this is the confusing part
}

I would then have ScriptA have a method that will be called in ScriptB by referencing the value of callMethod passed into scriptB.

1

There are 1 best solutions below

0
ephb On

There are multiple solutions to your problem and it depends on the rest of your structure what would be the best to use.

  1. UnityEvent where you create an event and add your target methods as listeners. In all other cases I would use C# events or actions instead but UnityEvents can be subscribed in editor.
  2. You could create a base class that implements all the methods you want to call and inherit all your classes from that.
  3. Basically the same but you create an Interface and add that to all classes you are calling.

It comes down to whether you want to only call your own code which you can modify or external code too. If the latter is the case you should go with option 1. There are many more ways to do this but these came to mind first.