Having only one if the same gameobjects in a scene
Options
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.
0
Best Answer
-
Be aware that this script is loaded by any player. So multiple players in the room will load and execute it and thus spawn enemies.
A simple approach to solve this is to run some code only for the Master Client of a room.0
Answers
-
Be aware that this script is loaded by any player. So multiple players in the room will load and execute it and thus spawn enemies.
A simple approach to solve this is to run some code only for the Master Client of a room.0