Using CoherenceSyncConfig to instantiate GameObjects locally

Instead of hard referencing Prefabs in your scripts to instantiate them, you can reference a CoherenceSyncConfig and instantiate your local Prefab instances through our API. This will utilize the internal INetworkObjectProvider and INetworkObjectInstantiator interfaces to load and instantiate the Prefab in a given networked scene (a scene with a CoherenceBridge component in it).

using Coherence.Toolkit;
using UnityEngine;

public class CoherenceSyncConfigExample : MonoBehaviour
{
    public CoherenceSyncConfig prefabSyncConfig;
    public CoherenceBridge bridge;
    
    private CoherenceSync instance1;
    private CoherenceSync instance2;
    
    void Start()
    {
        // Load the prefab and instantiate it in the current scene
        instance1 = prefabSyncConfig.GetInstance();
        // Load the prefab and instantiate it in the specific networked scene for the given CoherenceBridge
        instance2 = prefabSyncConfig.GetInstance(bridge, Vector3.zero, Quaternion.identity);
    }
    
    private void OnDestroy()
    {
        // Instances have to be destroyed via the ReleaseInstance method, so that its destruction is handle by the 
        // internal INetworkObjectInstantiator
        prefabSyncConfig.ReleaseInstance(instance1);
        prefabSyncConfig.ReleaseInstance(instance2);
    }
}

You can also hard reference the Prefab in your script, and use our extensions to instantiate the Prefab easily using the internal INetworkObjectInstantiator interface implementation. The main difference is that the previous approach doesn't need a Prefab hard reference, and you won't have to change the code if the way that the Prefab is loaded into memory changes (for example, if you go from Resources to load it via Addressables).

using System;
using Coherence.Toolkit;
using UnityEngine;

public class InstantiatorViaCoherenceSyncComponent : MonoBehaviour
{
    // Serialized prefab reference
    public CoherenceSync prefab;
    public CoherenceBridge bridge;

    private CoherenceSync instance1;
    private CoherenceSync instance2;

    void Start()
    {
        // Instantiate it in the current scene
        instance1 = prefab.GetInstance();
        // Instantiate it in the specific networked scene for the given CoherenceBridge
        instance2 = prefab.GetInstance(bridge, Vector3.zero, Quaternion.identity);
    }

    private void OnDestroy()
    {
        // Instances have to be destroyed via the ReleaseInstance method, so that its destruction is handle by the 
        // internal INetworkObjectInstantiator
        instance1.ReleaseInstance();
        instance2.ReleaseInstance();
    }
}

Last updated