Photonview.owner.nickname not working properly for Clients - unity3d

I'm working on photon game where I have to show the player name over their everything is working fine but there's an issue , when you create a room and join it , the host name is properly visible to everyone but when it comes to the client Client name is some random numbers even though client is also setting their user name before joining the room , here's my code which is handling the naming system
public void JoinRoom()
{
connectButton.interactable = false;
PhotonNetwork.NickName = userId.text;
PhotonNetwork.JoinRoom("Basic");
}

Try this
PhotonView view;
void Start()
{
view = GetComponent<PhotonView>();
}
void JoinRoom()
{
if(view.IsMine)
{
userId.text = PhotonNetwork.NickName;
}else
{
userId..text = view.Owner.NickName;
}
}

Related

Photon creating new room instead of connecting to already existing one?

When I create a build of the game, everything works normally. However, when the second player tries to connect to the room with the name, it says that the room does not exist and if I create a room with the first rooms name it gets created instead of saying "room already exists".
I thought it could be a region problem, but in PhotonServerSettings, the "Fixed Region" is set to "eu", "Use Name Server" checked on, and "Dev Region" set to null (left it empty). In the build settings I set "development build" to false.
I don't understand why the two games would not be in the same region based on what I mentioned before?
Picture of the PhotonServerSettings
This is the code for creating/joining a room:
public void CreateRoom()
{
if (string.IsNullOrEmpty(CreateInputField.text))
{
return;
}
PhotonNetwork.CreateRoom(CreateInputField.text);
}
public void JoinRoom()
{
if (string.IsNullOrEmpty(JoinInputField.text))
{
return;
}
PhotonNetwork.JoinRoom(JoinInputField.text);
}
public override void OnJoinedRoom()
{
PhotonNetwork.LoadLevel("Game");
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
failText.text = message;
}
public override void OnJoinRoomFailed(short returnCode, string message)
{
failText.text = message;
}
}
(for some reason I cant put the entire script but these are the important parts)

Unity & PhotonEngine. After scene reaload Joining to Lobby, CreateRoom and JoinRandom functions called repeatedly

I ran into a problem in the last step of a test project using Photon Network. When you first connect and join the room, everything goes without errors. However, after completing the match, exiting the room, and using LoadScene(), errors appear:
JoinLobby operation (229) not called because client is not connected or not yet ready, client state: JoiningLob <- in OnConnectedToMaster()
Through experience, I realized that the ConnectUsingSettings() methods and other Photon methods are called multiple times. But the connection to the lobby happens and I can create a room, but I immediately encounter MissingReferenceException errors.
I've seen a solution from guys who ran into this very same problem. The problems arose because of the events. Wherever this could happen, I unsubscribed from the events, but that doesn't help. What else can cause such problems, because I obviously missed something that prevents me from completely closing the scene during the transition?
Sorry for my language, used Google Translate
Code:
LobbyManager.cs
private void StartConnect()
{
PhotonNetwork.NickName = master.GameSettings.NickName;
PhotonNetwork.GameVersion = master.GameSettings.NickName;
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.AutomaticallySyncScene = true;
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to server");
if(!PhotonNetwork.InLobby) PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
onConnected.Invoke();//This use for show UIElements on Canvas
}
JoinRandomRoom class
public void OnClick_JoinRandomRoom()
{
if (!PhotonNetwork.IsConnected) return;
if (GameModeGlobalData.SelectedGameMode != null)
{
SetRoomOptions();
PhotonNetwork.JoinRandomRoom(expectedRoomProperties, GameModeGlobalData.SelectedGameMode.MaxPlayers);
}
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
Debug.Log("Join random failed: " + message + ". Room will be created...");
_createRoomMenu.CreateAndJoinRoom();
}
public void SetRoomOptions()
{
expectedRoomProperties[RoomData.GAME_MODE] = GameModeGlobalData.SelectedGameMode.GameModeName;
}
private void OnDisable()
{
ShowPanels.RemoveAllListeners();
}
And CreateRoom.cs
private ExitGames.Client.Photon.Hashtable _roomCustomProperties = new ExitGames.Client.Photon.Hashtable();
public void CreateAndJoinRoom()
{
if (!PhotonNetwork.IsConnected) return;
if (GameModeGlobalData.SelectedGameMode != null)
{
RoomOptions roomOptions = GetCustomRoomOptions();
roomOptions.CleanupCacheOnLeave = true;
PhotonNetwork.CreateRoom(randomRoomName, roomOptions);
}
}
public RoomOptions GetCustomRoomOptions()
{
RoomOptions options = new RoomOptions();
options.MaxPlayers = _maxPlayer;
options.IsOpen = true;
options.IsVisible = true;
string[] roomProperties = new string[]{ RoomData.GAME_MODE };
_roomCustomProperties[RoomData.GAME_MODE] = GameModeGlobalData.SelectedGameMode.GameModeName;
options.CustomRoomPropertiesForLobby = roomProperties;
options.CustomRoomProperties = _roomCustomProperties;
return options;
}
The project has grown, and I blame myself for not testing it at the very beginning. Didn't think there would be problems at this stage
Sorry for this post. Its resolved. For those who may encounter this in the future, in addition to unsubscribing from events, check all classes that inherit from MonoBehaviourPunCallbacks for overridden OnDisable() methods.
Like this:
public override void OnDisable()
{
base.OnDisable();
}
This in turn will call the
PhotonNetwork.RemoveCallbackTarget(this);
Also, from the documentation:
Do not add new MonoBehaviour.OnEnable or MonoBehaviour.OnDisable. Instead, you should override those and call base.OnEnable and base.OnDisable.
I forgot about it and used MonoBehaviour.OnDisable.

Simple sending data between client/server

I am trying to send data on a simple multiplayer game, using Var1 and Var2 in this example. Var1 should sent and be stored as Var2 in the other user's instance.
The code I have sort of works, except I think the server is sending data to itself and overriding the data it receives, because if I load the client and initialize/send data, the server sees it. Then if I go to the server and initialize/send data, the client sees it. But if I go back to the client and send data, the server no longer sees it. It's like the server is acting as both a client and a server. Am I doing something wrong somewhere?
public class mouseController : NetworkBehaviour
{
GameLoop g;
void Start()
{
GameObject thePlayer = GameObject.Find("Main Camera");
g = thePlayer.GetComponent<GameLoop>();
}
void Update()
{
if (!isLocalPlayer)
{
return;
}
if (isServer)
{
if (g.var1 > 0)
{
Rpcsenddata(g.var1);
}
}
else
{
if (g.var1 > 0)
{
Cmdsenddata(g.var1);
}
}
}
[Command]
void Cmdsenddata(int i)
{
g.var2 = i;
}
[ClientRpc]
public void Rpcsenddata(int i)
{
g.var2 = i;
}
}
https://gyazo.com/b77e2ce35ec5f4d47147894c9430da03
(the data being sent is the card selected by your opponent. The server is the window on the right)
I think I fixed it by adding a !isLocalPlayer check
[ClientRpc]
public void Rpcsenddata(int i)
{
if (!isLocalPlayer) {
g.ehandSelected = i;
}
}

Authority with UNET client

I need to modify a non-player object. I am able to do it but for some reasons, I get warning:
Trying to send command for object without authority.
UnityEngine.Networking.NetworkBehaviour:SendCommandInternal(NetworkWriter, Int32, String)
ModelControl:CallCmdSetCube()
ModelControl:Update() (at Assets/Scripts/ModelControl.cs:21)
I have gone through the unity docs and the various answers but the weird part is that it does work but I wish to prevent the warning.
First there is a Manager object that creates the neutral object. This happens on the host.
public class ObjectControl : NetworkBehaviour
{
public GameObject cube;
public override void OnStartServer()
{
if (GameObject.Find("Cube") != null) { return; }
GameObject cubeInstance = (GameObject)Instantiate(this.cube,
new Vector3(0f, 0f, 5f), Quaternion.identity);
cubeInstance.name = "Cube";
NetworkServer.Spawn(cubeInstance);
}
}
Then each player has the following:
private void CmdSetCube()
{
GameObject cube = GameObject.Find("Cube"); // This is the neutral object
if (cube != null)
{
NetworkIdentity ni =cube.GetComponent<NetworkIdentity>();
ni.AssignClientAuthority(connectionToClient);
RpcPaint(cube, new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)));
ni.RemoveClientAuthority(connectionToClient);
}
}
[ClientRpc]
void RpcPaint(GameObject obj, Color col)
{
obj.GetComponent<Renderer>().material.color = col;
}
The host does not trigger the warning. Only the remote clients gets the warning. When I have many clients, I can see in the editor console that it will print as many times as there are clients.
But again, it does actually work, I can see the new data being propagated to all sessions but I am expecting something to go down later on.
So the issue came from the Update method:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
CmdSetCube();
}
}
The problem here being that all instances of that script will run the code while only one is really getting authority.
Solution:
void Update()
{
if (this.isLocalPlayer == false) { return; }
if (Input.GetKeyDown(KeyCode.Space))
{
CmdSetCube();
}
}
Add the line to make sure this is the local player calling.

How can i make remember me check box with unity?

I made an app that has a login form which gets the data from a SQL database on a server , i want to add a remember me check box so the user can automatically login , how can i do this or how can i save a data to text file then retrieve it back ?
thanks
unity, to addition to writing to a file, also provides local storing in PlayerPrefs, which work for all platforms.
Please read more about it here
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
You can store login information there and check it afterward to see if player has login credentials.
This script will create txt file in your project folder and write to it single row with login string. In order to use this you have to put this scrip anywhere you like then drag in editor your INPUT FIELD and toggle. Finaly assign OnClick event on your login button to execute loginClick() method.
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class InputFieldTest : MonoBehaviour {
//reference for InputField, needs to be assigned in editor
public InputField login;
string loginText;
//reference for Toggle, needs to be assigned in editor
public Toggle rememberToggle;
bool remeberIsOn;
// Use this for initialization
void Start ()
{
loginText = "";
FindLogin();
}
public void FindLogin()
{
if (File.Exists("userSetting.txt"))
{
using (TextReader reader = File.OpenText("userSetting.txt"))
{
string str;
if ((str = reader.ReadLine()) != null) login.text = str;
}
//Debug.Log(loginText);
}
}
public void remember()
{
using (TextWriter writer = File.CreateText("userSetting.txt"))
{
writer.WriteLine(login.text);
}
}
public void loginClick()
{
remeberIsOn = rememberToggle.isOn;
loginText = login.text;
if (remeberIsOn)
{
remember();
}
else
{
using (TextWriter writer = File.CreateText("userSetting.txt"))
{
writer.WriteLine("");
}
}
}
}