#archived-networking
1 messages ยท Page 21 of 1
this might help https://stackoverflow.com/questions/72661549/unity-mirror-is-there-a-way-to-keep-my-camera-independent-from-the-player-ob
thanks :)
I was wondering..
I made a host-client connection. So I was the host on my PC in UK and the other person was a friend who connected from Romania. But in the unity log I saw that the IP address of the connection was south korean. I was genuinely expecting my IP address there, as I thought that's what hosting a session meant. Does it go thruogh a proxy server?
You should be able to
i'm idiot i was calling other var than the one correct
ty btw
Are you using the Relay service? Or a VPN could do that as well
Yes Using Lobby with Relay
All connections will go through the relay server. When you create the relay you should see it ping all the regions for the best one. It's kinda weird that it went through Korea and not one of the EU servers
Ye, my friend said it went so far west it ended up south : D
The connection was pretty stable though
anyone please?
are you saying that clientBarrel there is the wrong one?
what do you mean
You said that the muzzle flash is being instantiated on the wrong player
hello, I recently switch to dissonance and i am trying to get proximity chat to work. Normally I would ask in the Dissonance discord but the support person is on vacation until next week. I have my player setup with the MirrorIgnorancePlayer attached for tracking and then i have a DissonanceSetup with a prox broadcast and prox receiever in the GridProximity room. When I join a game with two people I hear nothing. Is there anything im missing here?
Sorry, I was also wondering, if these connections go through relay server, does that mean I dont have to worry about the host having a bad connection?
Lets say my internet wasn't the best, so others wont have to deal with that issue who connect to the session i created?
Sorry, just trying to understand if the session I created exists on my end, or on a unity relay server that all connections go through?
The host is still running the game so your connection still matters
hey, after i finish the match, how do i delete the lobby or exit it?
If you don't send a heartbeat the lobby should delete itself. There is also a DeleteLobby() you can call as the host
i made a function for the host to kick the players
my player is controlling the other player i am using NGO can any tell me how i can fix this and i can't move the camera horizontaly using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerMovement : NetworkBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jump = 1f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jump * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
You need to check for IsOwner or IsLocalPlayer at that start of your Update()
Would hosting a dedicated server for my game on Linux pose any weird problems? Am I better of just sticking to windows?
The purpose is to use it for testing the netcode
I'm stumped. This code works perfectly for clients but the host gets a Null Exception when trying to starthost(). What could be null for the host and not the client?????
Error:
Does Netcode for GameObjects have a limit of concurrent connected users? https://docs-multiplayer.unity3d.com/netcode/current/about/
Overview of Unity's Netcode for GameObjects for your multiplayer networking needs.
Should be fine
Unity's own server hosting service is Linux only at the moment
It's just that many games are not linux supported but I imagine that has little to do with the code and more something to do with graphics and such
Nothing wrong with any of this code. Problem could be in the scene or on your player object when it spawns in
It does not. The only are limits on Lobby and Relay services which I believe are 100 players per session.
Went through each of the objects in the scene. Turns out its because there is child of a networkobject that had a networkobject on it. I guess Unity does not like that
Yeah. Network object has to be on the root object when spawned. It's possibe to reparent them after but it's a pain in the ass so I avoid doing it
Thank you
do you have any idea how could i check if the player quits(closes the app on the phone) ?
like if he is still in game or he quit?
There is an OnClientDisconnect event you can subscribe to
https://docs-multiplayer.unity3d.com/netcode/current/components/networkmanager/#connection-notification-manager-example
The NetworkManager is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
cloudcode dosen't have anything like this?/
cloud code doesn't have a connection to disconnect from
lobbies?
Lobby is just a web service there is no persistent connection there either. That's why it needs a heartbeat to keep a lobby alive
only when the host waits for someone to join.. right?
even then. the host is requesting that data from the Lobby service. there is no real time connection
um.. or i made something wrong or idk because i don't use any heartbeat yet and i can make requests..
After how many minutes does the lobby auto delete?
after 30 seconds it goes inactive and cant be found in a query. it gets marked for deletion after an hour.
https://docs.unity.com/ugs/en-us/manual/lobby/manual/heartbeat-a-lobby
Ok so I've got a big issue i can't figure out so im trying to use unitys new gaming services for dedicated server hosting and in all the references I've seen there's supposed to be a networkmanager component how do I get that and if you know why don't I have it
I'm using unity 2023.3.13
GetDamageClientRpc(damage, new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = new List<ulong> { 1 } } });
public void GetDamageClientRpc(int Damage, ClientRpcParams clientRpcParams)
{
basicHealth.healthParts[healthPartsNumber].Value -= Damage;
}```
why it doesn't work, it not synchronizes, it works in CodeMonkey
Hello, not sure this is the right place to post but here it goes.
I want my game to use the following Steam features:
- When a game is hosted by a friend, you can right click -> join to join their game
- When a game is hosted by a friend, and you want to join it, you can see the game being hosted in a list, without having to manually enter IP's.
Which parts of the Steamworks API would I need to use to achieve this?
Thanks a lot!
Are you using Netcode for GameObjects? That's where the network manager comes from. But you can use any network library with Multiplay if you need to
Only the host/server can call clientrpcs. Other clients will have to call a serverRPC that would call a clientRPC
I'm pretty sure Steamworks has a lobby service you can use
I tried that it still didn't pop up a network manager
You installed the Netcode package from the package manager and are not seeing the network manager script?
Hello, I was wondering if this relay usage is normal now what I am working on is a 3D tank game and in all of this data there was maximum of 2 players at a time
I am asking, beacuse whenever I move the client tank the lobby is timed out. This does not happen when I move the host
My project was corrupted i made a new project and the network manager popped up instantly
Hello, I am using FizzySteamworks and Mirror to allow players to connect with one another via steam. Currently the only way I have been able to test my game is by building the project, downloading the build onto my other laptop with a different steam account and then joining the host account via steam. Is there a way I can test multiple players on the same computer? Maybe with two unity editors or something?
There is this tool you can use: https://github.com/VeriorPies/ParrelSync#installation to open two unity editors. You wont be able to test with steam lobbys but I just disabled that for testing purposes and use Mirrors default NetworkManager with KcpTransport to test on local. When I actually want to test with other players I will use my own CustomNetworkManager with FizzySteamworks ๐
Stream only allows one account per PC. I guess you could use a virtual machine or something
how to call methods from client to client???
I have a code that lays out this damage dealing
{
health.GetDamageServerRpc(damage, new ServerRpcParams());
}
if (health.statusStorage.HostStatus()) //if host
{
health.GetDamageClientRpc(damage, new ClientRpcParams());
}```
the code that accepts the call
[ServerRpc(RequireOwnership = false)]
public void GetDamageServerRpc(int Damage, ServerRpcParams ServerRpcParams)
{
basicHealth.healthParts[healthPartsNumber].Value -= Damage;
}
[ClientRpc]
public void GetDamageClientRpc(int Damage, ClientRpcParams ClientRpcParams)
{
basicHealth.healthParts[healthPartsNumber].Value -= Damage;
}```
It works fine if it's between host and client but client to client can't damage each other, how can I make it work?
I have such a method. And for testing purposes I call this method when I press "c" on the client side but on the server side this method is not triggered.
You can not. All messages must go through the server/host. So it would be a serverRPC that calls a clientRPC
I tried to call the rps server from the client to the next client, nothing happened
It didn't call the serverRPC?
I tried this, they both have to be clients, then ServerRpc should be called
but nothing happened.
If that serverRPC is not called then one of those ClientStatus() is returning false
In order to avoid too many methods in the Player object, I do not want to create a separate class but implement ServerRpc and ClientRpc messages in it. An issue arises because the ServerRpc message cannot be defined because there is no network object in this class. How can I solve this?
RPCs have to be on a network object. You could also use custom message handlers as well
I have a great problem and I don't understand why. I start my client from the editor and then I build and run the server. I send a request from the client with ServerRpc and spam my object with the server, and it views on both. Later, when I build and run both of these (client and server), it doesn't work.
What might break down after it's built?
Heyo!
Can someone tell me if it's possible to query the current lobby a user is in to get data?
You can use Lobby Events
https://docs.unity.com/ugs/en-us/manual/lobby/manual/lobby-events
Hello, how would I go about fetching all the lobbies created by my steam friends, using the Steamworks API?
Is there anything more efficient then getting a list of friends who currently play the game, fetching all lobbies, and matching them?
Can someone tell my why changing the username is extremely stricted?
The rate limiting on it is like.. 3 times per minute or so?
If you mean lobby data then it's 5 requests every 5 seconds
https://docs.unity.com/ugs/en-us/manual/lobby/manual/rate-limits
No, authentication, set player name
Looks like for authentication it's 10 requests per second
https://services.docs.unity.com/auth/v1/#section/Overview/Rate-Limits
Is the web api the same as in c#?
I assume so
The only thing I found was this: https://forum.unity.com/threads/player-name-management-rate-limit.1423980/
small but strong things that are not clearly documented 
Well that's annoyingly undocumented anywhere
its supposed to instantiate only for other players
and not for the one that shot
so if you shoot
instantiate the muzzle flash for every player
except from yourself
so this spawns it for everyone
including the player himself
which is not what i want
Add if(IsOwner) return; before that Instantiate()
like this?
omg it works
thank you so much
You can use the OnClientConnected callback
https://docs-multiplayer.unity3d.com/netcode/current/components/networkmanager/#connection-notification-manager-example
The NetworkManager is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
I have a setup where I have a "Spaceship" object, with a "PlayerGroup" and "ShipObject" parented under it. The PlayerGroup is the parent of players inside that Spaceship and ShipObject has a movement script for the ship on it. The ShipObject also has the following script attached:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayersFollowShip : MonoBehaviour
{
[SerializeField] private GameObject playerGroup;
void Start()
{
var spaceshipObject = transform.root.gameObject;
playerGroup = spaceshipObject.GetComponent<Spaceship>().playerGroup.gameObject;
}
void Update()
{
playerGroup.transform.position = transform.position;
playerGroup.transform.eulerAngles = transform.eulerAngles;
}
}`
When the host is in the ship and parented under the player group, when the ship is moved with the movement script, the host's player object stays in place correctly inside the spaceship, but when I do the same with a client it always physically lags behind the ship. Any ideas on how to fix this and make sure the client player object correctly stays inside the spaceship and doesn't lag behind it? (I can provide a video of the issue if this isn't clear enough)
Hey guys, how can I make something like different profiles for each player that allow me to save their data so when they rejoin a room created by someone they don't lose all their progress and they still have everything?
I want to save the data on the PC of the hoster so they can create a room and play for a bit, and then even if they stop playing and close the room the next day they can continue playing without having to restart.
wait im confused
so how would i use it
like if i have a seperate script
called LobbyManager
do i still make the OnPlayerJoin and OnPlayerLeave methods?
That depends on how you are doing your lobbies. If its after clients connect then you would use the Network Manager OnClientConnected/Disconnected callbacks. If you are using the Lobby Service then you would subscribe to lobby events
How to manually correctly spawn object as player object? Just simply start client and then instantiate player and use spawn as player object?
Only the server can spawn so you would either need to send a ServerRPC from the client after they connect, or just instantiate and spawn from the server when it get a OnClientConnected callback
Do you know why my startclient() is called 2 time in the code when i join a host and disconnect me right after
using System.Collections.Generic;
using UnityEngine;
using Steamworks;
using TMPro;
using Steamworks.Data;
using UnityEngine.UI;
using Unity.Netcode;
using Netcode.Transports.Facepunch;
using UnityEngine.SceneManagement;
public class SteamManager : MonoBehaviour
{
[SerializeField] private TMP_InputField LobbyIDInputField;
[SerializeField] private TextMeshProUGUI LobbyIDText;
[SerializeField] private GameObject MainMenu;
[SerializeField] private GameObject LobbyMenu;
void OnEnable()
{
SteamMatchmaking.OnLobbyCreated += LobbyCreated;
SteamMatchmaking.OnLobbyEntered += LobbyEntered;
SteamFriends.OnGameLobbyJoinRequested += GameLobbyJoinRequested;
}
void OnDisable()
{
SteamMatchmaking.OnLobbyCreated -= LobbyCreated;
SteamMatchmaking.OnLobbyEntered -= LobbyEntered;
SteamFriends.OnGameLobbyJoinRequested -= GameLobbyJoinRequested;
}
private async void GameLobbyJoinRequested(Lobby lobby, SteamId steamId)
{
await lobby.Join();
}
private void LobbyEntered(Lobby lobby)
{
LobbySaver.instance.currentLobby = lobby;
LobbyIDText.text = lobby.Id.ToString();
CheckUI();
if (NetworkManager.Singleton.IsHost) return;
NetworkManager.Singleton.StartClient();
NetworkManager.Singleton.gameObject.GetComponent<FacepunchTransport>().targetSteamId = lobby.Owner.Id;
}
private void LobbyCreated(Result result, Lobby lobby)
{
if (result == Result.OK)
{
lobby.SetPublic();
lobby.SetJoinable(true);
NetworkManager.Singleton.StartHost();
}
}
public async void HostLobby()
{
await SteamMatchmaking.CreateLobbyAsync(3);
}
public async void JoinLobbyWithID()
{
ulong ID;
if (!ulong.TryParse(LobbyIDInputField.text, out ID))
return;
Lobby [] lobbies = await SteamMatchmaking.LobbyList.WithSlotsAvailable(1).RequestAsync();
foreach(Lobby lobby in lobbies)
{
if(lobby.Id == ID)
{
await lobby.Join();
return;
}
}
}
public void CopyID()
{
TextEditor editor = new TextEditor();
editor.text = LobbyIDText.text;
editor.SelectAll();
editor.Copy();
}
public void LeaveLobby()
{
if (NetworkManager.Singleton.IsHost) return;
LobbySaver.instance.currentLobby?.Leave();
LobbySaver.instance.currentLobby = null;
NetworkManager.Singleton.Shutdown();
CheckUI();
}
private void CheckUI()
{
if (LobbySaver.instance.currentLobby == null)
{
MainMenu.SetActive(true);
LobbyMenu.SetActive(false);
}
else
{
MainMenu.SetActive(false);
LobbyMenu.SetActive(true);
}
}
public void StartGameServer()
{
if (!NetworkManager.Singleton.IsHost) return;
NetworkManager.Singleton.SceneManager.LoadScene("Game", LoadSceneMode.Single);
}
}
I'm having a hard time fully understanding Network variables vs RPCs. For example: I want a client to call a serverRPC and send a variable (say an int or bool) to the server. Is this the proper way? Or should I be using network variables and just use the RPC to do whatever action with the int/bool?
To add to this, what if I want the server to send to int/bool to all other clients? I was thinking client rpc. But may e network variables are just the way to go?
Appreciate any help!
Basically. Its RPCs for one off events. and Network Variables for data a late joining client might need
https://docs-multiplayer.unity3d.com/netcode/current/learn/rpcvnetvar/
Choosing the wrong data syncing mecanism can create bugs, generate too much bandwidth and add too much complexity to your code.
Got it thanks!
Hi, I want to impletement Stripe payment system into my unity WebGl app, how can i do that?
How do I respawn a player after death, does anyone have an example script?
you can instantiate the player again, you need to make sure that the player is a brefab
This is understandable, but if I do this, it is not considered a local player
I need help in connecting two unity applications together and sending photos from one app to another, it will be paid help. if someone is interested and capable to do so, please send me private message
I did not get what you mean
I have a condition that if the player is not local, then the camera and walking script are turned off so that it does not conflict with other players on the scene.
you can add another flag disfiguring local player, and make sure to turn it on for the camera and movement to work again
in Unity NGO this :
{
// This check is for clients that attempted to connect but failed.
// When this happens, the client will not have an entry within the m_TransportIdToClientIdMap or m_ClientIdToTransportIdMap lookup tables so we exit early and just return 0 to be used for the disconnect event.
if (!LocalClient.IsServer && !TransportIdToClientIdMap.ContainsKey(transportId))
{
return 0;
}
var clientId = TransportIdToClientId(transportId);
TransportIdToClientIdMap.Remove(transportId);
ClientIdToTransportIdMap.Remove(clientId);
return clientId;
}```
always return 0 when i try to connect to the host do you know why ?
How to make audio effects networked? Through RPCs? Unity NGO
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PickupSystem : NetworkBehaviour
{
public GameObject Hand;
public Camera playerCam;
public bool hasItem = false;
public void Update()
{
if (isLocalPlayer)
{
if (Input.GetMouseButtonDown(0) && !hasItem)
{
RaycastHit hit;
Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.CompareTag("Pickup"))
{
CmdPickup(hit.transform.gameObject, Hand.transform);
}
}
}
}
}
[Command]
void CmdPickup(GameObject go, Transform parent)
{
RpcPickup(go, parent);
}
[ClientRpc]
void RpcPickup(GameObject go, Transform parent)
{
go.transform.position = parent.position;
go.transform.rotation = parent.rotation;
go.transform.parent = parent;
}
}
I am using Unity Mirror. The code works well when I right click on an object with Pickup tag, it goes on the position of my Hand, the bool hasObject sets to true, but the object doesn't become child of Hand...
When to use UnityWebRequest Post? It seems put the url and data.What kind of data need this method and how does the server respond to it?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
This is interesting question. I use network animator and I have animation events inside some clips. Are they networked? (Animation event will be called on all clients)
Animation events will fire off locally when the animator hits those events in the animation
So if I want to hear another player footsteps then through server and client RPCs. Animation event will be fired locally and inside it I should call server RPC?
That shouldn't be necessary. The other player object should have an audio source that can play footsteps when it's walk animation fires those events
So having a network animator with events is enough for networked footsteps sound?
Technically not networked, but yes.
Thanks ๐
So other players will be able to hear your footsteps without RPCs. That's cool. @sharp axle?
Yep. The audio is played locally so it will be like any other sound from an audio source
Anyone know why this code randomly stops working?
public class ServerConnections : NetworkBehaviour
{
public int PlayerCount = 2; // Change to the number of players you expect to be in the game
private int ConnectedCount = 0; // Track the number of connected clients
private int RngSeed; // Rng seed shared by all clients
private void Start() {
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
}
private void OnClientConnected(ulong clientId) {
Debug.Log("OnClientConnected");
if (IsHost) {
RngSeed = Random.Range(-214748364, 214748364); // Max Int: 2147483647
}
ConnectedCount++;
if (ConnectedCount == PlayerCount) {
foreach (var client in NetworkManager.Singleton.ConnectedClientsList) {
var player = client.PlayerObject.GetComponent<Player>();
player.SetupPlayer_ClientRpc(RngSeed);
}
}
}
}
It was just working, I didn't change anything about the code, and now I can't connect. This has been happening on and off all day. I'm using the default settings in my Network Manager (UnityTransport). I run the game in my editor as a Host and I don't see the "OnClientConnected" debug message.
hey, does this code not exist anymore ? InvokeClientRpcOnEveryone();
Trying to write a function that allows any client to instantiate a network prefab. This is what I have
[ServerRpc]
public static GameObject InstantiatePrefabServerRPC(GameObject prefab, Vector3 pos, Quaternion rot, Transform parent)
{
return InstantiatePrefabClientRPC(prefab, pos, rot, parent);
}
[ClientRpc]
static GameObject InstantiatePrefabClientRPC(GameObject prefab, Vector3 pos, Quaternion rot, Transform parent)
{
GameObject spawnedObj = Instantiate(prefab, pos, rot, parent);
spawnedObj.GetComponent<NetworkObject>().Spawn();
return spawnedObj;
}
but i still get an exception in the clients logs saying only the server can spawn network objects, but I dont know why since its a serverrpc calling the client rpc
Because that spawn must be inside server rpc
And wait, you can have game object as RPC function?
What network solution are you using?
i thought so but i guess i never confirmed it
relay
like this?
[ServerRpc]
public static GameObject InstantiatePrefabServerRPC(GameObject prefab, Vector3 pos, Quaternion rot, Transform parent)
{
GameObject spawnedObj = Instantiate(prefab, pos, rot, parent);
spawnedObj.GetComponent<NetworkObject>().Spawn();
return spawnedObj;
}
You mean unity netcode for game objects
I thought you can only use voids with RPCs
Yep
looks like they can have return values
https://docs-multiplayer.unity3d.com/netcode/1.0.0/advanced-topics/message-system/deprecation-of-return-values/
Netcode for GameObjects (Netcode) supports RPC return values on convenience RPCs.
maybe not a GameObject tho, that could be the issue
That's the issue
damn
thats annoying
do you know of any better way to allow any client to instantiate a prefab
I do it through IDs
how so?
Let's say you want the server to spawn an apple ok?
You make a scriptable object with apples, bananas and grapes. Each has an id. Then you send to server which thing you want to spawn (by id) and server will spawn it from its own assigned scriptable object
@lavish canyon
U welcome ๐
if (teammateObject != null)
{
return teammateObject.gameObject;
}``` Is this a valid way to find a teammate?
Hey gang, my game is aiming to use a p2p Steam transport design where you can invite friends to your game and act as the Host. I don't care about cheating.
I was wondering how I could go about the following:
I want one central class that acts as the "ServerData", which contains information for everything and can sync it to everyone.
My issue is getting access to this ServerData class from the non-Host clients since it only exists on the Server. I know I can send an RPC to the Server to interact with the data, but I was wondering if there's a faster and more effective way. For example, this is how I'm doing it now but it's a pain to have to do this every time:
// Setup non-host clients
if (IsHost) { return; }
foreach (var spawn in NetworkManager.Singleton.SpawnManager.SpawnedObjectsList) {
if (spawn.gameObject.TryGetComponent(out ServerData sd)) {
sd.SetupClient_ServerRpc(OwnerClientId);
}
}
It'd be ideal if my clients could do something like this:
ServerData.Singleton.SetupClient_ServerRpc(OwnerClientId);
But since ServerData doesn't exist for them it's not possible. ^ Any ideas of how to achieve that? Sorry if this is a stupid question, I'm still trying to wrap my head around all of this.
i need to run the whole OnEnable after the network objects have been iniatilized
because the OnEnable runs before the network game objects are iniatilized
maybe i could just make the network iniatilize quicker here?
i could do this but i wanna do it it more simpler
or better
anyone?
I have on my Loginscene a NetworkManager, when I change scene all is working fine. When I retourn to default scene i have 2 NetworkManagers, why is he creating every time a new one on Startingscene ?
Network Manager get set to Do Not Destroy on Load
How can I easily access the player object (owner) of a network object in the client side?
I have a question related to Unity's netcode for gameobjects. I implemented a simple multiplayer host-client system but whenever I click on host it works perfectly fine until I make another instance as a client. Then the host's camera swithces to the client's, why is that? It has to do with camera ownership or something like that right?
This is my cameraHandle script:
For their own player object its NetworkManager.LocalClient.PlayerObject
If you need another client's player object, you could search the network objects for .IsPlayerObject
Unity will show the last active camera in the scene. You should be disabling the camera on the non local players'
I have a network object. In order to understand whether this network object is mine or the enemy's, I need to look at the side information of the player that my network object has, but I could not do it.
If you are checking a collision then you will need to check .IsOwner or OwnerClientId
But if there are 2 team(gruop A and Group B) and there are 4 color(red,blue,green,yellow)
Red and blur are gruop A , green and yelliw gruop B
Gruop A is enemy with gruop B
Gruop and color info are in playerObject
How i know color and grup info of network object
You can Get component whatever class you are storing that info in
This info in PlayerObject and server set to this network variable. I think i should use OnNetworkSpawn method. I am not sure
Setting a network Variable should be done in OnNetworkSpawn() or later
Can anyone help, when I play with one player, it spawns one zombie and waits until it's dead, as it's intended. But When I play with two or more , the wave system just skips and doesn't check if the zombies are dead. Also instead of only spawning one zombie, it spawns one zombie per player. I'm not sure if the RPC's are done correctly
https://paste.myst.rs/4kfq5k88
a powerful website for storing and sharing text and code snippets. completely free and open source.
Why is it that the first code works, but the second doesnt? (Of course the first code is not the outcome i'd want because it's not syncing clientwise.
I have a question related to Unity's netcode for gameobjects. I want to create a SpawnArea like known from RTS games like Steel Division where the user can set his initial start units. Each area is only visible for the specific client, should be server authoritative and allow later the server to check local avoidance when the client place his units. Actually I'm struggle what is the best approach to realize this. Using NetworkObjects for the SpawningAreas, or request the available areas via RPC from each client and rebuild the GameObject for this area? Or an other approach?
Quick question on CloudCode in relation to NetCode Entities. Are there available Admin methods available or would I just do standard API request? Iโm trying by to evaluate the features in general to build a very authoritative server to handle save states and other functionalities that might interact with CloudSave. Most things I see around are using standalone servers that are non unity based leveraging things like Node servers to invoke the functions.
I think the main one is authenticating for service account on server side to leverage UGS natively
How to find other player's object on client side? Currently I find all network FPS through find objects of type and then by id find it but that sounds terrible
Yes you would just use the regular API request to authenticate a service account or you should use the Multiplay server authentication
https://docs.unity.com/ugs/en-us/manual/cloud-code/manual/modules/how-to-guides/authentication
It really depends on how often you are searching for a player object. Use the Profiler to see if it's an actual problem. You could also have the players on spawn save themselves to a local dictionary then use that to look them up
One time at the beginning. To assign your teammates
How to do it with local dictionaries?
You would have like a dictionary<clientId,PlayerClass> Players. then in the player class OnNetworkSpawn () you would Players.Add(LocalclientId,this)
Thanks bro
In Unity Netcode for GameObjects I use Relay and Lobby to set up a match. On server side I have a list of MatchUsers wich holds any data from relay/lobby (guid, networkid, displayname ect.) to identify my players. Now I need for some set-ups the clientID which is handled by the NetworkManager, which doesn't know the other values. How can I create a relationship between those values in my MatchUser? One idea is to call NetworkManager.LocalClient.ClientID at LobbyOrchestrator when the user create or join a match, StartHost/StartClient has been invoked and use an RPC to expose this to any client to force an update of those data. But this looks a little bit hacky. Is there a better approach to get a link between clientID and NetworkID?
I will normally just slap a network variable on the player containing the PlayerID. Anyone who needs them can loop through all the players and save them to a list or dictionary
I think Iโll end up using that. I was thinking of having the server handle the save states as opposed to client side. Like in mmo scenarios where server just syncs ghost states to the client and have server retrieve and save progress. Using NetCode entities as server already so thinking of using cloudcode to interact with cloud save and then limit cloud save access to just service account. Thinking itโs probably best not to have client trigger cloud code in case of some sort of data manipulation client side on the player state
Hi guys, i got an error and i don't know what cause of it. I'm using Mirror and FizzySteamwork to make multiplayer game.
FizzySteamwork error
using System;
using UnityEngine;
namespace Assets.Scripts.Classes.Components
{
public class Side
{
public ColorEnum TeamColor { get; set; } = ColorEnum.Red;
public GroupEnum TeamGroup { get; set; } = GroupEnum.GroupA;
public Side()
{
}
public Side(GroupEnum group, ColorEnum color)
{
TeamGroup = group;
TeamColor = color;
}
}
}
I have side class and i want to use as networkvariable
NetworkVariable<Side> side = new ....
But i am getting error runtime
How i can
guys im using relay to make a multiplayer game i move the players in the host but it is laggy because of that what should i do?
should i move the player in the client?
Network variable can not be a class. Make Side a struct that implements inetworkserializable
Introduction
Aren't the complex examples here a class? structure?
those are both structs
Thank you man
I asked this before but I couldn't get a clear answer and couldn't find a solution myself.
var client = NetworkManager.Singleton.ConnectedClients[clientId];
var player = client.PlayerObject.GetComponent<Player>();
How to do a similar operation in the client? In order to understand whether a networkObject is a foe or a friend, The values of that object in the player class need to be access.
Summary: How do I access the owner PlayerObject(Owner) of a network object?
You can GetComponent<Player>() from the client no need for anything fancy. If you don't want to use GetObjectsByType<Player>(), then you could have the players save themselves to a local list or dictionary when they spawn in
Hey I'm having an issue with switching scenes in my multiplayer game, so im using multiplay, matchmaker, and netcode for gameobjects and im trying to make it so the player starts a client side connection than switches from the main menu scene to the game scene I've got the client side connection and the matchmaking set up but I can't figure out scene changes while connected using a button can someone plz assist me with this? A little more info when I use the traditional methods like networkmanager.scenemanager.Loadscene it says that only the server can change scenes but I figure there's got to be a way around this.
Once the client connects to the server, the client will automatically load the scene that server has loaded
So how do I get the server to load a scene automatically?
Automated client synchronization that occurs when a client is connected and approved.
All scenes loaded via NetworkSceneManager will be synchronized with clients during client synchronization
You can switch scenes according to the matchmaker payload.
Got it thanks
So having used netcode for game objects for a while now I can say that it is good. However I very much dislike having to write IsServer, IsClient etc etc all over my code. Is there a guide or a best practice on how to cleanly separate server and client code ?
I was having difficulty implementing the stateAuthority funtionality in Photon Fusion 1, for a VR network object while I was doing that I realized why isn't a lot of the things in fusion not automated and rather have to be done manually? or is there any easier plug and play method?
I think I couldn't explain my problem, it would be better if I explain it from the beginning. There is a Player class in the script inside my PlayerPreb. This class also contains team and group information. I send a request to the server from the client and I spawn network objects with spawnOwnerShip on the server side. So every networkObject has a Player, so it has a team and group. Then, on the client side, I need to access the owner's team and group information to understand whether a network object is a friend or a foe. However, I cannot access the PlayerObject of the owner of the networkObject on the client side.
You can use either compiler defines or assembly definition files to separate out the code. Honestly, I think it's more trouble than it's worth. You end up with double the amount of files with Client Player Movement and Server Player Movement classes and what not.
You can put a network variable<network object reference> of the player object in the Player class. You could also create a local dictionary<clientID,Player object> on each client and have the player object save itself to it when it spawns in
Yes I am well aware of these options. I was asking for general good principals in the design of the systems
I'm a solo dev and super lazy, so I err on the side of simplicity. It might not be best practice but having IsServer checks keeps things more organized in my mind.
I have not actually looked at the code but cant IsServer be in theory spoofed ?
what do you mean "be spoofed" in this context? Like could a malicious client somehow just become the server? No
I mean they could do it locally and run server code, but none of their changes to synced data would propagate to other clients unless you give the clients a lot of permissions to do things. If you stick to a mostly server authoritative architecture, this will not be an issue
and also, in most networking libraries I have used, if a client tries to do some breaking change (like sending an RPC that they shouldn't have been able to send) it will just immediately kick them from the server
If you have a host client at all, I would say it is very not worthwhile to try and decouple the code. It will just cause headaches. If you are only going to be creating a standalone server, some people opt to use entirely different projects, or split it into Client / Server / Shared assemblies. However.. most Unity-integrated libraries (like NGO, Mirror, FishNet, etc) are designed to have IsClient / IsServer sprinkled around everywhere. Unity encourages spaghetti code (which in turn means libraries made for it encourage it as well), so trying to get around it can be difficult and not worthwhile
You can check out Unity's thoughts on it in their Boss Room sample
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture/#clientserver-code-separation
Boss Room is a fully functional co-op multiplayer RPG made with Unity Netcode. It's an educational sample designed to showcase typical Netcode patterns often featured in similar multiplayer games. Players work together to fight Imps and a boss using a click-to-move control model.
To play a spacialized sound on all client should a make a serveur RPC or not ?
I need help making Client Prediction because even on the host the server player and client player get out of sync as soon as i hit a ball i have 2 gamobject with the same movement code one for the client and one with the networkobject when i move normaly they dont get out of sync but when i hit the ball they instantly get out of sync and how can i reset the position when they get out of sync everytime the hit the ball
Depends on how you are triggering the sound. From the server you will need to use a clientRPC
a client walk on an object and make a sound
Then it can play the sound locally with no need for a RPC
Ok. So let me see if I am understanding this correctly...
This means that EVERYONE that is connected to the server (including the host) runs this function on THEIR OWN and each one has a DIFFERENT 'clienId' passed in?
No this will send the same clientId to all clients
Does that mean that the line that reads NetworkManager.Singleton.LocalClientId will have their OWN locaClienId? So basically the server sends WHO died and then the clients check to see if its them that died with the localClientId?
If that's called on the player when they die, then yes
For NetCode Entities, is there a best practice for server side REST calls? Iโm guessing systems is not the best place for it and maybe use something like event bus to monobehaviour that lives server side only?
even if the sound should be heard by everybody in the lobby ?
Following a tutorial on the documentation page and I came across this.
If you start as a host.... doesn't that create a server and connects the host as a client? Why do we need the 'isServer' check? Isn't everyone a client anyway?
As far as I know a system should work fine. It would just have to called from the main thread
If the audio listener is in range of the audio source then yes. Otherwise, yea, you would need to use a clientRPC
Because the Network Variable is server authoritative. On the server can change that value. Clients would get an error
Im using rigedbodys for the movement and addForce and its Server Authoritative and now I need Client Side prediction but when i have the client it gets aut of sync even on the host when I jump against the ball so i dont know what to do because the player would get teleportet every time they hit the ball wich is the point of the game so i need help for the logic or what to do
Hello, is there a way to make a dedicated server for NetCode using Facepunch.Steamworks? If so, how? Google has only tutorials for lobbies...
Isnโt that what โSubmitPositionRequestServerRpc();โ does? Why doesnโt everyone just use that function?
That HelloWorldPlayer example is kind of a bad on. The Move() should just be SubmitPositionRequestServerRpc(). Technically the server can not call ServerRPCs. But the host client can
Whats the best resource for learning networking for an absolute beginner. ( looking to try netcode for gameobjects, other frameworks recommendations are welcomed too) trying to build a simple ip based client hosted multiplayer game
Anyone know how to make an account system with Photon PUN?
Code Monkey has a huge 10 hour course on Netcode for GameObjects
Why do you have a public and protected Network Variable? You really only need one. The private one does not need to be networked.
I may have made a mistake. Also, I solved my problem this way, right?
You might get a warning about changing a network variable before spawn but it should still work
Any suggestions on debuging Large serverTick prediction error. Server tick rollback to Unity.NetCode.NetworkTick delta
Only seem to have that problem when running server mode only and connecting with client separately. Doesn't seem to have the issue when running both on editor.
running server from command line + editor client = no problem
running server from editor + dedicated client = lag
Looks like dedicated server + dedicated client = lag too
Actually I think that might be unrelated. Itโs lagging in the sense that my IInputComponentData is not syncing over the network all the time. Sometimes it goes smooth but 75% of the time itโs not pushing it to the server
Nvm figured it out. I had mixed my input system in the wrong update group. Fixed by moving it back to GhostInputs. Weird that itโs not a problem in some cases
https://gist.github.com/Winter-r/50b01a8632ec412eb713a6de4f48e8d4
Tryna handle late joining in my game, as of right now i got to the conculsion that the OnNetworkSpawn method does not get called when players join late, thus their player object doesn't get instantiated but they do get moved to the game scene. What do i do exactly?
Does BLE come under this channel?
Hi everyone, currently I am working on a multiplayer game that use relay and netcode for gameobject. I have a list of "PlayerData" from the server that needs to be sent to the client only once when the game starts. What is the best way for me to sending this data list to other players?
If you need it sync then networklist but if only once then just pass the data through a client RPC. You will need to ensure the PlayerData can be serialized over the network.
Thank you sir!
One more thing, Is that NetworkVariable support class type?
Yeah scroll down to complex types section in this link... there is a great example of complex type that can be serialized over the network "WeaponBooster" struct https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/
Introduction
Structs but not classes.
Ok, i see now
Thank y'all
does OnCollisionStay get called by the Server and other clients?
If you are using Network Rigidbody then only the server will get collision events.
ok Thanks
was going through boss room sample, can somone explain what [Inject] is and how do i use it, whats the use cases
The OnEventComplete event will be called every time a new client joins and the scene loads successfully, right?
That is part of an dependency injection library called VContainer
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture/#dependency-injection
Boss Room is a fully functional co-op multiplayer RPG made with Unity Netcode. It's an educational sample designed to showcase typical Netcode patterns often featured in similar multiplayer games. Players work together to fight Imps and a boss using a click-to-move control model.
I keep getting this error but i dont see anything wrong
Warning: Undefined array key "loginUser" in C:\xampp\htdocs\NEA\Login.php on line 8<br />
<br />
Warning: Undefined array key "loginPass" in C:\xampp\htdocs\NEA\Login.php on line 9<br />
hey everyone, I need some help with setting up a multiplayer game, I could not find the right place to put it so I'm asking here. So my problem is not with linking up two players, but I have a problem wuth the camera, when I try to join the host with the client, the window with the host switches so the client camera shows up on both screens, is there any way to fix it?
if you need more information, i could give
There should only be one active camera in the scene. Unity will always use the last camera added. You should disable the camera of the remote player if you have that as part of the player prefab
Hi, I'm new to multiplayer and want to learn about it. I'm reading this off unity docs and don't understand something:
"Critical data (like your character health or position) can be server authoritative, so cheaters can't mess with it."
I don't get this. Games have their code running on the client's PC anyway. So can't someone access that code and change the data being sent to the server to hack it and get what they want (like max health or infinite abilities)?
Alright, ill try it
Yes they can. That's why you should never trust the data coming from the clients. This is what server authoritative means. The server will also have a copy of all the player data. The only thing the client would be sending is just controller inputs. Even those should be double checked to make sure the player isn't trying to move faster than normal or through walls or something.
It didn't seem to work, could you elaborate?
What exactly didnt work? If you disabled the camera then is would not be switched on the host?
no, the camera just stays floating where i left it
and then it shows the same thing forboth screens
Right, so wouldn't the player be able to modify the code so that they can move twice as fast for example? So when they ask the server to move they will, but twice as fast because they edited the code of the game
no, because the code is running on the server. and the clients can not modify that
if the server sees a client misbehaving like that then the server can kick that client
I'm making some tools for turn-based multiplayer games. I'm wondering what's the best way of synchronizing the game state on clients. For some games, it would be handy to just send the info about player inputs, so each client can simulate all interactions on their own. Randomness doesn't seem to be a problem, because seeds can be also sent to the clients. However, the existence of a hidden game state complicates it. By hidden game state, I mean stuff like a fog of war, traps, or cards in hand/deck. There are plenty of interactions between hidden and revealed content that could mess up simulating the game based solely on inputs (e.g. if I simulate movement on a client that doesn't have info about traps, then it obviously can't activate those unless the info about those is revealed by the server before simulation). I suppose the easy way of solving it is to sync only outcomes instead of inputs, but it means more messages will be sent to clients.
So the question is: do you know any good articles/videos that would cover the topic of syncing the game where hidden content exists? I'm curious about approaches of other people.
I don't think syncing the input would be helpful. Just sync the important data for the game state.
The server would be keeping track of who can see what in regards to the world state. After each turn the server would send the updated world state to each client according to what they can now see
how's it know who is misbehaving or what misbehaving even means
sorry I just haven't wrapped my head around how server side logic works
Depends on your game. It might be trying to double jump or shooting at a higher rate than allowed. If the only thing the client is sending is that spacebar was pressed, then there is much less room for attacks. The client could still try to spam the server with garbage packets to try to lag out the server.
Hello so im using photon for networking and I've set up matchmaking and in my matchmaking script I have it so when I find a match with the chosen mode it switches to the corresponding scene but for some reason when I switch scenes it says im not in a room when just before I switched scenes my matchmaker said I successfully created a room I can provide the script but if anyone knows what could be causing this id greatly appreciate your help I've been at this for hours and I feel like im about to lose my head
hey everyone, i need some help about this issue. After i update NGO to 1.8.0 version, when a player join as client, the server got this message "[Netcode] Received a packet with an invalid Hash Value. Please report this to the Netcode for GameObjects team at https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues and include the following data: Received Hash: 3049800023012508954, Calculated Hash: 5552551004536440314, Offset: 4, Size: 112, Full receive array: 70 00 00 00 60 11 01 00 70 00 00 00 1a 85 a3 5f f6 10 53 2a 09 d2 02 02 01 7d 9a e2 a5 01 b2 36 17 b3 01 46 c4 ca 04 01 39 3b e8 2c 01 ab c9 50 60 01 53 a3 38 44 01 d3 f6 1c b8 01 a6 22 89 97 01 b5 fe 01 74 01 be 97 be 73 01 9d 9a 5c 01 01 e9 51 97 17 01 8a f7 e7 83 01 42 7f 88 c6 01 97 a3 f5 46 01 00 00 00 00 01 5c fc ed 91 42 32 07 a3 00 00 00"
Nah, After back to 1.5.1 version, everything work good!
Weird, I didn't think 1.8 was out yet. Where did you get it from?
Hello,
I would like to develop an MMORPG on Unity in VR, and I am willing to invest a significant budget in it and want it to last in the long term.
Based on these criteria, what would you recommend in terms of networking, in order of best to least recommended? Fishnet, Mirror, Netcode, Photon, or creating my own network? If, for example, I start with one of them, is it easy to switch later on? Or, if I want to switch, would I have to start all over again from scratch? Let's say I started with Fishnet and want to switch to Netcode or my own network, would I have to start everything from scratch, or are there just a few modifications needed to adapt?
For a legit MMO, you are going to need a large experienced team and huge server infrastructure. You can use Unity Transport but you would be basically building everything on top of that from scratch.
If you just mean an online RPG then any of the networking frameworks will do. I like Netcode for GameObjects.
Unity Transport is a library to build our own networking ? also when you say large experienced team, we need it directly from the start or is it scalable ?
Yes, unity Transport is fairly low level. It's not exactly dealing with raw sockets but it's damn close. It's what Netcode for GameObjects and Entities are built on top of.
I can't tell you how to manage your team but the people writing your game server are not going to have time to also work on the client or make character abilities. And that not even counting the ungodly amount of art assets that will need to be created and integrated into the game. And all of this has to be done roughly simultaneously
@sharp axle thank you for your answers ! One last question, if I would like to build a team who will work on developing our own networking code, what kind of skill should I focus on in their profile, how can I tell that he's the good one for the job ? because there are a lot of people mentionning networking skill, but not all of them will be able to work on a networking code from scratch I guess, is there a way to diferenciate them and to be able to define which one will be able and which one will not ?
Zenith online is a VR MMO made in unity. They have a good article on using unity DOTS and how it assisted in lowering server rate limits. Netcode for entities is probably specifically better than netcode for gameObjects if looking at unity's built-in multiplayer solutions. Zenith also used some of the ugs like vivox I believe
That's the million dollar question. It's the reason why entry level positions require previous experience. It's a very hard problem. I don't have a good answer for you.
Zenith is a good example to go by. They are using Dots but not Netcode for Entities. I believe that began using SpatialOS but I don't if they switched to something else
https://unity.com/case-study/zenith-the-last-city
I was reading this article, and I recall if I remember correctly when I asked them, that they started with something and then went for their own network solution
Yeah i am not sure what they used for the networking (I don't think Netcode entities was ready for them when they were in development... but because of the benefits of ECS that DOTS gave them for VR MMO... Netcode for entities would be better than gameObjects in an MMO space.
Sorry guys for those questions, I'm just trying to understand since I'm not from that universe ๐
What's the difference between Unity Transport, unity Dots, Netcode for Game Objects and Netcode for entities ?
Unity transport and unity Dots are library to build our own network ? and Netcode for Game Objects / entities is an already built networking framework ?
DOTs is the Data Oriented Technology Stack. It's a whole suite of systems. The Entity Component System (ECS), the Job System, and the Burst Compiler are all part of it. It's a completely different programming paradigm using Data Oriented Design.
Netcode for Entities is built using DOTS and Unity Transport. It has deterministic Physics and a Client Prediction System built in.
Netcode for GameObjects is built using unity Transport and the regular systems we are all used to.
How to install Unity Netcode for GameObjects (NGO).
i have just a question i have made a game where it is possible to move the player and have different guns and stuff but how can i make this game multiplayer with lobbies and teams is there like a page or tutorial you guys reccomend ?
Ok so if I understood it correctly :
1 - Netcode for Entities/Gameobjects are framwork like Photon, Mirror, FIshnet
2 - But those framework are built differently and for the Netcode case they both use DOTS but depending on entities or gameobject they will either use Unity transport either the regular systems
If That's the case then if I start with either Netcode for entities either Netcode for gameobjects, it should be easy to switch to building my own network after using DOTS and unity transport or regular systems, since they have the same basis ?
Only Netcode for Entities uses Dots. DOTs requires a complete rewrite of you entire game to use ECS.
Porting a game to multiplayer after the fact is gonna be a bad time. Unless you coded it with that in mind. Check out Code Monkey's 10 course on Netcode for GameObjects
thank you
1 - correct
2 - But those framework are built using different low level transport libraries... for unity Netcode case they both use unity transport.
3- Netcode for gameObjects provides high-level networking for GameObject/MonoBehaviour workflows. Netcode for entities provides high-level networking for DOTS.
As evilotaku mentions, it is not easy to switch later without massive rewrites to code, game architecture and package/dependency changes.
I'll be damned. You gotta install 1.8 by name but it sure says it released on the 8th. It has some pretty major changes that I've been looking forward to.
/// Registrierung Username & Password
/// </summary>
public async Task RegisterWithUserNamePassword()
{
try
{
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(m_RegisterUsernameInputField.text, m_RegisterPasswordInputField[0].text);
Debug.Log("SignUp is successful.");
}
catch (AuthenticationException ex)
{
ErrorMessage(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
//Debug.LogException(ex);
}
}
private string ErrorMessage(AuthenticationException ex)
{
return "";
}```
Hey how Do i get the ErrorCodes and can change them in a If statement ?
Then even if we start our own network we will have to choose between how netcode for gameObjects did and how netcode for entities did ? which is either going for networking for gameObject/monoBehaviour or going for DOTS ? if we go for mmorpg in VR we should go like zenith did with DOTS ?
Also if we go with a framework like Fishnet or Photon or Netcode, what will be our limit, what will be the wall breakboint that we won't be able to overcome ?
The limit for all of those frameworks including both Netcodes are server to server communications. A single server will only hold a few hundred players at most. So a shard with 3000 players will need 10+ servers communicating with each other. That's why you'll end up with a custom networking solution
is anyone here familiar with photon fusion? how do I tell what player avatar belongs to who? I need to programmatically assign my player input class to its networked avatar
Hi everyone, my ServerRpc function send player data from client to server and call a ClientRpc function inside it to send data to another client but when i call this, nothing change and got this message
"[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 0, but that trigger was not received within within 1 second(s)."
Anyone know about this?
You will have to wait until OnNetworkSpawn() before you can send RPCs
my function not call after scene start, it just call when i click a button!
does anyone have good servers for coding or just for unity?
Do you have anything getting called in the OnClientConnected callback?
If you mean discord servers then check the pinned comment here for the Unity Netcode server
Nope. Nothing
Dunno. You've got gremlins sending network messages to an object before it finished spawning
Hnmmm. I have 2 function same like that but 1 work 1 not. Maybe it cause by object?
Are they being called in Start() or Awake()?
Nope. Just by click
is there anyone who can help me with Photon i just tried to make basic movement with server and joining and making rooms but whenever someone joins the room he can control the other players movement is there anyone who knows whats wrong because before there were any rooms it was possible to move sepperatly
I don't use Photon but is sounds like your movement script is not checking for owner or local player
Yeah I checked but the weird thing is he can control me and I can control him but we canโt control our own player and itโs also with the looking but I will check again
Thank you
All gameObjects spawned by 'Unity Netcode for GameObjects' are always set with IsOwner set as false, even the player object that was created when clicking "Start Host". Is this a bug? Maybe I'm missing something or I accidentally changed a setting?
Depends on when you are checking for it. If you are checking in OnNetworkSpawn then it should be correct.
I'm currently checking in the spawned player's Awake, So Awake would be too early then? I'll try that.
That fixed it, you were right. Thanks.
Can anyone tell me what networking solution should i use for a game similar to lethal company like procedural generation , proximity chat and AI I am thinking either fishnet or netcode for gameobjects
Lethal Company uses Netcode for Gameobjects + Facepunch Transport for NGO. So you should be fine with them (in case you're going to develop for Steam)
Link to Facepunch Transport: https://github.com/Unity-Technologies/multiplayer-community-contributions?path=/Transports/com.community.netcode.transport.facepunch
For the voice chat, they use this package: https://assetstore.unity.com/packages/tools/audio/dissonance-voice-chat-70078
But you might also try Vivox from Unity.
thanks
where can i find more information about lethal company
unless you find some devlogs by the developers you are not going to find much. There is a pretty big modding community for it though
This is attached to a player prefab (which spawns when you start as a host or when you connect as a client)
I have started a server, nothing shows us because there is not player (as expected)
BUT when I connect as a client then this code gets executed. Why is that if I connected as a client and not a host?
Btw, this log only shows up in the server instance.
When will a client not be an owner?
That network object will be spawned on all clients. Only one of those clients will be the owner
Scroll down to ownership in this link for a full explanation and examples: https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/
Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:
do NetworkDictionary not exist in Netcode for gameobjects? if so what can i do instead?
With here, I can't call the RPC because it is despawned, where can I put the call to the RPC?
and another issue in calling it on spawn too
here, the issue is when playing as 'host' (client & server in one) i think the player is spawned before the 'gameController' so I have to use a wait (fixes the problem) but obviously not ideal
would be fantastic if someone could help me out here, once this system is polished I'm happy to move on
just 'fixed' this one by checking 'isSpawned' and if not spawned will call coroutine else will call RegisterServerRPC directly
but the disconnecting one still puzzled by it, It wouldn't occur if I had a 'leave match' button but atm when I stop unity playmode it insta-dcs
I am making a multiplayer 3d game and I have an issue with Photon Pun 2 where when a second player joins the room the two players view and controls switch. Is this a common problem? How can I fix it? I followed this tutorial: https://youtu.be/93SkbMpWCGo?list=PLk_wI66GzU9jCMTDBGyZLY83x3vyg6lcb
Get your next game design project organized - Sign up to Milanote for free: https://milanote.com/blackthornprod0621
Udemy Multiplayer course: https://www.udemy.com/course/beginners-guide-to-multiplayer-game-development-in-unity/?couponCode=86D7C0073D7CD59B6C07
0:00 - Intro
0:3...
At the moment there is only one on the community repo that should still work.
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDictionary
This should be fixed in 1.8.0
anyone here good with photon ?
good news, will it auto-update for me? and this is unity or netcode update?
Its a netcode update. its available now. you can install it by name and specify the version number
Im trying to spawn a projectile particle using a NetworkTransform and Teleport. but Im running into issues where its still at 0,0,0 when I go to turn on the Particle System
isPlaying.Value = true```
How do I get things like client network transform
is there a very good youtube playlist that teaches multiplayer fundamentals and how to implement them using Mirror?
how can I code the enemy in my game to follow and attack players in multiplayer?
I'm not sure if I even need to do anything
do players in multiplayer games all have the same GameObject?
Make sure that only the server is teleporting that object
You can just copy the code here
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform/#owner-authoritative-mode
Introduction
It's not mirror but Code Monkey's has a 10 hr course on using Netcode for GameObjects from scratch. Mirror is very similar if you are stuck using it.
Generally AI is handled by the server and the bots position is synced with a network transform. Just make sure that the bot logic is only running on the server
is there a tutorial or something?
On making AI? Or using a network transform? You can have the AI component disable itself with a IsOwner check. That way the AI will only run on the server.
network stuff
so the monster can go after the closest player
There is no network stuff needed to do that. The server can check for every object with your player class on it and then test for the closest one just like in any single player game.
If you need help with using RPCs and network variables then that's different. Check out Code Monkey's course on the basics and that will get you started
so I Don't need to do anything?
๐ฌ Here is the Multiplayer Course! I really hope both of these FREE courses help you in your game dev journey! Hit the Like button!
๐ Course Website with Downloadable Project Files, FAQ https://cmonkey.co/freemultiplayercourse
๐ฎ Play the game on Steam! https://cmonkey.co/kitchenchaosmultiplayer
โค IF you can afford it you can get the paid ad-free ...
This one?
If it's just finding and moving towards the player then no. Just put a network transform on it and it will work
I am yes, but calling teleport then setting a networkvariable. on the client when i get the OnValueChanged it hasnt teleported yet
I see. yea, they are being called in the same frame. I don't know if it would be easier to wait a frame before setting the isPlaying or put a delay in the particle system itself.
thats what i did, but that always makes me nervous, why are they arriving out of order?
I'm develop my first multiplayer RTS competitive game. Now I'm struggling with the approach of handling the visual representation. My game is mostly server authoritative and actually I've for each visual unit object a separated ServerObject, spawned to each client. Should the visual representation only performed on client side, like it is done in the Boss-Room tutorial? Or should I instance the visual representation also on server side and use NetworkPrefab instead of the client self loading approach. I'm not sure what is the better approach. BTW, each unit could be customized by a player like in an RPG and have separate equipment (got archetype definitions as ScriptableObjects, but could be modified). Those changes should be also visualized.
Hello. I am using the steamworks.net sdk to communicate with steam. I create a lobby via SteamMatchmaking.CreateLobby, and set some lobby data via SteamMatchmaking.SetLobbyData(...);
From a different steam account / build instance, I fetch the lobbies my steam friends are in via this process:
- int friendCount = SteamFriends.GetFriendCount(EFriendFlags.k_EFriendFlagImmediate);
- for (int i = 0; i < friendCount; i++)
- CSteamID friendId = SteamFriends.GetFriendByIndex(i, EFriendFlags.k_EFriendFlagImmediate);
after which I get the lobby id via SteamFriends.GetFriendGamePlayed(friendId, out friendGameInfo) and friendGameInfo.m_steamIDLobby.
everything is perfect so far. i can create lobbies from steam account A, and I can find it on steam account B.
Unfortunately, I can't retrieve any lobby data from account B. Even after doing SteamMatchmaking.RequestLobbyData(friendLobbyId), which the documentation says you must do for friend lobbies which you havent joined yet. SteamMatchmaking.GetLobbyData(friendLobbyId, KEY)) always returns an empty string regardless of which key I use.
any ideas what i'm missing?
I'm sure this has been asked already somewhere but I am trying to send a procedurally generated map (list of transforms, rotations and prefab indexes) to clients once the host has generated it. I can't for the life of me figure out how to send clients a list of struct data with the info in it.
I have the following:
public struct MapData : INetworkSerializable, IEquatable<MapData> {
public int prefabIndex;
public Vector3 position;
public Vector3 rotation;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter {
if (serializer.IsReader) {
var reader = serializer.GetFastBufferReader();
/*
serializer.SerializeValue(ref prefabIndex);
serializer.SerializeValue(ref position);
serializer.SerializeValue(ref rotation);
*/
reader.ReadValueSafe(out prefabIndex);
reader.ReadValueSafe(out position);
reader.ReadValueSafe(out rotation);
}
else {
var writer = serializer.GetFastBufferWriter();
writer.WriteValueSafe(prefabIndex);
writer.WriteValueSafe(position);
writer.WriteValueSafe(rotation);
}
}
public bool Equals(MapData other) {
return prefabIndex == other.prefabIndex && position == other.position && rotation == other.rotation;
}
}//EO Struct
But it's throwing serialisation errors in the console. Is there an easy way to do this? (I tried using network objects on the prefabs but there is some wierd parenting going on in the alogrithm that causes errors so figured an RPC or network var would be better)
It's probably because it takes a frame to move and update the network transform. I'm not too sure though. I rarely use teleport unless a player has died and is respawning
Visuals are usually rendered locally only. The server will be headless so no graphics there in any case
You don't send the entire map data. Normally you just send the seed and let the client procedurally generate the map locally.
the map is just a bunch of prefab rooms and no seed is generated by the function I'm using because it wasn't meant for multiplayer. Any ideas?
Since the rooms are randomly generated, there isn't a way to rebuild it on the clients without going ham on the randomiser function afaik
So I figured passing a list of structs to the clients was the best way. Or have I missed something way easier? ๐
I just try to perform a server validation of a client raycast. On Host everything is working fine, but on client side, I got no raycast hit in the ServerRPC. Here is my code: ```public void OnPointerClick(PointerEventData eventData)
{
if (IsClient)
{
var ray = Camera.main.ScreenPointToRay(eventData.position);
var position = ray.origin;
var direction = ray.direction;
if (Physics.Raycast(position, direction, out var hit, Mathf.Infinity, 1 << 8))
{
Debug.Log("Hit at clientside side with coord values! " + hit.point.ToString());
Debug.Log("Object: " + hit.transform.gameObject.name);
Debug.Log("Layer: " + hit.transform.gameObject.layer);
RequestSpawnPositionServerRPC(position, direction);
}
}
}
[ServerRpc]
private void RequestSpawnPositionServerRPC(Vector3 position, Vector3 direction, ServerRpcParams rpcParams = default)
{
Debug.Log("ServerRPC executed");
if (Physics.Raycast(position, direction, out var hit, Mathf.Infinity, 1 << 8))
{
Debug.Log("Hit object at server side! " + hit.point.ToString());
Debug.Log("Object: " + hit.transform.gameObject.name);
Debug.Log("Layer: " + hit.transform.gameObject.layer);
}
}``` The Object to detect is spawned with client ownership. By this reason the RPC could only called by clients with ownerhip, and I see on server side, that it is called. But based on same inputs, I got no raycast hit. Any idea why this not work?
Meanwile I take a walk with my dogs and think about it. May this not working, while the server is also the host and have a camera set-up in opposite direction? (View is like a tabletop, where you sit in front of your opponent)
um using fixed update for the movement in my game its server authoritative should i still use tickrates because the player gets out of sync really fast even though i run both instances on the same pc https://codefile.io/f/psZYpqjfml
guys whats a best way to do ui for photon
i have a ui as a child of the player but its having hard time displaying the local players stats
should i make a ui prefab and spawn it with the player as thei child ?
If either object is moving then you would need to send a timestamp as well. You'll need to do the ray ast from that timestamp instead of when the server received it.
@sharp axle The object is a none moveable plane on ground to define an entry zone.
You might need to use Camera.ScreenToWorldPoint instead. Different screen resolutions might be messing this up.
@sharp axle The values I send to server are the postion and direction from this raycast on client side. I also already tried to use the camera.transform.position and forward value, but this never produces a hit. I already tried as you mentioned the camera on server side directly, but this also not produces a hit.
Debug out the position and make sure its in the same spot on both
for unity netcode i have three two different ui, one for the gameMaster and one for each player,
im unsure how to give players their own seprate ui because their uis keep overlaping
UI should be instantiated locally and not part of the prefab
@sharp axle Yes it is, values checked several times. On host everything is working, for check I've activated the RPC, which is normaly not used by host. In this case, client event and RPC generate the same result and a test object is correctly placed at hit point. May it make a difference, that the camera on server side is the host camera, with opposite position values (client rotated 180 degree and on opposite positive z value)?
no raycast does not care about camera position. as long as the target has a collider then a raycast should hit it
@sharp axle I think I got it. I moved my collider by mistake to the visuals, which are not visible at server side (deactivated at each client without ownwership). So the raycast has nothing to collide ... At host this works, while the host is the client and has those visuals.
Hi. I want to make 2-player game and I need to a lobby locally with ParrelSync but I get this error when I try to join as player2 (Client)
Unity.Services.Lobbies.LobbyServiceException: player is already a member of the lobby ---> Unity.Services.Lobbies.Http.HttpException`1[Unity.Services.Lobbies.Models.ErrorStatus]: (409) HTTP/1.1 409 Conflict
I know why I get this error, the players on both the original Unity Editor and the Clone have the same ID.
Is there any way I can make the Clone instance generate a different ID or an alternative to ParrelSync?
@granite stump You can force ParallelSync to use a different Player Setup. Then this failure will not happen
How?
Unity Multiplayer Networking
https://docs-multiplayer.unity3d.com โบ ...
Testing multiplayer games locally
This site provides Unity Multiplayer documentation, references, and sample code tutorials.
There is a ifdef You have to set for different authentication
Thank you. It's kind of late in my time zone, so I'll look more into it tomorrow.
Works fine. Use it by myself sice several month. You can also take a look to the Boss-Room tutorial
Hello.
I am using unity 2022.3.18f. I have a scene with a player prefab and a NetworkBehaviour, NetworkObject and a NetworkTransform component on it.
Via the NetworkManager I start a host on one instance and with ParrelSync I start a client on another instance.
The client connects to the host normally, no errors. I can see both player prefab clones on both instances, however there is NO synchronization happening (not even the host player prefab gets synchronized. I know the client's shouldnt but at least the servers' should as far as i can tell from docs / tutorials).
What could be the reason for this?
- The player prefab is referenced in the network managers player prefab slot, as well as added to the network objects SO.
- Synchronize Transforms is enabled on the NetworkObject component.
Code monkey offers a good video when I'm debugging stuff like that https://www.youtube.com/watch?v=3yuBOB3VrCk
โค Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
๐ Get my Complete Courses! โ
https://unitycodemonkey.com/courses
๐ Click on Show More
๐ฎ Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubre...
Hello guys
I would like to know how to don't destory Networkobject when owner out room in photon fusion.
private void NetworkManager_OnClientConnectedCallback(ulong clientId)
{
PlayerData playerData = GloomGameMultiplayer.Instance.GetPlayerDataFromClientId(clientId);
this.clientId = clientId;
isSpectator = playerData.isSpectator;
Debug.Log($"Client ID {clientId} is connected");
}
public override void OnNetworkSpawn()
{
Debug.Log("OnNetworkSpawn called");
if (IsSpawned)
{
Debug.Log("Network object is spawned");
if (!isInitialized)
{
Debug.Log("Initializing components");
InitializeComponents();
}
}
}
I'm trying to initialize my players according the variables assigned in the OnClientConnectedCallback event, however the OnNetworkSpawn is getting called before it so it doesnt end up getting initialized correctly. What can i do in this case?
Why not move everything into OnNetworkSpawn?
The client id argument
guys im learning networking - trying to make multiplayer work from scratch, and how to handle two way UDP connections when there is a nat on the clients side? I know there is something like nat punch but no idea how that works. Anyone can help?
or just send position data by tcp?
Easiest way to use a relay service like Unity Relay
i dont really want the easiest solution
It may be too much at once but i want to fully make everything from scratch (somewhat)
Good luck. You'll need a stun server if you want nat punch through
Looking for some project guidance.
I have a Unity Windows build that is connected to several microcontrollers over serial ports. I would like other devices (PCs, tablets, phones) on the same local network to be able to access a simple UI to see some variables states and send commands to the main application.
My thought was to have my main application, on startup, deploy a locally hosted Webgl build of an application containing said UI.
Given how simple this should be (I hope), what path would you recommend for handling the networking? Am I on the right path regarding the locally hosted Webgl build? If I ever wanted to access the UI from a different network, how could that be accomplished?
Thanks in advance for any pointers.
and if you had to choose between Unity and unreal for a vr MMORPG at high scal, you would go for which one of them (in total neutrality ๐ ) and why ?
It would be whatever one your team is most comfortable with.
Are the two equal? Because I was told that Unreal had several advantages, especially with nanites.
https://hastebin.com/share/esizatiber.csharp
anyone know why I am unable to move on host editor, but client editor works fine?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Sure if your team know how to take advantage of nanite
Is there a link to all the functions/methods/properties for the network manager?
For example something like
NetworkManager.SOMENAME
Or
NetworkManager.Singleton.SOMENAME
I'm wondering how I can display a Health, Ammo and Coin UI for a game I'm working on. https://streamable.com/caxzdf because atm it works perfect on the host end but when others join it bugs it out because I guess I need to spawn more copies dynamically and/or the network variables can't be changed by the client or something?
and I want each player's screen to look like this https://streamable.com/cof7pm
should the playerHUD also have network behavior?
the health station seems to work with CurrentHealth being a network variable but CurrentAmmo seems to have issues
The UI itself should not be networked. It needs to be Instantied on each client locally
ok, so you set up a holder for the player HUD on each player's game object, and then spawn that dynamically in?
Not with .Spawn() but just Instantiate(), yea
hello, i am using ParrelSync in order to have 2 players running at once and test out networking, however whichever unity instance is in the background is running at 4 fps. (foreground one is running at 300). i have a geforce gpu and windows 11 installed. how did you guys remedy this? (for those using a similar setup for network testing)
Should this not be a network variable?
No, it's being set with an RPC
But how is this synchronized? Isn't that the job of a network variable to synchronize things across all players?
side-note: I'm working my way down the docs, next is 'spawning and ownership' and then 'network synchronization' so hopefully this get cleared up later, just where I stand now it seems that this will not get synchronized.
The RPC syncs it for everyone currently connected. late joining clients will get the latest through OnSynchronize() when they first connect
Best way to debug netcode entity with rigidbodies? Basically my character gets into an invalid AABB error without info. Character is fine if I remove the rigidbody (ground has it, other stuff have it). I also have a navmesh on the ground. The moment I add it, the character snaps to the edge of the nav mesh surface outside of bounds and get invalid AABB. Doing a small scale test on a new project doesn't seem to yield this problem. I also set it so that the character's collider is is_trigger: true but that hasn't change a thing about it. Character doesn't have physics world index on it yet and it still has that problem.
Hey if anyone is currently looking at multiplayer system, we've recently posted one we've been working on since 2015. We call it Reactor and it's a bit like photon except the 'room' can run your code, contains your physics and collider data, and executes physics. We've implemented a networked controller system to use with physics based games. Our big achievement is that Reactor can update tens of thousands in real-time with relatively little bandwidth (often 3 bits per 3d object per update). We've used it to run games since 2017, so we've had a lot of time to ferrett out the issues. We provide it as a unity package tarball that you install using Unity's package manager. We have the development SDK posted here: https://kinematicsoup.com/reactor/download
It has built-in hosting that requires an account on our back-end and we'll have to enable it.
I'm trying to spawn different prefabs depending on weather the player is a spectator or not, but it's always spawning as a regular player even though according to my Debug.Logs it is getting acknowledged as a spectator. Maybe there's a problem in the Network Manager component?
private void InitializePlayer(ulong clientId)
{
PlayerData playerData = GloomGameMultiplayer.Instance.GetPlayerDataFromClientId(clientId);
bool isJoiningLate = GloomGameMultiplayer.Instance.IsPlayerJoiningLate(clientId, GloomGameLobby.Instance.GetLobby());
if (isJoiningLate)
{
InitializeSpectator(clientId, playerData);
}
else
{
InitializePlayerObject(clientId, playerData);
}
playersNetworkList.Add(playerData);
}
private void InitializeSpectator(ulong clientId, PlayerData playerData)
{
playerData.isSpectator = true;
Transform spectatorTransform = Instantiate(spectatorPrefab);
spectatorTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
}
private void InitializePlayerObject(ulong clientId, PlayerData playerData)
{
playerData.isSpectator = false;
Transform playerTransform = Instantiate(playerPrefab);
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
}
I have client prediction in my game and everything works fine except when it comes to moving parts like a ball because the ball has a diffrent pos on the server than on the client wich causes stuttering and also when trying to hit the ball you miss extremly often cause the hit gets calculatet on the server where the client and ball have a different position so how do i handle something like that
I'm also confused with those things, but I think the correct approach is to go back in time
Yea. Basically you will need to keep a list of positions that the ball has been in order to be able to roll back and do you physics calculations from that point then resimulated up to the present.
In photon fusion as master I can see A) my input B) other client's inputs
But as a client I can only see my input, and not other people's input...
Can we as a client see other people's input? Or only master can?
I don't use photon, but normally inputs are only sent to the host. you could have the host send the inputs to the other clients if you really need to
I see
, is there a reason why we usually don't send over the inputs? I feel like sending inputs over would make syncing much more accurate
the inputs clients would be getting from other clients would be delayed by 2x ping at least. And if its server authoritative, then the server is the one moving everything anyways.
How so?
Client input -> master
Master sets position and animation and sends to client
Client input -> master
Master input -> client, client sets position and animation locally
Both would be executed in 2 steps no?
The first one the position is set after one ping. Server is authoritative.
Second one the position is set after 2 pings. Client is authoritative. You'll need to deal with that lag somehow. Usually with some kind of client prediction system.
Wait so in first one the second step doesn't take one ping?
It does. but the server is what matters. Since that is where all the gameplay logic is happening. Clients there are just seeing the visuals
I see
thanks for the useful info!
for ownership the host and the server are the same entity.
Networking package question, I am using Mirror and KCP and have a question about message size
How efficient should I be compressing my messages? Will I notice any kind of significant performance different in for example compressing and then unpacking a Vector2 into/from two shorts instead of a vec2?
ok thanks i found a talk on youtube about rocket legue cause it was the most similar to the type of game im going with the just used client prediction for the ball and player i will try that and hope it will work
Let's say I am a host and I have a main menu where you can select to be a host or a client. I have scene1, scene2, scene3. My host has passed scene1 and scene2 and is now on scene3.
My question is if a client joins will they be automatically taken to scene3?
If I am controlling a cursor over a network, 'when' should be I be applying changes to the cursor?
Update? Fixed Update? Late Update? InputSystem.onAfterUpdate? As fast as the network is able to send messages?
If you are using NGO, then yes. The host will sync it's currently loaded scenes to the client. You could load your scenes additively if you can't have scenes being skipped
Hello, is there any limit for users stored in unity cloud?, not talking about the data inside each user, i'm just talking about the max amount of users that can be stored
There is no player limit. Just keep in mind that you pay per GB and every 10k read/writes passed the free tier
hello, I am facing an issue where my network prefab seems not to be owned by any client even if I spawned the gameobject using NetworkObject.SpawnAsPlayerObject(clientId), does anyone know if I am missing any needed steps for properly spawning a player object?
Lets say we have 3 players and particles system that spawns particles over a players head.
If the server runs the ClientRpc all three screens have particles for THE ONE PLAYER who called it.
My question: If this ClientRpc runs for ALL clients why don't ALL client get particles on them?
It runs for all clients on their local copy of the player of the client that called it
Are animator layers functioning in netcode for game objects? Owner Network Animator
Can anyone help me w/ my first person networking movment
Both my client and host have a frozen camera
I belive they can still look
as in tilt the camera
but when moving they both move one of the two capsules I have setup
*correction, they both can move but they control the same capsul
and the host has pretty scuffed movment
Am I misunderstanding how changeownership works? I want to teleport all players 40 in the air when all players are connected.
There is nothing else you have to do. You might be checking owner too soon.
I believe Layers should work like normal.
Make sure the input code is checking for isLocalPlayer or IsOwner
Either
It might be taking a frame to actually change the ownership.
ah ty, I'll move to using an RPC to handle this
The RPC is being sent too soon. You'll also need to check that the object has spawned. checking if(IsSpawned) should work
Ah, it has to be spawned. I was hoping I could just have it in the scene
In scene network objects will get spawned automatically when the network connects. Its just that Update() happens before all of that
Oh wait, I think I'm spawning them wrong
Ah that was it. I needed my prefabs to be of type NetworkObject and to actually call spawn on them.
In Unity, you typically create a new game object using the Instantiate function. Creating a game object with Instantiate will only create that object on the local machine. Spawning in Netcode for GameObjects (Netcode) means to instantiate and/or spawn the object that is synchronized between all clients by the server.
I shoulda googled at the start 
I have a list<Player> from Unity lobby and a list of clients from the network manager. I'm wanting to bring across player data from the lobby to in-game.
I need to work out which client belongs to which player. Struggling to think of a way to do this as the clientID starts from 0 and the playerID is from the lobby system.
The camera is still locked onto one of them and the movement is scuffed
anybody mind hekping me?
I don't even know if my code works w/ ownership
You'll also need to make sure that there is only one active camera in the scene. Disable the camera for the not local players
only the local player needs a camera. Each player will have their own camera
How do you mean?
Now when I start Thers no cameras
Sounds like you are disabling all the cameras instead of only keeping the local player's camera
Where do I put my network objecvts
The network object should only be on the root object
Just one on the player prefab right?
ok
It is still moving just the host capsule and the movement on the host is scuffed
Camera is locked to the host capsule on the client as well
Nevermind, the client is jenk with the host capsuler
you can jump with the client capsule using the client but the camera is locked too the host, movment the same
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
readyToJump = true;
}
private void Update()
{
if (!IsLocalPlayer) return;
// ground check
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.3f, whatIsGround);
MyInput();
SpeedControl();
// handle drag
if (grounded)
rb.drag = groundDrag;
else
rb.drag = 0;
}
private void FixedUpdate()
{
MovePlayer();
}
private void MovePlayer()
{
if (!IsLocalPlayer) return;
// calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
// on ground
if (grounded)
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
// in air
else if (!grounded)
rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
}
private void SpeedControl()
{
if (!IsLocalPlayer) return;
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
// limit velocity if needed
if (flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
private void Jump()
{
if (!IsLocalPlayer) return;
// reset y velocity
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
private void ResetJump()
{
if (!IsLocalPlayer) return;
readyToJump = true;
}
}
Is it my code?
Is the camera on the player prefab?
Can anyone explain me how clusters would work in game engine. Websites cluster is simple to understand, load balancer gives specific node a task and it returns the finished result. when you multiple clusters is fine, couz each task is self contained, so you can easily scale it. But in game dev, where you track position for example, you don't have self contained data, so in order to know if another player touched yours you would need to share the data between cluster nodes. But sharing this data makes you to have communication node of some kind and it needs to have all the data, and you get your bottleneck here. So how for example eve online had their cluster like server and hosted server for thousands players? Am I missing something?
As for now I can only imagine linear horizontal scaling, 500 people goes to server A, when server A full, new players go to Server B. Server A can't see server B and everything works. But this is not rly cluster method....
Online chess game
Weird, maybe it's because I have netcode 1.2. it doesn't work in my case
The IsOwner flag does not become true. I check for its value during every update loop and it always stay false. The player object is spawned in the world but it just seems like no clients own it
Yeah
most MMOs are split up into zones. the only time server to server communication would be needed is when a player is at the edge of a zone and is about to switch servers. kind of like cellphone towers. But few people are making MMOs these days
You've got something else going on. SpawnWithOwnership() does exactly that
That's what I read from the documentation and why I am really confused. One more thing, when I spawn player object by assigning a player prefab in the Network Manager properties (as soon as a client connects, the player prefab is spawned), the player object can be controlled properly. When I do it via SpawnWithOwnership() it does not work. Is this helpful in anyway?
I guess it depends on where you a checking for ownership. If it's a player prefab you can use .SpawnAsPlayerObject() as well
I have tried this function too, same results
My player prefab contains a script that only accepts client input if the object is owned by the client (so that only the player can control his own player object, i suppose that is the standard way to do it?). The current situation is that since ownership check always fail, the player cannot control his own player object.
I have also added the prefab into the Network Prefab List before this happened, just in case you suspect that's the issue
That should be fine. Are you checking IsOwner or isLocalPlayer? Though both should be true for that client's player object. And are you checking it in OnNetworkSpawn()?
Yes
You need to check if the player prefab is the local player and then disable the camera on it if it is not
How does that work exactly, it only disables it if its not owned and It doesn't do this to other clients?
Each client will only have it's own camera enabled.
if (!IsLocalPlayer)
{
Camera.Destroy(gameObject);
}
put this in
all of the cameras are gone
how do I disable the camera?
Camera is a static class that has the main camera. You want disable the prefab child object or component
So i disable it and use something like ```c++
if (!IsLocalPlayer)
{
Camera.Destroy(gameObject);
}
Excuse me
using UnityEngine;
using Unity.Netcode;
public class OwnerComponentManager : NetworkBehaviour
{
[SerializeField] private Camera _camera;
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (!IsOwner) { return; }
_camera.enabled = true;
}
}
Hi, i was wondering if its possible to load a modified prefab on a client but the other clients see it as normal. (network for gameobjects)
Both IsOwner and IslocalPlayer shows false. I am checking the flags values in Update(). OnNetworkSpawn() was not even invoked when the prefab is spawned using SpawnWithOwnership() or SpawnAsPlayerObject(), however OnNetworkSpawn() do get invoked when spawned as the default player prefab when set in Network Manager.
Ok your objects are not actually spawning. Make sure that the spawn functions are only getting called in the server. Clients can not spawn things themselves.
I see. I am also using Client Network Transform instead of the server authoritative one. I thought by doing so I can simply spawn it client side and it will sync across clients by themselves. And from what i observe the other clients do see a new player object spawned when one client spawns the object, it's just that the IsOwner flag stays false.
is there a way to make multiplayer testing easier, instead of me making a build everytime i just need to change a single line
Can I add multiplayer to a game after creating a project? Or should I create a new project and just move everything over and do the necessary adjustments, there isn't much to move or much that is affected, just wondering if it requires a new project setup for things like Photon or FishNet
Hey guys, my clients can't connect to my ip when doing the gaem
On an external Ip U get bitgubg bacj
I get nothing back from the clients, pardon me
Hi guys. Any advice on a socket server for a webgl client? Scalable
It does not need a new project. But you want to start implementing multiplayer as soon as possible so you aren't rewriting a bunch of things
It's most likely a firewall issue. Have you tried using the Relay Service? Also make sure you have Allow Remote Connection checked
Relay unity transport?
We do have remote connection
Why wouldn't it be wworking?
My ports are all forwarded
Like I said it's probably a firewall issue
When the other side tries to connect it starts a client with any ip, stalls, and doesn't get anything
It gives back an empty client with just ui and no camera
Anyone got any decent ways to sync a rigidbody's velocity across the network?
Have you looked at NetworkRigidbody? https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/
There are many different ways to do physics in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.
yeah, we have those
but I don't see a way to get the velocity synced from that?
velocity represents the state of the rigidbody. your question makes no sense in that context, what would it sync if not velocity?
Yeah, but we already have NetworkRigidbodies
and yet our velocity is not being synced, as you can see
it's like it's just syncing the position of the cars, and not the rigidbody?
at least not the velocity
"On the clients, the Rigidbody is kinematic." ohhh
so it doesn't actually sync the velocity by design
Hey guys, kinda stupid question but I have to ask it. I cannot find the lobby package in the package manager. I've linked my project to my ID, entered my payment information (even though I'm yet to make any revenue from this project lmao?), restarted the editor in case the token needs to refresh, and can still not find it in the Unity registry or in the project. Not really sure what's up. Anyone got any pointers? Any help is appreciated.
is there any chance that if I installed lobby and relay earlier they just wont appear anywhere in the package manager? including in the "In Project" section?
okkkkkk sooo it seems relay is here but not lobbies?
is my version of unity (2021.3.1f1) too old for lobby now or something?
(relay is also not appearing in the package manager)
quick question, on the player are a network object, network transform, and rigidbody, and in the movement script is if (!IsLocalPlayer)return; to not run the movement
why does the joining player not move? only the host
Because only the local player can move in your script
yeah but how do i make that only the current player can move and not move all players when pressing a button?
i used isLocalPlayer because i thought thats the solution for that
Make it so only the local player only moves itself and put a network transform on it
Or have the local player only send its move-inputs to the server and have the server move the corresponding player, also put a network transform on all players
but doesn't it already do that? i mean i have in update where the movement input is if (!IsLocalPlayer)return;
so i thought it only runs if it is the local player, so the player only moves itself
or am i dumb rn
xD
Are you using network transform or client network transform?
uhm idk where do i get the client network transform
Copy the code here
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform/#owner-authoritative-mode
Introduction
i am confused
About what exactly?
wdym copy the code
This script is the client network transform
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Multiplayer.Samples.Utilities.ClientAuthority
{
/// <summary>
/// Used for syncing a transform with client side changes. This includes host. Pure server as owner isn't supported by this. Please use NetworkTransform
/// for transforms that'll always be owned by the server.
/// </summary>
[DisallowMultipleComponent]
public class ClientNetworkTransform : NetworkTransform
{
/// <summary>
/// Used to determine who can write to this transform. Owner client only.
/// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
/// </summary>
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
}
where do put it
sorry i am new to networking
just replace the regular network transform with this one
yeah but where, like create a new script with this exact code?
i mean if i just create a script with this code i get "the script cannot be found" when adding it to an object
Is it giving any compiler errors?
no, no just if i add itr to an object
wait now it works kinda
I am currently trying to send data from C# Unity Client to Java Server and reverse.
i got my TcpClient in C# connected to my ServerSocket in Java. I tried so many things out now but i couldnt get the sending and reading to be working. I know that the Network Things are the same for every programming language and platform but it feels that C# does some things different.
// CSHARP
// Sending Data Length + Data
var data = "Hello World"
BinaryWriter.Write(data.Length);
BinaryWriter.Write(Encoding.UTF8.GetBytes(data));
// JAVA
// Receiving the Data
DataInputStream dataInputStream = new DataInputStream(inputStream);
System.out.println("Reading data...");
int dataLength = dataInputStream.readInt();
System.out.println("Received Data length: " + dataLength);
byte[] dataBytes = new byte[dataLength];
dataInputStream.readFully(dataBytes);
data = new String(dataBytes, StandardCharsets.UTF_8);
System.out.println("Received data: " + data);
Its getting stuck on the Java Server. The String i sent from C# is: "receivers=Server;keep-alive". I do not think the data size is correct for the length
Reading data...
Received Data length: 452984832
I know about dispose, close and all that best practices but i first wanna get it to working, then I can optimize that. If i dispose, flush or close binaryWriter it somehow also closes the stream, even when i set it to "leaveOpen = true"
I hope someone can tell me if i am using it completely wrong or any other solutions to it. I do not want a Unity Server to upload my whole game to an extra server additionally to the game. So i am trying to create a simple dynamic solution for my project like Photon, Nakama etc. where you just send Data to server or other clients and handle the rest in the Client mostly. That way I do not have to update the server when a new feature is added. Only when I wanna do something server authoritive
Have you used ServerSocket on Java and TcpClient on C# or anything else you would recommend that is working good?
How can I run multiple clients so I don't get rate limited when trying to join a lobby?
Make sure you switch the Authentication Profile
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/testing/testing_locally/#ugs-authentication
Guide covering the available workflows for testing multiplayer games locally.
do I need to do that before or after I do AuthenticationService.Instance.SignInAnonymouslyAsync();?
ah, before
Hey guys, Having a tiny issue with disabeling a camera
@sharp axle I belive its you who gave me the script but every time I launch the camera doesn't enable for the player
using UnityEngine;
using Unity.Netcode;
public class OwnerComponentManager : NetworkBehaviour
{
[SerializeField] private Camera _camera; // This is your camera, assign it in the prefab
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (!IsOwner) { return; } // ALL players will read this method, only player owner will execute past this line
_camera.enabled = true; // only enable YOUR PLAYER'S camera, all others will stay disabled
}
}
Is it giving an error message?
No
It unbinds the serialized field when it spawns a player
How would I force it to serialize field
yea I though so as well. I guess this is only way.
Make sure you are saving it in the prefab. As long as the camera is also part of the prefab then it should persist
I fixed it a little but now the host's camera doesn't exist
what do I do here
The object with the network behavior has to be enabled. The camera component can be disabled
When I try to use just the camera component It doesnt bind when it spawns
Oh it's only on the ones I don't care about
How do I deystroy
Do i Need to worry about this?
You don't want to destroy the object, just disable it
But how could I disable just the camera
I can't drag the cammera into the serialized feild
I used ServerSocket on Java and AsynchronousClient on C#
Hello everyone i have a problem on my Netcode skin change script and i cant fix it. Anyone can help me about it ?
When I apply the code below, meaning when I get the Mesh of the SkinnedMeshRenderer corresponding to the Tshirt from the Outfits dictionary (Top_Skin_3), there is no change, and I cannot achieve the desired result.
-First try
https://gdl.space/ufunesitot.cs
Even if I modify the code and assign the Mesh of the SkinnedMeshRenderer corresponding to the Tshirt from the Outfits dictionary (Top_Skin_3) to a newly opened Mesh variable named testMesh, and then apply it as below, there is still no change, and I cannot achieve the desired result.
-Second try
https://gdl.space/cirojudeyo.cs
However, if I manually assign the mesh (Top_Skin_3) to the testMesh variable from the inspector and then run the code, I get exactly the result I want. What could be the reason for this, and how can I overcome it? Run time mesh changes never work its just work when i add mesh in editor.
Can someone say whatโs the difference between isOwner and isLocalPlayer?
At runtime I believe you have to make a new mesh then assign it to the renderer.
There is only one local player object. But the client can own other objects like pets or bullets or weapons.
hey, i want to create a pick up and carry object script, but when i pick an object up and move, the object doesn't move with the player, without networking i change the parent to the holdTransform, however this doesn't work here, what is the best solution?
Check out how the Client Driven Sample works
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven/#client-side-object-detection-for-pickup-with-server-side-pickup-validation
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
Thanks
How I can do that?
looks complicated for what i just wanna do :')
Hello, i am trying to get into networking so i thought to rea and follow the documentation along a bit to get a basic idea of how everything works, but it seems like something doesnt work.
When i us [Rpc] the SendTo option doesnt appear, is the documentation outdated or am i just stupid? i think i installed everything correctly
Make sure you are updated to version 1.8.0. you probably have to install the package by name
Oh you're right, thank you, can i just download the new one or should i first remove my current version and redo the project?
Hey Evilotaku can you help me about my problem ?
You can just update it in place
Cool, it works, Thank you very much!
It would probably be easier to just use prefabs and swap them out with an RPC
I have lots of skin more then 500
I'm trying to use 'connection approval' but I can't seem to get it working.
How would I make the host set the password and spawn in?
Here I'm trying to start a server as a 'Host' but it does not spawn the 'player prefab'.
I've added some print statements to try to figure out what is going on.
If I get rid of line 19 [Where I connect the callback to the 'ApprovalCheck' method] it works.
I did manage I workaround but just want to know what the correct way of doing this is.
Hello, it's me again, sorry to bother you, I try to have a better understanding about all of this.
So you told me that if we want a shard with 3000 players it will need 10+ servers communicating with each other and for that a custom solution is more appropriate.
Will it be the case also if it was instanced ? for example instead of having 3000 players in the same shard, having 10 instances of 300 players so each server will be an instance
For example let's say you have an environment with 2 green houses, where you can change the color of houses, and you turn one house color to blue, the 3000 players will be in 10 different instances but they will get the same data environment which means they will all see the 1 green house and 1 blue house and if some one turn the green to red they will all see the red house.
In this scenario case, will it change something to have 3000 players in one instance instead of having them in 10 instances of 300 players.
Can a framework network solution do the job for the instances solution or both solutions will require a custom network solution
Do not ever send passwords in Connection Approval. That is not encrypted so it's send in clear text
It's still the same issue. The one server the change happened on will need to tell the other 9 servers of the change. Then those changes have to go out to 3k players. Instances in MMOs, are just private little zones that are meant to cut down on the number of players that are getting synced. Those dungeon instances would probably be in different servers themselves.
Oh ok, so that means that as soon as I want to share data with the 3k+ players I will need to have a custom solution.
And if I want a framework solution, I will have to not share the data with the players from the different servers. Which means that in this situation if I have 2 servers with 300 players each and I have player A in server A and player B in server B, if player A and B see 2 green house, and player B change 1 green house to blue, the player A won't see that change and will still see the 2 green house, there will be only the players in the server B that will see this change, this situation is suitable for a framework solution ?
Pretty much. But even getting to a 100 player per server is going to be a challenge. It's one of the reasons MMOs are so insanely expensive to run. Palworld is not even an MMO and it's costing the devs around $400k a month
[Netcode] [Client-1][PlayerPlaceHolder(Clone)] Server - client scene mismatch detected! Client-side scene handle (-53014) for scene (Game)has no associated server side (network) scene handle!
I get this error on the client and server i dont know why PlayerplaceHolder is an GameObject that sets the player up when the game switches scenes and the destroys itself with .Despawn() on the server
Yeah I read that it doesnโt encrypt but I new to this and just learning the basics.
My solution to set connectiondata for the host at the beginning of the host method.
You don't need to set the connection data for the host. The host doesn't call connection Approval since it automatically approves itself. Though that may have changed recently.
I think it has because it run the method and it gives me the error that appears in the console log.
I get something similar this usually happens when I am the host and disconnect. Then If I connect again the error messages go away. I don't know if its the same problem you are having.
With Netcode 1.8.0 the clients are just allowed to start a method and send that to everyone?
I know you can do [ClientRpc] but they say its legacy and we should be using [Rpc(sendTo.TARGET)]
What if I only want a method to run only if the server allows it?
You would SendTo.Server first run your checks there then have server SendTo.Clients
I didn't see a SendTo.Clients option
I used ClientsAndHost. but my problem is that the clients can just bypass this and call the method for everyone without the servers persmission
Yea. Either that or NotServer
If the users are decompiling your game and sending rouge RPCs you'll need a more robust anti cheat system
haha no I don't think so I'm just learning Netcode right now. I just didn't like the idea that a client can say "tell everyone I have a million dollars" and every client will accept it.
Also I just want to say a quick Thank you. You are always willing to help and answer my questions. You have made a difference in my Netcode learning journey.
Happy to help out! Clients can only send the RPCs you create for them. If you make an UpdateMoneyRPC() and let clients call it, thats on you. If it's serious(ie Real Money) there are UGS services like cloud code and economy that makes things that much more secure.
I'm using NetworkManager to link two devices together. When I try to connect to a server I make, I get this error, "Invalid network endpoint: Type Here:6666."
I've changed the port, ive used different ip addresses.
Any ideas?
See if this works. Try to go under the Unity Transport component and there is a section that reads 'Connection Data' expand that and make sure the listen address is the same as your address.
If the two things you want to connect are on the same computer you can just use 127.0.0.1
If the things are on the same local network you can use that devices local IP address usually starts with 192.168
Hope this works.
Hi, what's the best & easiest networking solution that also has free plans?
You are getting the wrong string for your IP address
Most of the frameworks out there are free to use. The connection services are usually what you are paying for. Unity Relay service has a very generous free tier. Steam P2P and Epic Online Services are free as well.
wait, i can host my game on steam and epic servers for free?
Yeah I meant connection services
I am thinking of using photon 2 atm
Not server hosting. Just the p2p relay connection.
Photon's free tier is only for testing. I think it's still only 20 CCU unless it's changed recently.
Yeah I am only planning to create a game just to have fun with my friends and not sell it
for someone in my situation what do you recommend?
if its less than 50 players then I would just stick with Unity relay service. It would be literally impossible to go beyond the free tier in that case
So I can host freely with it and it's easy to implement?
Do I have to port forward tho? Cause I use mobile hotspot and I can't port forward
Hello all , trying to setup netcode with relay for LAN connection here , but the client cant resolve the host destination
The whole point is get around port forwarding. And yeah, I think its pretty easy to set up
Although ,It worked fine when it was on the same machine
for more context , I have 0.0.0.0 as my server address
and checked AllowRemote Connections (i also tried without it)
Are you using the Relay Service?
yeah
Then you should be getting the server address from the Relay Allocation
yeah i did that in my client and server classes . however I didn't see any specification for the unity transport address
as for the the client code :
public async Task<bool> CreateClient(String joinCode)
{
try{
await StartUnityServices();
var alloc = await RelayService.Instance.JoinAllocationAsync(joinCode);
transport.SetClientRelayData(alloc.RelayServer.IpV4,
(ushort)alloc.RelayServer.Port,
alloc.AllocationIdBytes,
alloc.Key,
alloc.ConnectionData,
alloc.HostConnectionData);
return NetworkManager.Singleton.StartClient();
}catch(Exception e)
{
debugText.text+='\n'+e.Message;
}
return false;
}
I read some articles thst I might need a vpn ๐ข
I'll be trying this after the weekend ๐
hi, let me ask you something. when we make a multiplier game on this steam, we make the server that creates the lobby. can we make this a steam server server, so no one in the lobby will be a server.
What might be a good way to handle syncing abilities? I have a stat change buff with visual effects and something similar to a smoke grenade that affects the camera of players in its radius, the abilities themselves work fine in single player, but multiplayer gets confusing, is there a typical way abilities/spells/etc are often handled with multiplayer? Im using PUN2, though I dont think that should matter in this case - im thinking I would have to instead send a event of the ability ID to spawn it once on the network for everybody, rather than spawn the ability locally, but then every ability would probably need conditional logic, like "if caster/local apply stat change, otherwise show visuals" or "if caster/local, ignore collision checks, otherwise damage player" when spawned on the network? Would that mean every ability would need some kind of "network ability manager" script ontop of the actual ability logic? Would this even be a good approach?
@terse idol @sharp axle thank you both so much! I got it working!
Thats basically how I would do it. Send an RPC with the ability id. Leave it up to the ability manager to handle the effects locally
Ah ok, so it would be normal to setup conditions for each ability? For example a speed buff cast by Player A, would send a event for the ID, on receive, "if PlayerA, change client speed, else play visual effects"? Should that kind of logic be something ontop of the ability itself or a part of the ability's "OnActivate" logic?
could be either way really. check out some of Jason Wiemann's recent youtube videos on ability systems.
Interesting, I will check that out, I have an implementation of an ability system that works fine in single player, though everything usually gets more complicated with multiplayer - thanks for the suggestion
hey can anyone help me with photon PUN2 I want to just play with Integers like if i press the button the number is added which then gets updated to all the devices
public int SharedVal;
void CallSetting(int newVal)
{
PhotonView photonView = GetComponent<PhotonView>();
photonView.RPC("Setting", RPCTargets.All, newVal);
}
[PunRPC]
void Setting (int someValue)
{
SharedVal = someValue;
}
Something like that should work. Just a guess, on my phone
Does the unity relay service not use port forward and doesn't cost to host?
so it's free to host?
what am i doing wrong? i want to log my files inside the build folder because i want a log for each instance of the game (doing this tutorial https://docs-multiplayer.unity3d.com/netcode/1.5.2/tutorials/helloworld/#testing-the-command-line-helper)
Tutorial that explains creating a project, installing the Netcode for GameObjects package, and creating the basic components for your first networked game.
the default location only has these 2 files and i would like that, if i ran 1 instance of the server and 2 instances of the client, there were 3 files, one log for each instance
Solved: i had to change my command directory
im new to networking and im just trying to instantiate a host and a client, but for some reason i get this error.
if i understand the log correctly it says that the client connects, then gets a nullreference exeption and disconects because of it?
Have you set a default network prefab?
Yea i have, when i start the host it spawns, its only zhen i start a client that it doesnt
Iโm also learning so Im trying with the knowledge that I have. It looks like you might have clicked โconnection approvalโ in the network manager.
so i was trying to spawn objects as the client and not the server, but nothing happens, here is my code:
IEnumerator BuildSpaceShip(GameObject buildQueueItem)
{
//some code
spawned = false;
if(NetworkManager.Singleton.IsServer)
{
newShip = Instantiate(ship, shipSpawn.position, shipSpawn.rotation);
newShip.GetComponent<NetworkObject>().Spawn();
spawned = true;
}
else
{
SpawnShipServerRpc();
while (!spawned)
yield return null;
}
//rest of the code
}
[ServerRpc(RequireOwnership = false)]
void SpawnShipServerRpc()
{
newShip = Instantiate(ship, shipSpawn.position, shipSpawn.rotation);
newShip.GetComponent<NetworkObject>().Spawn();
spawned = true;
Debug.LogError("NON SERVER SPAWN");
}
even tho it's not server the server rpc is not working? the debug is not called
i am new to this so maybe i just miss something
im new to networking and im just trying
you were right, thank you!
Make sure you are using NetworkBehaviour
I think you can just do newShip.Spawn();
You can also spawn with ownership with newShip.SpawnWithOwnership(OwnerClientId);
Uhm the point is the spawning works for the host not not for the clients
This color only get updated on the host.
if client or host spawn in a ball.... the color is white on clients but is updated on host.
Yea. Onvaluechanged event does not trigger if the value has already been changed. So for the clients the ball color is already the updated value. So what you can do is just set the sprite renderer color to ballcolor.Value in your OnNetworkSpawn() if(!IsServer)
Just to see if I understand this... The OnEnable fucntion does not exits yet?
or why does it work for the host but not the client?
btw this is how I create the ball
how could i get the client id of the client who owns the player object inside the player object script?
I want to only send client rpcs to the client that owns the player from the server
and not any others
here u need to use rpc param
I tried updating hostId using https://services.docs.unity.com/lobby/v1/index.html#tag/Lobby/operation/updateLobby
... and Lobby's host permissions seem to change properly, but stuff like https://docs-multiplayer.unity3d.com/netcode/current/components/networkmanager/ doesn't seem to have updated values for stuff like NetworkManager.Singleton.IsHost ... is changing the hostId to a different Player's Id supported? I seem to be able to pass the hostId to another player, then everything in BossRoom kind'a breaks until I transfer the host back to the original host (from the new host)
The NetworkManager is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
It's not that OnEnable isn't run, it's that the change event doesn't fire because the variable hasn't changed yet. On the clients variable starts with the updated color.
You can not change host in NGO. The Lobby service is a separate thing.
I'm having a hard time taking this in.
I spawn the ball and change color on host(server) and its appears correct on the host(server).
Then I Spawn the ball to the network and clients receive this ball. If they are receiving the updated ball why doesn't the color reflect that?
I'm sorry if I'm not understanding.
I'm using VContainer for Dependency Injection in my game. Has anyone knowledge how I can register a NGO spawned GameObject at runtime on Client to the LifetimeScope?
This is the code from the tutorial I'm following and the only difference is that he uses NetworkStart() and I use OnNetworkSpawn() but his color updates for both host and client. but mine only for host.
DI containers and dynamically spawned objects are not really playing well with each other.
This is what I assume meanwhile ๐ But how you handle this in the common way? Singletons? Scriptable Events? When an object is spawned at Client I've no knowledge or references to the managers which I use in the common approach at instantiation, while those are server restricted ...
This is an old tutorial or using an old version NGO. In the server check in your OnNetworkSpawn set ballRenderer.color = ballcolour.Value
Check out the BossRoom Sample. I believe they use VContainer.
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture/#dependency-injection
Boss Room is a fully functional co-op multiplayer RPG made with Unity Netcode. It's an educational sample designed to showcase typical Netcode patterns often featured in similar multiplayer games. Players work together to fight Imps and a boss using a click-to-move control model.
@sharp axle I know, this is the reason why I started use VContainer. But based on their kind of game, there is no requirement to register spawned objects to inject dependencies.
Dang it, ok. So uhh, I wonder if Boss Room will ever be updated with Host Migration implemented?
https://docs.unity.com/ugs/manual/lobby/manual/host-migration
Er, I guess NGO, and Boss Room
Is there a way to have a gameobject as a paramtere in clientrpc?
No, but you can pass a network identity of a gameobject
Wdym by network identity? Like network object or..?
Depends on the framework youโre using what itโs called
NGO
You want to use network object reference
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#networkobjectreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
exampels use serverrpc, i assume this works with clientrpc aswell?
Yes, it will work with any RPC and network variable as well
Nice
You just have to make sure the network object has been spawned first
Hey I have encountered some issues. I used the Netcode for game objects for a bit and started with Lobbies. I have a script and a scene in which one person should be able to host and another one should be able to join said lobby.
But when both are in there I don't know how to start. I switched scenes but no player spawns. Its 4 am and I'm just down. If anybody could help me, that would be amazing.
using System.Collections.Generic;
using Unity.Services.Lobbies;
using Unity.Services.Lobbies.Models;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Unity.Netcode;
using UnityEngine.SceneManagement;
public class MainMenuController : NetworkBehaviour
{
public NetworkManager networkManager;
[Header("Host UI Elements")]
[SerializeField] private Button hostButton;
[SerializeField] private TMP_InputField HostCode;
[Space(1)]
[Header("Join UI Elements")]
[SerializeField] private Button joinButton;
[SerializeField] private TMP_InputField JoinCode;
[Space(30)]
[SerializeField] private TMP_Text ErrorMessage;
// Start is called before the first frame update
void Start()
{
hostButton.onClick.AddListener(CreateLobby);
joinButton.onClick.AddListener(JoinLobby);
}
private async void CreateLobby()
{
Debug.Log("Request Lobby-Host: " + HostCode.text);
try
{
string lobbyname = "GameLobby";
int maxPlayers = 2;
Lobby lobby = await LobbyService.Instance.CreateLobbyAsync(lobbyname, maxPlayers);
Debug.Log("Lobby created with id: " + lobby.Id + " Lobby code: " + " and the Playermax of: " + lobby.MaxPlayers);
ErrorMessage.text = "Lobby created with id: " + lobby.Id + " and the Playermax of: " + lobby.AvailableSlots;
}
catch (LobbyServiceException e)
{
Debug.LogError("Error creating lobby: " + e.Message);
ErrorMessage.text = "Error creating lobby: " + e.Message;
}
}
private async void JoinLobby()
{
Debug.Log("Request Lobby-Join: " + JoinCode.text);
try
{
Lobby lobby = await LobbyService.Instance.QuickJoinLobbyAsync();
Debug.Log("JoinedLobby");
ErrorMessage.text = "Lobby joined with id: " + lobby.Id + " and the Space for: " + lobby.AvailableSlots;
if(lobby.AvailableSlots == 0)
{
StartGame();
}
}
catch (LobbyServiceException e)
{
Debug.LogError("Error joining lobby: " + e.Message);
ErrorMessage.text = "Error joining lobby: " + e.Message;
}
}
public void StartGame()
{
SceneManager.LoadSceneAsync("Lobby");
}
}
Hey. My goal is to connect players who are in the same network, ideally connected to the same wifi. I'm using Netcode (and the fallback option would be Unity Relay). Is there a way to achieve this and if yes, where to find how?
DM me if you are from Europe, South America, USA, Canada PLEASE i want to try my online app
You also need to setup a Relay for the players to join. The host will save the relay code in the Lobby Data. The other clients will grab that code from the lobby and then join the host's relay.
If you are typing in the IP address then you can use SetConnectionData()
https://docs-multiplayer.unity3d.com/netcode/current/components/networkmanager/#connecting
Or you can try to use Network Discovery
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
Community contributions to Unity Multiplayer Networking products and services. - Unity-Technologies/multiplayer-community-contributions
The NetworkManager is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
I'm not very experienced with coding in C# but I'm trying to use Netcode For Gameobjects and having difficulty with spawning the client to the server. I had it working before but then basically restarted and I don't know what I did differently and my line: NetworkManager.Singleton.StartClient(); isn't joining the host. I'm 99% sure that the ip is set correctly and it's not giving me any errors
I have an issue with OnNetworkSpawn() method using Unity's Netcode for Gameobjects package.
This is my method to spawn a projectile:
public void CreateProjectileRpc(Vector3 spawnPosition, Vector2 forceDirection, float force)
{
NetworkObject projectileObject = ObjectPool.Instance.GetPoolObject(0);
projectileObject.Spawn(false);
ActivateProjectileObjectRpc(projectileObject, spawnPosition, forceDirection, force);
}
Then in my projectile script overrides OnNetworkSpawn() like this:
{
Debug.Log("Spawned");
if(IsServer) StartCoroutine(WaitToDisable());
}
I get no log in the console nor does the Coroutine start. Am I using OnNetworkSpawn incorrectly? (Also the projectile does spawn for both host and clients, but this method does not run unfortunately)
Did they change how ClientDisconnect works? I used to be able to check if the ulong id was 0, and if so, that meant that the server shutdown/kicked the client, but now it doesn't seem to work..
I have an issue with OnNetworkSpawn()
If I'm not mistaken, ClientDisconnect ID might be the ID of what client was disconnected. But I'm not 100% on that, that's just always what I assumed it was
And 0 from my experience in the ID of the host typically
I see
So how should I detect when the client is disconnected by the server and not the client itself?
Since when the server shutdown or whatever the client is frozen, and I wanna send them back to the menu
Both the server and client will be notified on the event NetworkManager.OnClientDisconnectCallback which I assume you're using you can simply switch scenes. I see what you're saying how you want to check if the ID is zero and then kick the clients to the main menu. When the server disconnects, clients will eventually disconnect from the server due to ping timeout, but I believe you could manually disconnect them.
If you run a method on the server side to disconnect the clients before the server fully shuts down, and then have the clients return the main menu when they disconnect, that might be the best way to do it.
This is assuming OnClientDisconnectCallback calls before the client actually disconnects
{
// Note: If a client invokes this method, it will throw an exception.
NetworkManager.DisconnectClient(player.OwnerClientId);
}```
Basically call this from the server for all of the connected clients
Then have the client return to a main menu scene when disconnected
But if the server disconnects them manually before shutting down, how will it know that the server kicked them?
I may be misunderstanding what you're trying to accomplish. I'm proposing that the server is the only one that calls the DisconnectPlayer method.
If you wanted to, you can use a "NotMe" Rpc call that calls to all clients except the server to tell them that the server is disconnecting them. Though, I would assume it would be the same outcome if you wanted to change scenes in the method that is called from the event NetworkManager.OnClientDisconnectCallback
Since the clients are being disconnected manually, they will trigger the NetworkManager.OnClientDisconnectCallback event which is where you can handle the scene changing
OnClientDisconnectCallback is called tho when the server OR client forces a disconnect tho, right?
if so, how can i differentiate between which side forced the disconnect?
just to clarify, my issue is not when i forcibly disconnect any clients via the server. in fact, haven't done anything like that yet
my main issue rn is that when the server closes, the client disconnects but it's still in the other scene. im trying to find a way to detect when the client disconnects due to the server kicking it out so i can return to the main menu
In 1.8, Shutdown() has been changed a bit.
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/pull/2789
there is also new event called NetworkManager.OnConnectionEvent that might also use instead of OnClientDisconnectedCallback
How do I use this new connection event? Are there docs?
how to make a network object IsActive(false)?
does Webgl support hosting for Netcode for Gameobjects? The documentation says it is supported but I still get the error "Unity.framework.js.br:10 Exception: WebGL as a server is not supported by Unity Transport, outside the Editor." when trying to host on a webgl build
are you using websockets?
I have NGO at 1.6.0 and unity transport at 2.1.0
if you mean checking "Use Web Sockets" in unity transport then yes
interesting. my project works with webgl and NGO with ws
but I'm also on a later version,
How do I use this new connection event?
i just built for webgl then pressed a button that runs "NetworkManager.Singleton.StartHost();"
and that error came up
You won't be able to run WebGL as host without using the Relay Service
ohhhh
soo before i commit to this
is it possble to have a webgl game with a host that allows clients to join over the internet with relay?
no dedicated server needed?
yes
ok thanks
wait on the documentation for unity transport it says "Note: It is not possible to start a server in a WebGL player even with the WebSocketNetworkInterface because the player is still constrained by the browser capabilities. Web browsers to date do not permit applications to open sockets for incoming connections and trying to do so will most likely throw an exception."
does that mean no webgl player can act as a host?
Not on its own. The relay server acts as a go between for all the clients.
so the webgl "host" still acts like the server for rpcs, but relay is what actually sends packets out?
Right. Technically the Relay is a unity hosted server.
ahh thanks that makes sense
is there any major differences between setting up a normal relay vs one with websockets?
like does it require some external plugin or messing around with java?
No, just check the box then when you create the relay you use wss instead of dlts
aii thank you ๐
What is the proper way to disconnect from Relay, Lobby and Netcode for gameobjects? Just to go to the start state before anything was done? I only find a few things on google that don't really work for me haha
I get an http not found 4004 error (I thought, I'll check what it was exactly in a few hours)
You just call NetworkManager.Shutdown()
And lobby and relay quits automatically as well then? Hmm I'll try, thanks!
Not from my experience
I figured it out, relay disconnects automatically (I think, I dont have troubles with it at least) and for lobby I called RemovePlayerAsync
I just had the problem that I didn't stop my LobbyManager from trying to send heartbeats and polling for updates, but because I left the lobby there was nothing to send it to
Yea. the lobby will persist between game sessions so you can keep the party together
It's weird, because when I change scenes (I'm using NetworkManager.Singleton.SceneManager.LoadScene() for that) The lobby does dissapear, without me asking it to.. But everything I find online says this shouldn't happen ๐
It will probably be another problem like before that comes down to just a boolean thats not changed or something, but it is frustrating haha
Hi, I am kinda very fresh to Netcode. But have used Mirror API and Photon PUN in past. My Querry is, can we use Netcode to organise multiplayer server /client side game at our own server without using any unity paide/free services regardng multiplayer ?
Yes
Itโs just like mirror in that regard.
If you stop sending the heartbeat the lobby will die
I keep doing that, but when I change my scene, directly afterwards my lobbymanager doesn't recognise the player as host or client anymore.. so I assume the lobby in its entirety just gets deleted when I change the scene
And normally your lobby only needs a heartbeat every 30 seconds no?
But oh well I'm just gonna focus on something different, I'll figure it out when I look at it with a fresh pair of eyes
Ok so every error I've gotten I was able to fix except this one.
It happens when I disconnect as a host or client
When I double click the error it opens this script and points me to line 159.
Any idea or lead to how I could fix this?
Does netcode for gameobjects support wss? Does checking the "use encryption" box switch to wss?
Call shutdown last there
You'll need to be using Unity Transport 2.0+ in order to use web sockets.
Yes i have a working webgl build using websockets. Problem is i cant connect using the ws protocol if the webpage is served via https, i need wss.
I reverted back to From Multiplayer Tools 2.1.0 to Multiplayer Tools 2.0.0-pre.5 and I stopped getting that error. But let me change it back and try to do your suggestion.
Update: I tried to move shutdown to the end on 2.1.0 and it gave me the error still. So looks like ill be sticking to the prelease for now.
I couldnt find any mention of wss in the docs
Check the pinned message here. You find the Unity Netcode discord link. We have a Unity Transport channel that has lots of discussion on connecting to secure sites.
Im not too familiar with WebGL but I'm pretty sure you just need to set the NetworkSettings.WithSecureServerParameters
https://docs-multiplayer.unity3d.com/transport/current/secure-connection/#create-a-secure-server
You can configure the Unity Transport package to encrypt the connection between the server and clients while ensuring the authenticity of both.
Ok i guess I'll just have to try it. Thanks for the links!
When you run NetworkManager.Singleton.StartClient(); with no host or server started, Netcode will start a networkManger as a client.
Why is this? what is the point if there is no server running?
how did you connect to the websocket?
i have a webgl build with relay
but when starting a host it keeps displaying the error message "Unity.framework.js.br:10 WebSocket connection to 'wss://failed: " and then it exits after a few moments
public async void StartHost()
{
await CreateRelay();
}
private async void Start()
{
await UnityServices.InitializeAsync();
AuthenticationService.Instance.SignedIn += () =>
{
Debug.Log(" signed in " + AuthenticationService.Instance.PlayerId);
};
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
public async Task<string> CreateRelay()
{
try
{
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(3);
string joincode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
var unityTransport = NetworkManager.Singleton.GetComponent<UnityTransport>();
unityTransport.SetRelayServerData(new RelayServerData(allocation, "wss"));
unityTransport.UseWebSockets = true;
unityTransport.SetHostRelayData
(
allocation.RelayServer.IpV4,
(ushort)allocation.RelayServer.Port,
allocation.AllocationIdBytes,
allocation.Key,
allocation.ConnectionData,
true
);
NetworkManager.Singleton.StartHost();
return joincode;
}
catch (RelayServiceException e)
{
Debug.Log(e);
return null;
}
}
How can I check to see if a host/server has been started before calling StartClient?
There is no way to know if a server is running until you try to connect to it
Don't use SetHostRelayData(). All you need is SetRelayServerData()
How would I stop the client from starting a NetworkManager?
What do you mean? StartClient() will just return false if there is no server to connect to.
But its start this.
its dosn't let the client in but it does start the client. So when I go back and connect as host, it doesn't let me because the above is already active.
this means the client is connected
Yeah but to what? There is no host/server started.
Are you sure? It won't connect to nothing
yeah. I have stripped down the client button so onclick triggers this function.
sure. But there is a server running on whatever ip address the Transport is set to.
It worked ๐๐๐๐๐
Thank you
But when I start it up and connect as host everything works as expected.
wouldn't it give me an error that there can only be one host if that was the case?
How would I find out if a server is indeed running on that address?
if a client connects then the server is still running.
I have uncommented everything except for this line.
You might have to call Shutdown() if StartClient() returns false. I'm not sure why client stays running if it doesn't connect
It returns true....
funny enough when I click client it still connect. then I click client a second time and then it disconnects.
I'm calling it a day.
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(6, region);
i am trying to connect to the North America East relay server
but when region is set to "us-region-1", it says no region of that name is found
what is the correction string to connect to us east?
I guess you need to check for IsConnectedClient
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.8/api/Unity.Netcode.NetworkManager.IsConnectedClient.html#Unity_Netcode_NetworkManager_IsConnectedClient
Looks like it's "us-east1"
i just made a dynamic dropdown that finds all of the servers available and lets the user choose
but thank you
This worked but now I can't connect to the server or host.
how do i make a super simple way to play a project with my friends together
m8b a space there is missing
The easiest way is to use the Relay service. Give your friends the join code and they will be able connect to your game
Try putting await before StartClient()
How does websockets handle unreliable rpcs? Do they still resend packets and order them?
Hi everyone, I have some problems starting the server on UGS on Game Server Hosting. The build files are correct, but when I try to start it, it show me this Error:
"Request ID: 0592c74c-3365-479e-8331-7561d2c59260.
An error occurred while starting the server. Try checking the server events for more information. Failed dependency: failed action"
I looked at the events, and the only thing I found related is this:
"Server having issues (Query didn't respond or responded incorrectly [DOWN]) for 120 seconds (Subtracted 0 time(s))"
I want to know how I have to configurate the IP and the PORT on my Scripts and my NetworkManager and Unity Transport.
I attached the ServerStartUp Script
Thank you so much for your time
how do i get a network prefab by Id (not a spawned one)
Hi. I'm doing netcode gameobject but I can't add my player to network prefab list. And yes I have player as prefab
You need to make the Server Query Handler is getting updated
https://docs.unity.com/ugs/en-us/manual/game-server-hosting/manual/sdk/game-server-sdk-for-unity#Start_server_query_handler
ook, thanks a lot!
And every time the network object is destroyed
What is the problem, you can't see the prefabs list object in the inspector?
in theory, you should drag the prefab to this list.
Yes and when I start game the network object just destroy
Well I can't
so, the problem is not to add the player
Yes I can't add it into prefabs list and my network object destroy on game start
I'm sorry, i cant hep u
No problem
Make sure the player has a network object
It have
And you can't add it to the list? The list is the scriptable object.
Yes I can't. There is only some DefaultPrefab.... as you can see in the screenshot
uh but i want to tell the server to spawn a network prefab from the list on the network manager (it's always a different one so i can't use a reference)
yes they have one before spawning i checked
I'll try older versions
now it works
I have 1.2.0
But it destroy on every game launch
I quit doing this
You can grab it by index directly from the prefab list
#archived-networking message
Yes. you have to open the Default Prefab List and place the player in there
how i get the index of the object?
In Photon Fusion, why does networkRunner.SessionInfo.MaxPlayers default to 10? This doesn't appear to be documented anywhere
Man. I'm saying you I can't do it. Anyway I quiting netcode because it's not functional as I thought. I have seen multiple tutorials but they have't same problem as me. I don't know
I've just been manually setting the index. I only have a few prefabs I'm spawning.
๐ซ
But its still just a list. You can search it with Linq if you really need to
i think it worked :) thx
Thanks a lot
I set Network Discovery up and it's working, now I'm just wondering if I need to worry about the port setting? Can I just leave the default 47777?
And just for my understanding: It wouldn't be possible to have some clients connect through Relay and some others through the local network, right?
You don't have to worry about the port. But I don't know about the 2nd part. I want to say that it would require setting up 2 different transports but I've never tried that
anyone please help me, i am having an issue where the player manager spawns on scene 0 even before an scene has been loaded, like when i start laoding a scene the playermanager spawns already and then spawns the player
it just resets the ball and player pos 50% of the time but the velicity gets set to zero everytime and a counter gos up from where the function gets called the fuction gets called in ontriggerenter and im using physics.simulate and physics get controlled with script i think its a network issue because why would it do everything except set the pos when the ball pos gets reseted the player pos gets also reseted```cs
private void ResetPos()
{
ballRb.velocity = Vector3.zero;
ballRb.angularVelocity = Vector3.zero;
ball.transform.rotation = Quaternion.identity;
int i = 0;
int l = 0;
int k = 0;
foreach (GameObject player in players)
{
if (i == 0)
{
player.transform.position = spawnPoints1[l].transform.position;
l++;
i = 1;
}
else
{
player.transform.position = spawnPoints2[k].transform.position;
k++;
i = 0;
}
}
ball.transform.position = Vector3.zero;
}```
Is there a question in here somewhere?
yeah why doesnt it set the pos to zero
why are you setting the position with the Transform
ballRb.position = Vector3.zero;
you can put that right up top with the other stuff
same thing with rotation
use the Rigidbody
ballRb.rotation = Quaternion.identity;
because its a gamobject i have to do .transfrom.
If this is using a network Transform and network rigidbody then youll need to make sure that only the server is running this code.
found out it works if i get the rigedbody and set the position there dont know why
try { CreateLobbyOptions lobbyOptions = new CreateLobbyOptions(); lobbyOptions.IsPrivate = false; lobbyOptions.Data = new Dictionary<string, DataObject>() { { "JoinCode", new DataObject(visibility: DataObject.VisibilityOptions.Public, value: m_JoinCode) } }; Lobby lobby = await Lobbies.Instance.CreateLobbyAsync("My Lobby", c_MaxConnections, lobbyOptions); m_LobbyId = lobby.Id; HostSingleton.MyInstance.StartCoroutine(HeartbeatLobby(m_HearthBeatSeconds)); } catch (LobbyServiceException ex) { Debug.Log(ex); return; }
I create here a lobby. And I try to join the lobby:
try { Lobby joiningLobby = await Lobbies.Instance.JoinLobbyByIdAsync(lobby.Id); string joinCode = joiningLobby.Data["JoinCode"].Value; Debug.Log(joinCode); //await ClientSingleton.MyInstance.MyClientManager.StartClientAsync(joinCode); } catch(LobbyServiceException e) { Debug.LogException(e); }
And I always get HttpException`1: (409) HTTP/1.1 409 Conflict. Whats the problem here ?
Looks like Conflict is usually when you try to join a lobby you are already part of. Are you having the host try to join the lobby it just created?
In netcode, do server rpc's need to be guarded with if (IsServer)?
maybe, depends on your architecture, likely if you are running in host mode
i have an in-scene NetworkObject + NetworkBehavior, that has OnNetworkSpawn overridden. For some reason though it only is called on the host, and not on the client when the connection is establiushed. it is not disabled or anything. any ideas why?
maybe its not actually being spawned on the client?
it is an in-scene networkbehavior (it is not dynamically spawned, it is already there before the connection is made)
Not really. ServerRpcs are only ever run on the server. Clients can't run them in any case. The host is also a server. In 1.8 there is a new [RPC] attribute that unifies clientrpc and serverRPC. It's worth looking into
Using Photon Networking
Why does it Put all players in different Lobbys/Rooms
using UnityEngine;
using Photon.Pun;
public class RoomManager : MonoBehaviourPunCallbacks
{
public GameObject player;
[Space]
public Transform spawnPoint;
private void Start()
{
Debug.Log("Connecting");
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
base.OnConnectedToMaster();
Debug.Log("Connected to a server");
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
base.OnJoinedLobby();
PhotonNetwork.JoinOrCreateRoom("test", null, null);
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
Debug.Log("We're now connected and in a room");
GameObject _player = PhotonNetwork.Instantiate(player.name, spawnPoint.position, Quaternion.identity);
_player.GetComponent<PlayerSetup>().IsLocalPlayer();
}
}```
there is a difference between present in the scene and "spawned" though, you can have an unspawned instance in the scene (though that probably shouldn't be the case on the client!). worth checking the inspector on the client to check that it's showing the right owner ID etc indicating it's actually spawned
can someone explain to me what this asset is that i found on unity's asset store? https://assetstore.unity.com/packages/tools/network/fish-net-networking-evolved-207815#content
it looks like someone is giving "free" webserver support through their own platform, but the more i read the more it seems kinda sus or like false advertising.
the video seems like its showcasing something entirely different and the names of the stuff in the packages seems like its more like optimization stuff?
Fishnet is just a networking framework. It lets you build multiplayer games. Some will offer a relay service to help with connections. Most will allow you self host as well
Using Pun 2 / Photon But when i test both players are there But only the local player has a Gun like the Other player gun is not syncing like showing
I have the setup in provided image above, But i simply want it to display the arms and gun for Each player but making only local player be able to control there gun!
Set Main Camera Active false so I can set it true for Only Local player but How can I replicate the gun for Each player like so it shows the direction and everything else?
when using netcode, what do i need to consider when choosing between soft synchronization or prefab synchronization? it seems like a pretty important choice, yet the documentation kinda glosses over it.
Networking setup question
hey, I need steam networking lib that will allow me to create lobby and send packets, nothing more, which one should I choose and which one is most supported? I see fizzy steamworks but it's weird