IValueProvider<TValue>

  8. Reference No Comments

Represents an object that can provide a value of type TValue on demand.

A scriptable object or component that implements the IValueProvider<TValue> interface can be assigned to an Initializer field of type TValue.

During initialization the Initializer will request the Init argument from the value provider, and pass it to the client’s Init method.

Example

If your value provider always returns the same value, regardless of the client that is requesting it, then you can just implement the IValueProvider<TValue>.Value property.

[CreateAssetMenu]
class MainCamera : ScriptableObject, IValueProvider<Camera>
{
    public Camera Value => Camera.main;
}

Example 2

If your value provider can return a different value based on the client that is requesting it, then you can also implement the IValueProvider<TValue>.TryGetFor method.

class NearestCamera : ScriptableObject, IValueProvider<Camera>
{
    public Camera Value => TryGetFor(null, out Camera camera) ? camera : null;

    public bool TryGetFor(Component client, out Camera camera)
    {
        if(client != null)
        {
            var camera = client.GetComponentInChildren<Camera>();
            if(camera != null)
            {
                return true;
            }

            camera = client.GetComponentInParent<Camera>();
            if(camera != null)
            {
                return camera;
            }

            camera = Object.FindObjectsByType<Camera>()
                .FirstOrDefault(c => c.gameObject.scene == client.gameObject.scene);
            if(camera != null)
            {
                return camera;
            }
        }

        return Camera.main;
    }
}

Use Cases

Value providers can provide functionality such as:

  • Providing a reference to prefab instance that is only created at runtime.
  • Providing a string that has been localized.
  • Providing a randomized name for a character.
  • And much more…

Here are some pre-existing IValueProvider<TValue> implementations that come bundled with Init(args)

  • MainCamera – Returns the current main camera with the tag “MainCamera”.
  • LocalizedString – Provides a string that has been localized by Unity’s Localization package.

See Also:

Leave a Reply

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