Why do my objects spawn in twice?

Mycoal
Mycoal
edited November 8 in Tutorials and Code Sharing

For some reason, every time a new player joins, it clones the tile gameObject again, resulting in 2 sets of tiles no top of eachother.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.SceneManagement;

public class GridManager : MonoBehaviourPunCallbacks
{

  [SerializeField] private int _width, _height;


  [SerializeField] private Tile tilePrefab;

  [SerializeField] private Transform cam;

  public bool spawnedIn = false;

  public PhotonView pv;
  public GameObject holder;
  private bool start = true;
  private void Start()
  {
    if(PhotonNetwork.IsMasterClient)
    {
      if(spawnedIn == false)
      {
        pv.RPC("generateTile", RpcTarget.AllBuffered);
      }
    }
  }


   

  [PunRPC]
  void generateTile()
  {
    if (!spawnedIn)
    {
      //pv.RPC("setFalse", RpcTarget.AllBuffered);
      for (int x = 0; x < _width; x++)
      {
        for (int y = 0; y < _height; y++)
        {
          var spawnedTile = PhotonNetwork.Instantiate(tilePrefab.name, new Vector3(x, y), Quaternion.identity);
          spawnedTile.transform.parent = holder.transform;
          spawnedTile.name = $"Tile {x} {y}";
          spawnedIn = true;

          if (x > 7)
          {
            spawnedTile.gameObject.layer = 24;
          }
          else
          {
            spawnedTile.gameObject.layer = 23;
          }
          spawnedTile.GetComponent<Tile>().lane = y;
          if (start)
          {
            spawnedTile.GetComponent<Tile>().plantSelect = true;
            start = false;
          }
          var isOffset = (x % 2 == 0 && y % 2 != 0) || (x % 2 != 0 && y % 2 == 0);
          spawnedTile.GetComponent<Tile>().init(isOffset);
        }
      }
    }
       
    cam.transform.position = new Vector3((float)_width / 2 - 0.5f, (float)_height / 2 - 0.5f, -10);
    cam.transform.position = new Vector3(cam.transform.position.x, cam.transform.position.y + .55f, cam.transform.position.z);
    //PhotonNetwork.Destroy(gameObject);
  }


  [PunRPC]
  public void setFalse()
  {
    spawnedIn = true;
  }
}


This is the only script that actually spawns in the tiles. Thank you for helping!

Best Answer

  • Tobias
    Tobias admin
    Answer ✓

    You call the RPC on all clients. Each of your players will then spawn the tiles and network-instantiate them, which means everyone will see everyone's tiles.

Answers

  • Tobias
    Tobias admin
    Answer ✓

    You call the RPC on all clients. Each of your players will then spawn the tiles and network-instantiate them, which means everyone will see everyone's tiles.