Any<TValue>

  8. Reference No Comments

The Any<TValue> struct can be used to create serialized fields, into which you can assign any objects of the given type.

TValue can be of any type, including:

  • Plain-old C# class
  • UnityEngine.Object
  • An interface type

You’ll be able to select any assignable value for the serialized field using the Inspector, and it will be serialized for you.

Initializers already use Any<TValue> fields internally. This means that will probably not need to define Any<TValue> fields manually except on rare occasions.

Service Support

If a Service has the defining type TValue, then serialized fields of type Any<TValue> will automatically receive a reference to the service.

You are however still able to manually drag-and-drop some other Object into the field, to use that instead of the default Service instance.

Value Provider Support

Any value providers that can provide a value of type TValue can be drag-and-dropped into a serialized field of type Any<TValue>.

Example

If you wanted to make it possible to assign any object that implements the IInteractable interface using the Inspector, you could add a member field of type Any<IInteractable> to your component class:

[SerializeField]
Any<IInteractable> interactable;

You can then use the Value property or the GetValue(Component client) method to acquire the value from the Any<T> field.

[SerializeField] Any<IInteractable> interactable;

IInteractable Interactable => interactable.GetValue(this);

void Interact() => interactable.Interact(this);

You will need to use the GetValue method and pass in the the client in order to acquire Local Service results, and to get values from certain Value Providers, such as GetComponent.

Leave a Reply

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