Represents an object that can provide values of requested types on demand.
A scriptable object or component that implements the IValueByTypeProvider interface can be assigned to an Initializer field, if IValueByTypeProvider.CanProvideValue returns true when provided the type of the field and a reference to the initializer.
During initialization the Initializer will request the Init argument from the value provider, and pass it to the client’s Init method.
Example
[CreateAssetMenu] class GetComponent : ScriptableObject, IValueByTypeProvider { public bool TryGetFor<TValue>(Component client, out TValue value) { if(client == null) { value = default; return false; } return client.gameObject.TryGetComponent(out value); } public bool CanProvideValue<TValue>(Component client) => client != null && (typeof(Object).IsAssignableFrom(typeof(TValue)) || typeof(TValue).IsInterface); }
Use Cases
Value providers can provide functionality such as:
- Cross-scene references.
- Providing a reference to prefab instance that is only created at runtime.
- Providing an asset that is loaded asynchronously using Addressables.
- A generic service locator that lazily creates and returns requested services.
- Providing a component found in the children of the client component.
- And much more…
Here are some pre-existing IValueByTypeProvider implementations that come bundled with Init(args):
- CrossSceneReference – Returns a reference to a component or game object that can located in a different scene than the client.
- AddComponent – Attaches a new instance of the given type to the client’s game object and returns it.
- GetComponent – returns an object of the requested type attached to the client’s game object.
- GetOrAddComponent – Returns an object of the given type attached to the client’s game object if one is found; otherwise, attaches a new instance of the type to the client and returns it.
- GetComponentInChildren – Returns an object of the requested type attached to the client’s game object or any of its children.
- GetComponentInParent – Returns an object of the requested type attached to the client’s game object or any of its parents.
- GetComponents – Returns all objects of the requested type attached to the client’s game object.
- GetComponentsInChildren – Returns all objects of the given type attached to the client’s game object and all of its children.
- GetComponentsInParent – Returns all objects of the given type attached to the client’s game object and all of its parents.
- FindAnyObjectByType – Returns an object of the given type that is currently loaded using.