- Home /
Having only one of the same gameobjects in a scene. Photon Pun
Hi!
I am making a multiplayer game in unity for the first time and In the game I have a SpawnEnemies gameobject that spawns enemies. Here is the SpawnEnemies script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class SpawnEnemies : MonoBehaviourPun
{
public GameObject enemy;
public EnemiesLeftBarScript enemiesLeftBar;
public PlayerController[] players;
public int maxEnemies = 50;
public static int enemiesLeft;
public Transform[] SpawnPoints;
private void Start()
{
enemiesLeft = maxEnemies;
enemiesLeftBar = FindObjectOfType<EnemiesLeftBarScript>();
enemiesLeftBar.photonView.RPC("SetMaxValue", RpcTarget.All, maxEnemies);
StartCoroutine(SpawnEnemyCoroutine());
}
IEnumerator SpawnEnemyCoroutine()
{
players = FindObjectsOfType<PlayerController>();
if (StartGameScript.gameIsStarted && enemiesLeft >= 0 && players.Length > 0)
{
PhotonNetwork.Instantiate(enemy.name, SpawnPoints[UnityEngine.Random.Range(0, 4)].position, Quaternion.identity);
}
yield return new WaitForSeconds(1);
StartCoroutine(SpawnEnemyCoroutine());
StopCoroutine(SpawnEnemyCoroutine());
}
}
The problem that I am having is that when you play multiplayer there will be several SpawnEnemies gameobjects and more enemies than intended will spawn because of that. How could I fix that? I'd greatly appreciate any help. :)
Answer by Captain_Pineapple · Aug 02, 2021 at 10:03 AM
The problem that you probably have is that this script will run for each connected client. So the more players there are the more Mobs will spawn. Everything in that regard should only be done by the master player. There is a flag PhotonNetwork.isMasterClient
that you can use to identify this player. So only run scripts like this if this flag is true
Your answer
![](https://koobas.hobune.stream/wayback/20220613041013im_/https://answers.unity.com/themes/thub/images/avi.jpg)