11. ScriptableWrapper

  04. Features No Comments

The ScriptableWrapper class is a ScriptableObject that can act as a simple wrapper for a plain old class object.

It makes it easy to take a plain old class object and serialize it as an asset in the project.

Let’s say you had a plain old class called Settings:

public class Settings
{
    public float MoveSpeed = 10f;
    public float JumpHeight = 4f;
}

To create a scriptable wrapper for the Settings class, create a class that inherits from ScriptableWrapper<Settings>.

public class SettingsAsset : ScriptableWrapper<Settings> { }

Beyond being able to wrap a plain old class object, this class functions just like a normal ScriptableObject, so you can decorate it with the CreateAssetMenu attribute to make it easy to create an instance of the asset from Unity’s create menu.

[CreateAssetMenu]
public class SettingsAsset : ScriptableWrapper<Settings> { }

You can access the plain old class wrapped by a ScriptableWrapper through the WrappedObject property.

var settingsAsset = Resources.Load<SettingsAsset>("Settings");
Settings settings = settingsAsset.WrappedObject;

This scriptable wrapper implements IInitializable<Settings>, which means that a new instance can be initialized with the Settings object passed as an argument using the custom Instantiate or Create.Instance methods that come with Init(args).

You can create create a new instance of the SettingsAsset with a Settings object wrapped inside of it using Create.Instance:

public void SaveSettings(Settings settings)
{
    var settingsAsset = Create.Instance<SettingsAsset>(settings);
    AssetDatabase.CreateAsset(settingsAsset, "Resources/Settings.asset");
}

You can clone an existing Settings asset while injecting a new Settings object inside of it using settingsAsset.Instantiate(settings);

public SettingsAsset InstantiateSettingsAsset(Settings overrideSettings = null)
{
    SettingsAsset settingsAsset = Resources.Load<SettingsAsset>("Settings");

    if(overrideSettings != null)
    {
        return settingsAsset.Instantiate(overrideSettings);
    }

    return Object.Instantiate(settingsAsset);
}

Unity Events

Wrapped objects can receive callbacks during select Unity events from their wrapper by implementing one of the following interfaces:

  1. IAwake – Receive callback during the ScriptableObject.Awake event.
  2. IOnEnableReceive callback during the ScriptableObject.OnEnable event.
  3. IUpdate Receive callback during the Update event.
  4. IFixedUpdateReceive callback during the FixedUpdate event.
  5. ILateUpdateReceive callback during the LateUpdate event.
  6. IOnDisableReceive callback during the ScriptableObject.OnDisable event.
  7. IOnDestroyReceive callback during the ScriptableObject.OnDestroy event.

Leave a Reply

Your email address will not be published. Required fields are marked *