0
\$\begingroup\$

Use case: scriptable objects that contain different algorithms but generate compatible data, which are used randomly in a procedural system. They implement an interface so that the system can give them inputs and get outputs without knowing the concrete type, allowing a list of type MyInterface to contain various different algorithms.

I want an exposed list in the inspector that a designer can drag configured scriptable objects into, and the system will be influenced by whichever objects are there.

It works if I have an exposed list of any scriptableObjects and manually ensure they all implement MyInterface, and loop through that list internally adding them to aList<MyInterFace> that the system can iterate through. However List<MyInterface> won't show up in the inspector.

I've been told Odin will allow me to serialize the List<MyInterface> and access directly in the inspector.

Is this possible? Full disclosure I don't understand serialization well and very possibly just didn't convey what I'm trying to do properly.

The following code will work but the contents of the list will not carry through to runtime, and every time I have to initialize the list in the inspector by selecting List<MyInterface> from a dropdown:

public class Odintest : MonoBehaviour
{
    [ShowInInspector] public List<IMyInterface> InterfaceList;

    [Button("AccessAlgorithms")]
    public void AccessAlgorithms()
    {
        foreach (var v in InterfaceList)
        {
            print(v.MyMethod());
        }
    }
    
}

public interface IMyInterface
{
    public float MyVar { get; set; }
    public float MyMethod();
}

[CreateAssetMenu]
public partial class MySrciptableObject1 : ScriptableObject, IMyInterface
{
    public float param1;
    public float MyVar { get; set; }
    public float MyMethod()
    {
        // do something
        float result1 = 1;
        return result1;
    }
}

[CreateAssetMenu]
public class MySrciptableObject2 : ScriptableObject, IMyInterface
{
    public float param2;

    public float MyVar { get; set; }
    public float MyMethod()
    {
        // do somethign else
        float result1 = 1;
        return result1;
    }
}

I've read through the docs on implementing the serializer but I can't work out how to apply that to an interface.

Thanks for any help

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

You need to do this:

public class Odintest : SerializedMonoBehaviour
{
    [OdinSerialize] public List<IMyInterface> InterfaceList;

    // ... 
}

Notice SerializedMonoBehaviour and OdinSerialize.

[ShowInInspector] displays the field in the editor, but doesn't serialize it.

\$\endgroup\$
1
  • \$\begingroup\$ Amazing, it seems that has worked. Thanks. \$\endgroup\$ Jul 27 at 20:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .