I'm trying to sync all the player names on server and client side, I'm following this tutorial, but I've made some changes to the code.
InitiateMultiplayer.cs
using Unity.Netcode;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Text;
namespace Multiplayer
{
public class InitiateMultiplayer : MonoBehaviour
{
[Serializable]
public class ConnectionPayload
{
public string password;
public string playerName;
}
public struct PlayerData
{
public string PlayerName { get; private set; }
public PlayerData(string playerName)
{
PlayerName = playerName;
}
}
private static Dictionary<ulong, PlayerData> clientData;
// Start is called before the first frame update
void Start()
{
NetworkManager.Singleton.NetworkConfig.ConnectionApproval = true;
switch (Buttons.GameMode)
{
case "Host":
clientData = new Dictionary<ulong, PlayerData>();
clientData[NetworkManager.Singleton.LocalClientId] = new PlayerData(Buttons.PlayerName);
NetworkManager.Singleton.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.Singleton.StartHost();
break;
case "Client":
Debug.Log("Client Started");
var payload = JsonUtility.ToJson(new ConnectionPayload()
{
password = "",
playerName = Buttons.PlayerName,
});
byte[] payloadBytes = Encoding.ASCII.GetBytes(payload);
// Set password ready to send to the server to validate
NetworkManager.Singleton.NetworkConfig.ConnectionData = payloadBytes;
NetworkManager.Singleton.StartClient();
break;
default:
break;
}
}
public static PlayerData? GetPlayerData(ulong clientId)
{
if (clientData.TryGetValue(clientId, out PlayerData playerData))
{
return playerData;
}
return null;
}
private void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
Debug.Log("approving");
string payload = Encoding.ASCII.GetString(request.Payload);
var connectionPayload = JsonUtility.FromJson<ConnectionPayload>(payload);
response.Approved = true;
response.Position = Vector3.zero;
response.Rotation = Quaternion.identity;
if (response.Approved)
{
response.CreatePlayerObject = true;
Debug.Log("approved");
response.PlayerPrefabHash = null;
response.Pending = false;
if (!clientData.TryGetValue(request.ClientNetworkId, out PlayerData playerData)) {
Debug.Log("we dont got data");
clientData[request.ClientNetworkId] = new PlayerData(connectionPayload.playerName);
}
}
}
}
}
Player.cs
using Unity.Netcode;
using UnityEngine;
using TMPro;
using Unity.Collections;
namespace Multiplayer
{
public class Player : NetworkBehaviour
{
[SerializeField] private TMP_Text displayNameText;
[SerializeField] private Renderer playerBody3D;
private NetworkVariable<FixedString32Bytes> displayName = new NetworkVariable<FixedString32Bytes>();
public override void OnNetworkSpawn()
{
if (!IsServer) { return; }
Debug.Log("Sapwned");
InitiateMultiplayer.PlayerData? playerData = InitiateMultiplayer.GetPlayerData(OwnerClientId);
if (playerData.HasValue)
{
Debug.Log("data -"+playerData.Value.PlayerName);
displayName.Value = playerData.Value.PlayerName;
}
}
private void OnEnable()
{
displayName.OnValueChanged += HandleDisplayNameChanged;
}
private void OnDisable()
{
displayName.OnValueChanged -= HandleDisplayNameChanged;
}
private void HandleDisplayNameChanged(FixedString32Bytes oldDisplayName, FixedString32Bytes newDisplayName)
{
if (IsClient) Debug.Log("client");
Debug.Log("Change in value"+newDisplayName.ToString());
displayNameText.text = newDisplayName.ToString();
}
}
}
The issue I'm facing is that the names are getting synced only on the server side, on the client side the palyer names are the default text.
Related
I am making a chatbot (well I'm attempting!) and I have set up wit.ai to handle the text-to-speech of the bot. My issue is that I am pulling all of the chat into the speaker on each update which is overloading the TTS, when I really only want the line of the Bot (Dave) to go through the speaker and update with each new line. How can I isolate only the bots lines? Would love some help with this!
public class SimpleCharacter : MonoBehaviour
{
public GameObject item;
public Scrollbar verticalScrollbar;
public ScrollRect scrollRect;
public TMP_Text chatText;
private Animator anim;
public TTSSpeaker _speaker;
// Start is called before the first frame update
void Start()
{
Debug.Log("Simple Character start 0 ");
anim = GetComponentInChildren<Animator>();
if (anim == null)
{
Debug.Log("Simple Character anim is null");
}
Debug.Log("Simple Character start 1");
}
public void Think (string text)
{
string chat = chatText.text;
chat = chat + "/n" + text;
chatText.text = text;
anim.SetTrigger("Think");
}
public void Talk(List<Choice> choices)
{
string chat = chatText.text;
chatText.text = "";
Debug.Log("////////////////////// : " + chat);
chat = chat + "/n" + choices[0].ToString();
Debug.Log("////////////////////// : " + chat);
chatText.text = chat;
chatText.text = choices[0].ToString();
anim.SetTrigger("Talk");
}
public void Talk (string text)
{
string chat = chatText.text;
chat = chat + "/n" + text;
chatText.text = chat;
chatText.text = text;
_speaker.Speak(chatText.text);
}
}
Daves's lines are being received from this character's script
namespace OpenAI_Unity
{
public class OAICharacter : OAICompletion
{
protected override StringBuilder GetDefaultInformation()
{
Debug.Log("GetDefaultInformation - OAICharacter");
var sb = base.GetDefaultInformation();
sb.Replace("[Subject]", this.characterName);
sb.Append($"\n\nHuman: Hi\n{characterName}: Hello\nHuman: ");
return sb;
}
public override string Description { get => $"The following is a conversation between a Human and {characterName}.\n"; set => throw new System.NotImplementedException(); }
public override string InjectStartText { get => "\n" + characterName + ":"; set => throw new System.NotImplementedException(); }
[SerializeField]
private string characterName = "Dave";
public override string InjectRestartText { get => "\nHuman: "; set => throw new System.NotImplementedException(); }
public override string[] StopSequences { get => new string[] { "\n", "Human:" }; set => throw new System.NotImplementedException(); }
public override int NumOutputs { get => 1; set => throw new NotImplementedException(); }
private void ThrowError (string value)
{
Debug.LogError($"Can not set OAICharacter variable to {value}! If you want to modify these please use an OAISimpleObject instead");
}
}
}
This is the controller script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using OpenAI_Unity;
using TMPro;
public class ChatController : MonoBehaviour
{
public OAICharacter _oaiCharacter;
public TMP_InputField questionInput;
// Start is called before the first frame update
void Start()
{
questionInput.onEndEdit.AddListener((string data) =>
{
if (!string.IsNullOrEmpty(data))
{
_oaiCharacter.AddToStory(data);
}
questionInput.text = "";
});
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
questionInput.Select();
questionInput.ActivateInputField();
}
}
}
And the completion
namespace OpenAI_Unity
{
/// <summary>
/// Used for objects that communicate with OpenAI Completion
/// Abstract itself, for a Generic and fully customizable Completion object use OAIGenericCompletion
/// </summary>
public abstract class OAICompletion : MonoBehaviour
{
public abstract string Description
{
get; set;
}
public abstract string InjectStartText
{
get; set;
}
public abstract string InjectRestartText
{
get; set;
}
public abstract string[] StopSequences
{
get; set;
}
public EngineEnum engine;
public enum EngineEnum
{
Ada,
Babbage,
Curie,
Davinci
}
public enum LogLevel
{
None,
Responses,
ResponsesAndMemory
}
public LogLevel logLevel;
public int Max_tokens = 16;
[Range(0, 1)]
public double Temperature = 0.1;
[Range(0, 1)]
public double Top_p = 1;
public abstract int NumOutputs {get;set;}
[Range(0, 1)]
public double PresencePenalty = 1;
[Range(0, 1)]
public double FrequencyPenalty = 1;
public int LogProbs = 1;
public StringEvent QuestionReceivedEvent;
public ChoicesEvent ResponseReceivedEvent;
public ChoiceEvent ResponseReceivedEvent1;
/// <summary>
/// This can be disabled when using multiple responses, since they should not be manually added to the entire memory
/// </summary>
[HideInInspector]
public bool autoAddResponseToMemory = true;
public StringBuilder memory ;
private void Start()
{
Debug.Log("OAI Completion start 0 ");
memory = GetDefaultInformation();
Debug.Log("Start - memory: " + memory);
Debug.Log("OAI Completion start 1 ");
}
public void Brainwash(bool resetToDefault = true)
{
memory = resetToDefault ? GetDefaultInformation() : new StringBuilder();
}
/// <summary>
/// D
/// </summary>
/// <returns></returns>
protected virtual StringBuilder GetDefaultInformation()
{
Debug.Log("GetDefaultInformation - OAICompletion");
StringBuilder sb = new StringBuilder();
sb.Append(Description);
foreach (OAIBehavior behavior in GetComponents<OAIBehavior>())
{
string behaviorText = behavior.GetAsText();
sb.Append(behaviorText);
sb.Append(" ");
}
return sb;
}
public async void AddToStory(string value)
{
//QuestionReceivedEvent?.Invoke(value);
//Character should remember what they said before, since every time we send a request it requires the full 'story' to OpenAI
memory.Append(value).Append(InjectStartText);
QuestionReceivedEvent?.Invoke(memory.ToString());
if (logLevel == LogLevel.ResponsesAndMemory)
{
Debug.Log(memory);
}
if (!OAIEngine.Instance)
{
Debug.LogError("No OAIEngine object found in scene. Make sure there's a GameObject with an OAIEngine Component in your scene");
return;
}
//We allow the engine to change per request (= per character and per statement)
OAIEngine.Instance.Api.UsingEngine = GetEngine(engine);
if (NumOutputs < 1)
{
Debug.LogWarning($"NumOutputs was set to {NumOutputs}. You should have at least 1 output!");
NumOutputs = 1;
} else if (autoAddResponseToMemory && NumOutputs > 1)
{
Debug.Log("Multiple or no outputs are requested while autoAddResponseToMemory is still true. You should set this to false and manually call 'AddResponseToMemory' after selecting your prefered response.");
}
Debug.Log("Stop Seq: " + StopSequences[0] + " _ " + StopSequences[1]);
var c = new CompletionRequest(memory.ToString(), Max_tokens, Temperature, Top_p, NumOutputs, PresencePenalty, FrequencyPenalty, LogProbs, StopSequences);
var results = await OAIEngine.Instance.Api.Completions.CreateCompletionsAsync(c);
//ResponseReceivedEvent?.Invoke(results.Completions);
//We make it easy by auto-adding responses to the memory
if (autoAddResponseToMemory)
{
var r = results.Completions[0].Text;
AddResponseToMemory(r);
if (logLevel == LogLevel.Responses || logLevel == LogLevel.ResponsesAndMemory)
{
Debug.Log(r);
}
}
}
public void AddResponseToMemory (string value)
{
memory.Append(value).Append(InjectRestartText);
ResponseReceivedEvent1?.Invoke(memory.ToString());
Debug.Log("Memory: " + memory);
}
private Engine GetEngine(EngineEnum e)
{
switch (e)
{
case EngineEnum.Ada:
return Engine.Ada;
case EngineEnum.Babbage:
return Engine.Babbage;
case EngineEnum.Curie:
return Engine.Curie;
case EngineEnum.Davinci:
return Engine.Davinci;
}
return Engine.Default;
}
}
}
You should work with the text string that is passed to the function instead of the entire chat text. Assuming that all spoken dialog starts with "Dave: " you can easily detect this substring in the text, remove it and pass it to your text to speech.
using System;
string botName = "Dave: ";
public void Talk(string text){
chatText.text += "\n" + text;
if(text.StartsWith(botName)){
string spokenText = text.Remove(0, botName.Length)
_speaker.Speak(spokenText);
}
}
I'm trying to get users to see each other's nicknames, but it doesn't work on client.
On server it works fine? but on client texts don't sync. TextMehPro is child of PlayerPrefab
On Client
enter image description here
On Server
enter image description here
This is my network manager
using Mirror;
using TMPro;
public class NetManager : NetworkManager
{
private UserController controller;
public TextMeshPro nickname;
public override void Start()
{
base.Start();
controller = UserController.Shared;
}
private void OnCreateCharacter(NetworkConnectionToClient conn, UserMessage message)
{
var go = Instantiate(playerPrefab);
var user = new User(message);
var tank = go.GetComponent<TankController>();
tank.thisNick.text = user.UserName;
NetworkServer.AddPlayerForConnection(conn, go);
tank.SetUser(user);
}
public override void OnStartServer()
{
base.OnStartServer();
NetworkServer.RegisterHandler<UserMessage>(OnCreateCharacter);
}
public override void OnClientConnect()
{
base.OnClientConnect();
ActivatePLayerSpawn();
}
private void ActivatePLayerSpawn()
{
var user = controller.User;
var message = new UserMessage(user);
NetworkClient.Send(message);
}
}
public struct UserMessage: NetworkMessage
{
public string Name;
public int Coins;
public int Id;
public UserMessage(User u)
{
Name = u.UserName;
Coins = u.Coins;
Id = u.Id;
}
}
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;
}
}
So I want to make some inventory system for my game, and I found some issue when collecting the item, what I want here matching the index Inventory_UI system exactly the same as currentIndex on the collected item, then display it on Inventory_UI system, let say I pickUp some item with the currentIndex = 1 so on Inventory_UI system index=1 too and so on. this happening when inventory description too so the id is same as itemIndex picked up.
so here the the script:
ItemManager( this for information of item ):
[System.Serializable]
public class theItems
{
public string Name;
public GameObject[] allCurrentPrefabs;
public int numberOfIndex;
public AudioClip[] allSound;
public string[] terjemahannya;
public string[] latinnya;
}
public class _ItemManager : MonoBehaviour
{
public static _ItemManager instance;
private void Awake()
{
instance = this;
}
public List<theItems> items;
[Header("SurahApa")]
public int Surah;
[Header("SoundStuff")]
public AudioSource aSource;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void PlaySurah(int surahnya, int ayatnya)
{
aSource.clip = items[surahnya].allSurahSound[ayatnya];
aSource.Play();
}
}
CollectibleItem ( this attach to each item )
public static _CollectibleAyat instance;
private void Awake()
{
instance = this;
}
public enum InteractionType
{
none, pickUp, Examine
}
public InteractionType interactType;
public int currentIndex;
public string terjemahannya;
public string latinnya;
public GameObject allCurrentPrefabs;
public UnityEvent customevent;
public void Reset()
{
GetComponent<Collider2D>().isTrigger = true;
}
public void interact()
{
switch (interactType)
{
//case InteractionType.none:
// Debug.Log("None");
// break;
case InteractionType.Examine:
_InteractSystem.instance.Examine(this);
Debug.Log("Examine");
break;
case InteractionType.pickUp:
// Add the object to the pickUpItems List
// Delete the Object
_InventorySystem.instance.PickUpItem(gameObject);
gameObject.SetActive(false);
Debug.Log("PickingUp");
break;
default:
Debug.Log("Null Item");
break;
}
//Invoke (Call) the custom Event(s)
customevent.Invoke();
}
This InventorySystem( when item pickup)
public static _InventorySystem instance;
private void Awake()
{
instance = this;
}
[Header("GeneralFields")]
public List<GameObject> items = new List<GameObject>();
public bool isOpen;
public int ayah;
[Header("UI Items Section")]
public GameObject UI_InventoryWindow;
public Image[] item_Images;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
ToggleInventory();
}
}
public void ToggleInventory()
{
isOpen = !isOpen;
UI_InventoryWindow.SetActive(isOpen);
}
public void PickUpItem(GameObject item)
{
items.Add(item);
Update_UI();
}
public void Update_UI()
{
HideAll();
for (int i = 0; i < items.Count; i++)
{
item_Images[i].sprite = items[i].GetComponent<SpriteRenderer>().sprite;
item_Images[i].gameObject.SetActive(true);
}
}
public void HideAll()
{
foreach (var i in item_Images)
{
i.gameObject.SetActive(false);
}
}
//SampeSini
public void ShowDescription(int id)
{
}
public void HideDescription()
{
}
InteractSystem ( this is for interact and storing collectibleItem system)
public static _InteractSystem instance;
private void Awake()
{
instance = this;
}
public Transform detectionPoint;
public const float detectionRadius = .2f;
public LayerMask detectionLayer;
public GameObject detectedObject;
public GameObject examinePanel;
private void Update()
{
if (DetectedObject())
{
if (PickUpInput())
{
detectedObject.GetComponent<_CollectibleAyat>().interactType = _CollectibleAyat.InteractionType.pickUp;
detectedObject.GetComponent<_CollectibleAyat>().interact();
_UIManager.instance.BackToGameFromExamine();
}
if (ExamineInput())
{
detectedObject.GetComponent<_CollectibleAyat>().interactType = _CollectibleAyat.InteractionType.Examine;
detectedObject.GetComponent<_CollectibleAyat>().interact();
}
}
}
bool PickUpInput()
{
return CrossPlatformInputManager.GetButtonDown("Fire1");
}
bool ExamineInput()
{
return CrossPlatformInputManager.GetButtonDown("Fire2");
}
bool DetectedObject()
{
Collider2D obj = Physics2D.OverlapCircle(detectionPoint.position, detectionRadius, detectionLayer);
if (obj == null)
{
detectedObject = null;
return false;
}
else
{
detectedObject = obj.gameObject;
return true;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.green;
Gizmos.DrawSphere(detectionPoint.position, detectionRadius);
}
public void Examine(_CollectibleAyat items)
{
examinePanel.SetActive(true);
items.terjemahannya = _QuranManager.instance.quran[_QuranManager.instance.Surah].terjemahannya[items.currentAyah].ToString();
items.latinnya = _QuranManager.instance.quran[_QuranManager.instance.Surah].latinnya[items.currentAyah].ToString();
items.allCurrentSurahPrefabs = _QuranManager.instance.quran[_QuranManager.instance.Surah].allCurrentSurahPrefabs[items.currentAyah];
var go = Instantiate(items.allCurrentSurahPrefabs, _UIManager.instance.instantiatePosition.position,Quaternion.identity);
go.transform.SetParent(_UIManager.instance.instantiatePosition.transform);
_UIManager.instance.terjemahanText.text = items.terjemahannya;
_UIManager.instance.latinText.text = items.latinnya;
}
Here is the Preview :
2.
note: on the ShowDescription(int id) i want to show item information that same as I picked up I have mentioned at first above.
I am making a multiplayer game and I am at the MenuScene where I make the choose room - on one panel and create room - other panel . It works to create a room , but when I press to show the panel with "ChooseRoom" it doesn't appear anything. here is the script that I use.So it doesn't appear the prefab that I made with the RoomListing1(text)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonReferences : MonoBehaviour
{
[SerializeField]
private MasterManager _masterManager;
}
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomListingsMenu : MonoBehaviourPunCallbacks
{
[SerializeField]
private Transform _content;
[SerializeField]
private RoomListing _roomListing;
private List<RoomListing> _listings = new List<RoomListing>();
private RoomsCanvases _roomsCanvases;
public void FirstInitialize(RoomsCanvases canvases)
{
_roomsCanvases = canvases;
}
public override void OnJoinedRoom()
{
_roomsCanvases.CurrentRoomCanvas.Show();
// _content.DestroyChildren();
_listings.Clear();
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
foreach (RoomInfo info in roomList)
{
//Removed from rooms list.
if (info.RemovedFromList)
{
int index = _listings.FindIndex(x => x.RoomInfo.Name == info.Name);
if (index != -1)
{
Destroy(_listings[index].gameObject);
_listings.RemoveAt(index);
}
}
//Added to rooms list.
else
{
int index = _listings.FindIndex(x => x.RoomInfo.Name == info.Name);
if (index == -1)
{
RoomListing listing = Instantiate(_roomListing, _content);
if (listing != null)
{
listing.SetRoomInfo(info);
_listings.Add(listing);
}
}
else
{
//Modify listing here.
//_listings[index].dowhatever.
}
}
}
}
}
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RoomListing : MonoBehaviour
{
[SerializeField]
private Text _text;
public RoomInfo RoomInfo { get; private set; }
public void SetRoomInfo(RoomInfo roomInfo)
{
RoomInfo = roomInfo;
_text.text = roomInfo.MaxPlayers + ", " + roomInfo.Name;
}
public void OnClick_Button()
{
PhotonNetwork.JoinRoom(RoomInfo.Name);
}
}
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestConnect : MonoBehaviourPunCallbacks
{
private void Start()
{
Debug.Log("Connecting to Photon...", this);
AuthenticationValues authValues = new AuthenticationValues("0");
PhotonNetwork.AuthValues = authValues;
PhotonNetwork.SendRate = 20; //20.
PhotonNetwork.SerializationRate = 5; //10.
PhotonNetwork.AutomaticallySyncScene = true;
PhotonNetwork.NickName = MasterManager.GameSettings.NickName;
PhotonNetwork.GameVersion = MasterManager.GameSettings.GameVersion;
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to Photon.", this);
Debug.Log("My nickname is " + PhotonNetwork.LocalPlayer.NickName, this);
if (!PhotonNetwork.InLobby)
PhotonNetwork.JoinLobby();
}
public override void OnDisconnected(DisconnectCause cause)
{
Debug.Log("Failed to connect to Photon: " + cause.ToString(), this);
}
public override void OnJoinedLobby()
{
print("Joined lobby");
PhotonNetwork.FindFriends(new string[] { "1" });
}
public override void OnFriendListUpdate(List<FriendInfo> friendList)
{
base.OnFriendListUpdate(friendList);
foreach (FriendInfo info in friendList)
{
Debug.Log("Friend info received " + info.UserId + " is online? " + info.IsOnline);
}
}
}