6. Prefab Instance References

  06. Initialization No Comments

References to GameObjects and components that are only instantiated at runtime can be assigned into Init fields of client components that have an initializer.

To assign a reference to an yet-to-be-instantiated prefab instance, drag-and-drop a prefab asset from the Project window into the Init field of a client component in a scene, and select ‘Prefab Instance’ from the dropdown that opens.

This will make Init(args) automatically generate a unique Cross-Scene Id for the dragged Object, and assign a value provider into the client’s Init field, which will be used to automatically resolve the prefab instance reference at runtime during initialization.

You can click the Object field to ping the prefab asset from which the prefab instance will be created at runtime.

You can also right-click the prefab icon shown next to the field to open a context menu containing various functionality, such as opening the prefab asset, or copying the Cross-Scene Id of the referenced prefab instance to your clipboard.

Asynchronous Initialization

At runtime, if you want the client to receive the prefab instance in its Init method immediately when the client’s scene is loaded, you have to make sure to instantiate the prefab before the client’s scene finishes loading.

If the client is loaded before the prefab is instantiated, the client component will automatically be disabled and its initialization delayed, until the moment that the prefab instance becomes available (see MonoBehaviour<T>’s Asynchronous Initialization section for more details).

Any<TValue>

Any<TValue> type fields can also be used to support prefab instance references in addition to initializers.

Leave a Reply

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