Minimum players to enter in a room PHOTON - unity3d

I am doing a multiplayer game and I want to know how I can add a minimum number of players for a user to enter a room . Like to not be alone till one player is connected at least. What I should add to my script? I have this Room Options function but It doesn't work too add like Min players or something to it. (I expected if is MaxPlayers to exist MinPlayers too)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;
using Photon.Pun;
using UnityEngine.UI;
using Photon.Realtime;
public class MPManager : MonoBehaviourPunCallbacks, IPunObservable
{
public PlayFabAuth auth;
public string GameVersion;
public Text connectState;
public GameObject[] DisableOnConnected;
public GameObject[] DisableOnJoinRoom;
public GameObject[] EnableOnConnected;
public GameObject[] EnableOnJoinRoom;
public LoadedPlayer loadPlayer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
connectState.text = "Connection: " + PhotonNetwork.NetworkClientState;
}
public void ConnectToMaster()
{
// PhotonNetwork.connectionStateDetailed
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby(){
foreach(GameObject disable in DisableOnConnected){
disable.SetActive(false);
}
foreach (GameObject enable in EnableOnConnected){
enable.SetActive(true);
}
}
public void CreateOrJoin()
{
PhotonNetwork.LeaveLobby();
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
RoomOptions rm = new RoomOptions
{
MaxPlayers = 3,
IsVisible = true
};
int rndID = Random.Range(0, 3000);
PhotonNetwork.CreateRoom("Default: " + rndID, rm, TypedLobby.Default);
}
public override void OnJoinedRoom()
{
foreach (GameObject disable in DisableOnJoinRoom)
{
disable.SetActive(false);
}
foreach (GameObject enable in EnableOnJoinRoom)
{
enable.SetActive(true);
}
Debug.Log(loadPlayer.currentPlayer.name);
GameObject player = PhotonNetwork.Instantiate(loadPlayer.currentPlayer.name , Vector3.zero, Quaternion.identity, 0);
}
public override void OnLeftRoom()
{
PhotonNetwork.LeaveRoom();
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
throw new System.NotImplementedException();
}
}

Thank you for choosing Photon!
You need to get the count of actors (PhotonNetwork.CurrentRoom.PlayerCount) when you join the room (OnJoinedRoom) or when another player joins the room (OnPlayerEnteredRoom). When the number of actors joined is enough for you, start the game logic, e.g. load scene, send a custom event etc.

Related

Error: d__7.MoveNext() after changing model

At first my model was humanoid and the game worked fine. I had to change it to generic though and after that I got this error:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Pokemon.Fight
{
public class PokemonTrainer : MonoBehaviour
{
//public Animator Prefab
public Animator animator { get; set; }
private void Awake()
{
animator = GetComponentInChildren<Animator>();
}
public void SpawnTrainer(/*TrainerSO trainer*/)
{
//animator = Instantiate(trainer.trainerPrefab, transform);
//animator.transform.localPosition = Vector3.zero;
}
public void Throw(bool isPlayer, int id, int level)
{
StartCoroutine(ie_throw(isPlayer, id, level));
}
private IEnumerator ie_throw(bool isPlayer, int id, int level)
{
animator.SetTrigger("throw");
yield return new WaitForSeconds(0.11f);
PokemonBall ball = PokemonGameplay.Instance.pokemonEffectPool.GetPokemonBall();
ball.Throw(animator.GetBoneTransform(HumanBodyBones.RightHand).position, isPlayer, id, level);
}
//public void SetEndgame(bool isWin)
//{
// if (isWin) animator.CrossFadeInFixedTime("Victory", 0.1f);
// else animator.CrossFadeInFixedTime("Defeat", 0.1f);
//}
public void OnRebind()
{
animator.Rebind();
}
}
}
Here is the code that had the error and "PokemonBall ball = PokemonGameplay.Instance.pokemonEffectPool.GetPokemonBall();" This line in iethrow was the reason for it. Idk how to solve this, I changed nothing in my code when I change the model. And for this my Pokeball can't run in a right way.
Tried to figure out what is null but noothing is. The ball can still spawn but it headed to a wrong position(I set the position for it).

what to do when you won't save

when I load a new scene I get this error: NullReferenceException: Object reference not set to an instance of an object GameController+d__16.MoveNext () (at Assets/Scrips/GameController.cs:76) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at :0)
this is my script to save:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Scene_Manager : MonoBehaviour
{
int Saved_scene;
int Scene_index;
public void Load_Saved_Scene()
{
Saved_scene = PlayerPrefs.GetInt("Saved");
if (Saved_scene != 2)
SceneManager.LoadSceneAsync(Saved_scene);
else
return;
}
public void Save_and_Exit()
{
Scene_index = SceneManager.GetActiveScene().buildIndex;
PlayerPrefs.SetInt("Saved", Scene_index);
PlayerPrefs.Save();
SceneManager.LoadSceneAsync(0);
}
public void Next_Scene()
{
Scene_index = SceneManager.GetActiveScene().buildIndex + 1;
SceneManager.LoadSceneAsync(Scene_index);
}
}
and this is my script for the whole game where I call save:
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(GameUI))]
public class GameController : MonoBehaviour
{
public static GameController Instance { get; private set; }
[SerializeField]
private int knifeCount;
[Header("Knife Spawning")]
[SerializeField]
private Vector2 knifeSpawnPosition;
[SerializeField]
private GameObject knifeObject;
public GameUI GameUI { get; private set; }
private void Awake()
{
Instance = this;
GameUI = GetComponent<GameUI>();
}
private void Start()
{
GameUI.SetInitialDisplayedKnifeCount(knifeCount);
SpawnKnife();
}
public void OnSuccessfulKnifeHit()
{
if (knifeCount > 0)
{
SpawnKnife();
}
else
{
StartGameOverSequence(true);
}
}
private void SpawnKnife()
{
knifeCount--;
Instantiate(knifeObject, knifeSpawnPosition, Quaternion.identity);
}
public void StartGameOverSequence(bool win)
{
StartCoroutine("GameOverSequenceCoroutine", win);
}
private IEnumerator GameOverSequenceCoroutine(bool win)
{
if (win)
{
yield return new WaitForSecondsRealtime(0.3f);
FindObjectOfType<LevelLoader>().LoadNextLevel();
FindObjectOfType<Scene_Manager>().Save_and_Exit();
}
else
{
GameUI.ShowRestartButton();
}
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single);
}
}
Now first of all take a look at this post to understand NullReferenceExceptions.
After that take a closer look at your error message:
NullReferenceException: Object reference not set to an instance of an object GameController+d__16.MoveNext () (at Assets/Scrips/GameController.cs:76)
The (at Assets/Scrips/GameController.cs:76) part tells you exactly where you error is thrown (which basically means where it occured). It's in your Assets/Scrips/GameController.cs script at line 76.
private IEnumerator GameOverSequenceCoroutine(bool win)
{
if (win)
{
yield return new WaitForSecondsRealtime(0.3f);
FindObjectOfType<LevelLoader>().LoadNextLevel();
FindObjectOfType<Scene_Manager>().Save_and_Exit(); // <--- HERE
}
...
}
In your specific implementation my best guess would be that you shouldn't load your new scene before you try to save & quit. You're starting to load your new scene asynchronously and then call another function which loads another scene (?) while not actually preventing the first scene from activating until your other functions actually executed properly. There's a plethora of cases where this can and will break.
I think you'll need to rethink what it is your actually trying to accomplish because these function calls don't make sense like that.

Unity 3d Team Spawning with Photon 2

I have been stuck on this problem for a few months now. The problem being that I cannot properly instantiate my prefabs in the scene I want. I need the spawning to be one person on one team, and the rest on the other. But I'm not sure how to do that. What happens is that when I click the play button on my lobby menu, I get an error called "No cameras to display." I also noticed that the scene I want does load, but it doesn't switch to it because there are no cameras that are instantiated. I am using Photon 2. I am new to game development and your guys' help would be greatly appreciated! :)
I will post my code if that will help:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;
using Photon.Realtime;
using System.Linq;
using System.IO;
public class Launcher : MonoBehaviourPunCallbacks
{
public static Launcher Instance;
[SerializeField] TMP_InputField roomNameInputField;
[SerializeField] TMP_Text errorText;
[SerializeField] TMP_Text RoomNameText;
[SerializeField] Transform RoomListBackground;
[SerializeField] Transform PlayerListBackground;
[SerializeField] GameObject roomListItem_pf;
[SerializeField] GameObject PlayerListItem_pf;
[SerializeField] GameObject startGameButton;
public PhotonView PV;
public int myTeam;
public GameObject myAvatar;
void Awake()
{
Instance = this;
}
void Start()
{
Debug.Log("Connecting to Master");
PhotonNetwork.ConnectUsingSettings();
}
public void Update()
{
PV = GetComponent<PhotonView>();
if (PV)
{
PV.RPC("RPC_GetTeam", RpcTarget.MasterClient);
}
if (myAvatar == null && myTeam != 0)
{
if (myTeam == 1)
{
if (PV.IsMine)
{
int spawnPicker = Random.Range(0, GameSetup.GS.spawnPointsTeamOne.Length);
myAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Player"), GameSetup.GS.spawnPointsTeamOne[spawnPicker].position, GameSetup.GS.spawnPointsTeamOne[spawnPicker].rotation, 0);
}
}
if (myTeam == 2)
{
if (PV.IsMine)
{
int spawnPicker = Random.Range(0, GameSetup.GS.spawnPointsTeamTwo.Length);
myAvatar = PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "Player"), GameSetup.GS.spawnPointsTeamTwo[spawnPicker].position, GameSetup.GS.spawnPointsTeamTwo[spawnPicker].rotation, 0);
}
}
}
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to Master");
PhotonNetwork.JoinLobby();
PhotonNetwork.AutomaticallySyncScene = true;
}
public override void OnJoinedLobby()
{
MenuManager.Instance.OpenMenu("title");
Debug.Log("Joined Lobby");
}
public void CreateRoom()
{
if (string.IsNullOrEmpty(roomNameInputField.text))
{
return;
}
PhotonNetwork.CreateRoom(roomNameInputField.text);
MenuManager.Instance.OpenMenu("loading");
}
public override void OnJoinedRoom()
{
MenuManager.Instance.OpenMenu("room");
RoomNameText.text = PhotonNetwork.CurrentRoom.Name;
Player[] players = PhotonNetwork.PlayerList;
for (int i = 0; i < players.Count(); i++)
{
Instantiate(PlayerListItem_pf, PlayerListBackground).GetComponent<PlayerListItem>().Setup(players);
}
startGameButton.SetActive(PhotonNetwork.IsMasterClient);
}
public override void OnMasterClientSwitched(Player newMasterClient)
{
startGameButton.SetActive(PhotonNetwork.IsMasterClient);
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
errorText.text = "Room Creation Failed: " + message;
MenuManager.Instance.OpenMenu("error");
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
MenuManager.Instance.OpenMenu("loading");
}
public void JoinRoom(RoomInfo info)
{
PhotonNetwork.JoinRoom(info.Name);
MenuManager.Instance.OpenMenu("loading");
}
public override void OnLeftRoom()
{
MenuManager.Instance.OpenMenu("title");
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
foreach (Transform trans in RoomListBackground)
{
Destroy(trans.gameObject);
}
for (int i = 0; i < roomList.Count; i++)
{
Instantiate(roomListItem_pf, RoomListBackground).GetComponent<RoomListItem>().Setup(roomList);
}
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
Instantiate(PlayerListItem_pf, PlayerListBackground).GetComponent<PlayerListItem>().Setup(newPlayer);
}
[PunRPC]
public void RPC_GetTeam()
{
myTeam = GameSetup.GS.nextPlayersTeam;
GameSetup.GS.UpdateTeam();
PV.RPC("RPC_SentTeam", RpcTarget.OthersBuffered, myTeam);
}
[PunRPC]
public void RPC_SentTeam(int whichTeam)
{
myTeam = whichTeam;
}
}

Switching weapons with PUN 2

I can't seem to get this to work.
The player presses 1 or 2 or 3 etc depending where the weapon is on the hotbar and it will show the weapon by setting it active in the hierarchy.
everything works fine client side obviously but I cannot get it to show from the other players perspective. Not sure where to put the photon view or where to put the code exactly but this is my code that is currently on the hotbar slot.
Also worth mentioning that the item is selected from an actual inventory and not just a simple switch so it all corresponds to another bit of code that is the item script attached to the pickupable item.
Thanks if advanced if anyone can point me in the right direction.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using Photon.Realtime;
public class HotbarSlot : MonoBehaviourPunCallbacks
{
public GameObject[] unstaticItems;
public static GameObject[] items;
public Inventory inv;
public NewPlayerHealth updateVitals;
public AudioSource audioSource;
public AudioClip Eating;
public KeyCode key;
public PhotonView PV;
[SerializeField]
private GameObject placeableObjectPrefab;
[SerializeField]
private GameObject currentPlaceableObject;
private float mouseWheelRotation;
void Awake()
{
PV = GetComponent<PhotonView>();
}
void Start()
{
if (unstaticItems.Length > 0)
items = unstaticItems;
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (!PV.IsMine) return;
if (Input.GetKeyDown(key))
Equip();
if (Input.GetKeyDown(key))
{
EatFood();
}
PlaceFurnace();
RotateFromMouseWheel();
}
void Equip()
{
{
photonView.RPC("EquipRPC", RpcTarget.AllBuffered);
}
}
[PunRPC]
void EquipRPC()
{
{
if (transform.childCount > 1)
{
Item item = transform.GetChild(1).GetComponent<Item>();
if (item.equipmentType == "Hand")
{
for (int i = 0; i < items.Length; i++)
{
if (i == item.equipmentIndex)
{
items[i].SetActive(!items[i].activeInHierarchy);
}
else
{
items[i].SetActive(false);
}
}
}
}
}
}

Swapping Two GameObjects on Keypress

When I press Space, the player and the dummy are supposed to swap places. This doesn't just happen once, it needs to happen everytime I press the Space bar so they can swap back and forth. However, sometimes it works and sometimes it doesn't. When it doesn't work, the dummy teleports to the player and then the player teleports inside of the dummy (as that is where its last position is). This just kind of pushes the player about.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSwap : MonoBehaviour
{
public GameObject player;
public GameObject dummy;
public GameObject cameraAnchor;
public Transform playerLastPos;
public Transform dummyLastPos;
public bool haveSwapped;
public bool canSwap;
public float swapRadius;
public LayerMask dummyInRadius;
// Update is called once per frame
void Update()
{
canSwap = Physics.CheckSphere(player.transform.position, swapRadius, dummyInRadius);
SwapTransforms();
if (canSwap)
{
if (Input.GetKeyDown(KeyCode.Space))
{
haveSwapped = !haveSwapped;
Swapping();
}
}
else
{
Debug.Log("Can't Swap");
}
cameraAnchor.transform.position = player.transform.position;
}
public void SwapTransforms()
{
if (haveSwapped)
{
dummyLastPos.position = player.transform.position;
playerLastPos.position = dummy.transform.position;
}
else
{
dummyLastPos.position = dummy.transform.position;
playerLastPos.position = player.transform.position;
}
}
public void Swapping()
{
if (haveSwapped)
{
player.transform.position = dummyLastPos.position;
dummy.transform.position = playerLastPos.position;
}
else
{
player.transform.position = playerLastPos.position;
dummy.transform.position = dummyLastPos.position;
}
}
public void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(player.transform.position, swapRadius);
}
}
I've solved it. After cleaning up most of the code and realsing I had to turn off movement and the character controller on the player (Link:Unity Answers), I came up with this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSwap : MonoBehaviour
{
public ThirdPersonMovement playerMove;
public GameObject player;
public GameObject dummy;
public GameObject cameraAnchor;
public Transform playerLastPos;
public Transform dummyLastPos;
public bool canSwap;
public float swapRadius;
public LayerMask dummyInRadius;
// Update is called once per frame
void Update()
{
canSwap = Physics.CheckSphere(player.transform.position, swapRadius, dummyInRadius);
if (canSwap)
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerMove.canMove = false;
player.GetComponent<CharacterController>().enabled = false;
SetTransforms();
}
}
else
{
Debug.Log("Can't Swap");
}
cameraAnchor.transform.position = player.transform.position;
}
public void SetTransforms()
{
dummyLastPos.position = dummy.transform.position;
playerLastPos.position = player.transform.position;
Debug.Log("Set Transforms");
Swapping();
}
public void Swapping()
{
player.transform.position = dummyLastPos.position;
dummy.transform.position = playerLastPos.position;
dummy.transform.rotation = player.transform.rotation;
Debug.Log("Swap");
playerMove.canMove = true;
player.GetComponent<CharacterController>().enabled = true;
}
public void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(player.transform.position, swapRadius);
}
}