Pun2 - Syncing randomly chosen mesh

Hello, I’m trying to create an animal spawner using PUN2. I want the spawner to instantiate the prefab, then choose a random child mesh of that prefab to display, and sync that over the network so all clients see the same randomly chosen mesh.

Here’s what I’ve tried…

public class Spawner : MonoBehaviour
{
    [SerializeField] List<Transform> spawnPoints = new List<Transform>();
    [SerializeField] GameObject prefab;

    private void Start()
    {
        if (PhotonNetwork.IsMasterClient == false)
            return;
       
        foreach (Transform spawnPoint in spawnPoints)
        {
            var animal = PhotonNetwork.Instantiate(prefab.name, spawnPoint.position, spawnPoint.rotation);

            Renderer[] childMeshes = animal.GetComponentsInChildren<Renderer>();
            int activeIndex = Random.Range(0, childMeshes.Length);

            for (var i = 0; i < childMeshes.Length; i++)
                childMeshes[i].gameObject.SetActive(i == activeIndex);
        }
    }

}

This syncs the animal prefab across all clients, but only the Master Client displays the randomly chosen mesh. All other clients, all meshes are displayed.

How can I have a spawner spawn a prefab, display a random child mesh, and sync that across all clients? How can non-master clients know what index to display?

I tried passing the random index as a custom property and setting the mesh visibility inside OnPhotonInstantiate(PhotonMessageInfo info) and had no luck.

I also tried setting the index inside an RPC function, but that didn’t seem to work either.

This is how the prefab is structured I want to instantiate.

Thanks!

8409921--1111248--Screenshot 2022-09-02 040752.png

PhotonNetwork.Instantiate has a final, optional parameter: “data”. In it, you can pass some values with the instantiation.
In your case, pass the chosen, random skin and use it in a script that implements OnPhotonInstantiate.
There is a doc about Custom Instantiation Data.

This makes me think you might be working on some open world or some game with a lot of networked objects. In this case, I would recommend switching over to Fusion, which is our state of the art networking solution. It supports more networked objects with less overhead.

1 Like

That’s what I needed, thanks!

And yes, I am working on an open world game. I’ll have to look into Fusion!