I am learning about Networking in Unity. I am confused on how can I send a message or event from client to server. I have these script already that successfully connect my client to server.
This is my server script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ServerNetwork : MonoBehaviour {
void Start()
{
SetupServer();
}
// Create a server and listen on a port
public void SetupServer()
{
NetworkServer.Listen(4444);
NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnected);
Debug.Log("Server is running");
}
void OnClientConnected(NetworkMessage netMsg)
{
Debug.Log("Client connected");
Debug.Log(netMsg.msgType);
}
}
This is my client Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ClientNetwork : MonoBehaviour {
NetworkClient myClient;
public bool isClientConnected = false;
void Start()
{
SetupClient();
}
// Create a client and connect to the server port
public void SetupClient()
{
myClient = new NetworkClient();
myClient.RegisterHandler(MsgType.Connect, OnConnected);
myClient.Connect("127.0.0.1", 4444);
isClientConnected = true;
}
// client function
public void OnConnected(NetworkMessage netMsg)
{
Debug.Log("Connected to server");
}
}
The Server Script is attached to "NetworkManager" Object on ServerScene
The Client Script is attached to "NetworkManager" Object on ClientScene
I have build ClientScene alone to run as a client, and running ServerScene inside editor
With these script, I can already connect the client into the server. From this, how can I communicate from client to server ?
the purpose here is to send real time score into the server from client every second.
Thank You
You have to use [SyncVars] Attribute. In short what it does is it synchronize a variable from client to the server. Here is a simple example from Unity3d Documentation.
[SyncVar]
int health;
public void TakeDamage(int amount)
{
if (!isServer)
return;
health -= amount;
}
another way to do this is by using custom WebSocket implementation for Unity3D. There a few very good ones in GitHub.Also please take a look at the documentation Unity3d
Related
- error message
After completing the bullet script operation, I tried to insert the script into Bullet Sprite in 2D Object format, but an error was displayed and the insertion was not possible. I tried turning off and on the editor because I thought it was a bug because I had the same file name and class name, but it didn't work. Do you happen to know about this problem? The editor version is 2021.3.11f1.
Bullet Script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class Bullet : MonoBehaviour
{
[SerializeField]
private float speed = 10f;
private IObjectPool<Bullet> pool;
void Update()
{
transform.Translate(Vector2.up);
}
public void SetPool(IObjectPool<Bullet> bulletPool)
{
Launcher.Instance.bulletPool = pool;
}
private void OnBecameInvisible()
{
Launcher.Instance.bulletPool.Release(this);
}
}
I turned off and on the editor and changed the class name because I thought it was different.
i am trying to make a multiplayer game by following a tutorial but i dont know why when i check from which is wrong i'm using photon free i also looked at the other forum but i can't solve
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class Launcher : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
void Start()
{
Debug.Log("Connecting to Master");
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to Master");
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
Debug.Log("Joined Lobby");
}
// Update is called once per frame
void Update()
{
}
}
I'm trying to synchronize text in a unit between players, but I'm getting an error.
I just need to sync the text
[1]: https://i.stack.imgur.com/0l98U.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using UnityEngine.UIElements;
public class Sync : MonoBehaviourPunCallbacks
{
private PhotonView view;
public Text textGame;
public Text copied;
void Start()
{
view = GetComponent<PhotonView>();
}
public void sync()
{
if(view.IsMine)
view.RPC("ViewAll", RpcTarget.AllBuffered, textGame.text);
}
[PunRPC]
public void ViewAll(string tG)
{
tG = copied.text;
Debug.Log(tG);
}
}```
пппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппппп
The error is telling you that the "view" variable has not been assigned and is therefore null.
To assign it you can make that field public, and in the inspector you
assign the photonView you want, I guess that of the player.
Alternatively you can assign "view" not from the inspector but in a
Start() or Awake() method. If the photonView you want to associate is
on the same GameObject as the script, you can write like this:
void Awake()
{
view = GetComponent();
}
However, the easiest answer is to replace "view" with "photonView".
It will have the same result as the solutions described above, but it will be very simple.
enter code here
public void sync()
{
if(photonView.IsMine)
view.RPC("ViewAll", RpcTarget.AllBuffered, textGame.text);
}
I have not directly given you the simple slogan to make you fully understand the problem and to help you solve it.
I am relatively new to Unity and am currently trying to build an multi-user app on Hololens. Currently, I am just trying to get two Hololens to connect over LAN using Unet. When I use one of my Hololens to host the server, my laptop can connect to it during play mode in the Unity editor. However, when I try to use my other Hololens to connect to it, it does not work and I am not sure why. Does anyone else have this problem? And if so, how do you fix it?
Thanks in advance.
Edit: some code
Here's the code for network manager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;
public class NetworkManager_Custom : NetworkManager
{
public void StartupHost()
{
setPort();
NetworkManager.singleton.StartHost();
}
public void JoinGame()
{
SetIpAddress();
setPort();
NetworkManager.singleton.StartClient();
}
private void SetIpAddress()
{
string Address = "192.168.2.80";
NetworkManager.singleton.networkAddress = Address;
}
private void setPort()
{
NetworkManager.singleton.networkPort = 9001;
}
}
Here's the code for the start-server button
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using UnityEngine.Networking;
public class ok : NetworkBehaviour, IFocusable, IInputClickHandler
{
bool hasFocus;
public NetworkManager_Custom manager;
public void OnFocusEnter()
{
hasFocus = true;
}
public void OnFocusExit()
{
hasFocus = false;
}
public void OnInputClicked(InputClickedEventData eventData)
{
manager.StartupHost();
}
}
Here's the code for joining server as client
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
public class aegf : NetworkBehaviour, IFocusable, IInputClickHandler
{
bool hasFocus;
public NetworkManager_Custom manager;
public void OnFocusEnter()
{
hasFocus = true;
}
public void OnFocusExit()
{
hasFocus = false;
}
public void OnInputClicked(InputClickedEventData eventData)
{
manager.JoinGame();
}
}
It's worth double-checking the capabilties that you've set. Ensure all three of these are selected:
InternetClient
InternetClientServer
PrivateNetworkClientServer
Ref: https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/appxmanifestschema/element-capability
I´m new to Networking and can´t find the problem on my self.
I made a matchmaking system for my game and it worked well.
But after some changes in my Game it stopped working.
It should create a room if no room is there. Else join a random room.
But it always creates a new room. no errors etc.
here are the scripts that should do the work.
Edit:
broke it down to this script:
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PhotonLobby2 : MonoBehaviourPunCallbacks
{
public static PhotonLobby2 lobby;
public GameObject battlebutton;
private void Awake()
{
lobby = this; // create singleton
}
void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
Debug.Log("connected to masterserver");
PhotonNetwork.AutomaticallySyncScene = true;
battlebutton.SetActive(true);
}
public void OnBattleButtonClicked()
{
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
Debug.Log(message + returnCode);
Debug.Log(" failed to join random game");
CreateRoom();
}
void CreateRoom()
{
PhotonNetwork.CreateRoom("Room");
}
public override void OnCreatedRoom()
{
Debug.Log("Created Room");
base.OnCreatedRoom();
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
Debug.Log("Entered");
base.OnPlayerEnteredRoom(newPlayer);
}
}
Debug says: No match found32760
It is because the two players join matches in different regions... you can force this in the photon server settings Fill in Dev region and Fixed region with one particular server region that has better ping for you. Make the property Use sure name serve is also checked
I resolved this issue by checking the room properties which first player creates.
There is a variable of Room named "IsOpen". If it is false then second player cannot join the same room. I just set it to true and now its perfectly joining the same room.