Whether a library supports N players depends on what you do with them. There is no absolute limit in any library, only relative ones. Mirror supports interest management out of the box. Depending on your game it might be enough or require custom implementation, but then you could use any other library again. Experience of most mmo projects seems to be that you need to go fully custom.
#archived-networking
1 messages · Page 13 of 1
Unity and Photon built a 200 player battle royale demo.
If you need players moving between servers that's a whole different beast
How network for entities server side works? Is one of players host?
It works just like regular NGO. You can have a player host or a dedicated server
Hey, i want to implement spine ik, but seems like only host can can send info about target point
public Transform spineConstrainPoint;
public Transform spineConstrainTarget;
private void Update()
{
SetSpineConstClientRpc(spineConstrainPoint.position);
}
[ClientRpc]
public void SetSpineConstClientRpc(Vector3 pos)
{
spineConstrainTarget.position = pos;
}
here's my code
anyone know how to fix this?
Yea, only the host/server can send clientRPCs. Just putting a Client Network Transform on the IK Target is the easiest solution here
yeah it worked, thanks a lot
Hey folks. Can someone help understand the Network Prefabs List in the Network Manager? Previously I had a list of prefabs and it was working, but after updating I'm not sure how to use this list. I've created a list in my repo and have assigned it in my Network Manager prefab, but every time I host / server / client it appears to clear out the list. The warning that's being thrown is:
[Netcode] Runtime Network Prefabs was not empty at initialization time. Network Prefab registrations made before initialization will be replaced by NetworkPrefabsList.
How is this list supposed to be used?
Yea. in 1.4 you should be adding your prefabs to that scriptable object instead of in the Network Manager itself
How do I assign the list of prefabs then? Do I need to script it somewhere? 🤔
The DefaultNetworkPrefabs is getting cleared out due to the above warning so even though I have my prefabs in the scriptable object the Network Manager isn't using the list
you should be able to duplicate the SO then add that to the network manager
Hm.. I have it setup that way but something else may be going wrong. The issue I'm trying to fix is when I connect clients to a host / server it's saying:
[Netcode] NetworkConfig mismatch. The configuration between the server and client does not match
why dead body here is launched to the space? I dont apply any force to it and colliders dont overlap
did you saved?
Ah, I think I needed to create a new list and not use the Default. I just realized the DefaultNetworkPrefabs was set in my main editor's Network Manager but my clone's editor was empty
Thanks!
Hello, where can I have basic to advanced tutorial about networking in unity DOTS?
Hi all. I have a multiplayer pokemon/card game, with each "Pokemon, "PokeMove", "UIPokeMove" as a class. A value of a card can have dynamic stats and registers events, hence the class. A player has multiple pokemon. UIPokeMove has reference to PokeMove
Now, is it advisable to use class? At least for PokeMove and UIPokeMove. I'm thinking of changing them to struct. Just checking if there's a certain "standard" on making multiplayer card games/UICards
1 of the reason is bcoz clients don't maintain references between these
The references are handy on server side when doing operations. So i guess client side should always re-connect? Or if all use struct then gotta keep several idIndex and always find the needed instance thru a getter?
I think most people are waiting for it to come out of preview
I keep all my data in scriptable objects. This includes cards and abilities. I use the Hashcode() as the object's id
Yes already doing this. But i'm talking about the instance of the card itself
So i guess the issue is the pokemon/pokeMove instances are kept in multiple places
Some solution:
- Always only keep 1 master "container" of the instances. In this case in Player.pokemonComponent.pokemons list. And for PokeMoves, in Pokemon.moves list
- Pokemon and PokeMove gotta have enough info in the struct to find the master container. Maybe ultimately a method that can take care of updating the master container, no matter where/who changes the pokemon struct instance?
struct Pokemon
int playerId;
int pokeIndex;
public void AssignToList()
{
Player player = Player.Get(playerId);
player.pokemons[pokeIndex] = this;
}
Is this kinda practice uhh.. common?
Dunno how common it is, but that's basically how I do it.
Can someone please help me in setting up unity netcode
A very basic setup
I can't seem to figure out what I am doing wrong
If anyone can help me do a basic setup for netcode
What difference between netcode for gameobjects and network for entities what better for first person view multiplayer shooter?
One is for GameObjects, one is for Entities, are you using DOTS?
I would check out the Youtube videos by Code Monkey and SamYam. Those two are probably the most up to date tutorials out there
I am about to use dots
Right, so you'd want Netcode for Entities
DOTs is a lot to wrap your head around. Its a totally different programming paradigm for object oriented.
I was surprised when they said DOTS, but we are in Networking so maybe they're a more advanced user
Or they have no idea what DOTS is
To be fair, you don't have to all in on Dots. A hybrid approach is currently recommended.
I did
I am having so much problem with the rpcs
If anyone could help me one on one
I would really appreciate it
So, network for entities is for DOTS and NGO is for object oriented system, that's the difference right?
That's correct. Netcode Entities also has Client Prediction built in by default
Thanks for the answer
Is there limitation for number of players with entities?
Eventually you'll find the limits of the hardware and software, the number depends on many factors
You'll reach bandwidth and hardware limits way before you hit any theoretical software limits
What is way to get best tick rate and lowest ping and delays? What about to build master server using C++ it is faster I heard
That all depends on your game and your server hosting provider
Hi everyone, I'm new to unity netcode and I found the tutorial about how to spawn an object seems not clear enough to solve my problem. I'm currently using netcode 1.3.1 in which the network prefabs are already replaced by network prefabs list. According to the history message in this channel earlier, I think I already put the network prefabs into the list and added to network manager. But the problem for me is that how to access that NetworkPrefab I want to spawn in script code and Inisantiate() it. Just directly access it with prefab name doesn't work. Here is my code:
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
public class EntryManager : MonoBehaviour
{
[SerializeField] private Transform Infantry;
......
static void SpawnButtons()
{
if (GUILayout.Button("Spawn"))
{
Instantiate(Infantry);
}
}
}
This throws an error called An object reference is required for the non-static field, method, or property 'EntryManager.Infantry'
Changing the static property of this prefab doesn't solve the problem, I'm wondering what else I can do to solve this?
Indeed I'm just not sure how to properly access the networkPrefab, failed to find the doc on this, maybe I missed something.
hey guys i started to work on a simple netcode project ( i am fairly new )
and got a question i tried to use server rpc and it doesn't change the value that i want in server
public class PlayerNetwork : NetworkBehaviour
{
private NetworkVariable<bool> gamestart = new NetworkVariable<bool>(false);
private NetworkVariable<bool> wait_for_client = new NetworkVariable<bool>(false);
public override void OnNetworkSpawn()
{
gamestart.OnValueChanged += (bool oldValue, bool newValue)=>{
Debug.Log("let's change gamestart from: "+oldValue+" to: "+newValue);
};
wait_for_client.OnValueChanged += (bool oldValue, bool newValue) => {
Debug.Log("let's change wait_for_client from: " + oldValue + " to: " + newValue);
};
}
void Update()
{
if (!IsOwner) return;
if (IsHost)
{
if (!gamestart.Value && !wait_for_client.Value)
{
wait_for_client.Value=true;
}
}else if (IsClient)
{
if (!gamestart.Value)
{
startGameServerRPC();
}
}
if (Input.GetKeyDown(KeyCode.T))
{
Debug.Log("ishost: " + IsHost);
Debug.Log("game started: " + gamestart.Value);
Debug.Log("wait_for_client: " + wait_for_client.Value);
if (gamestart.Value)
{
Debug.Log("game has been started");
}
else if (wait_for_client.Value)
{
Debug.Log("waiting for the client");
}
}
}
[ServerRpc]
private void startGameServerRPC()
{
Debug.Log(OwnerClientId);
Debug.Log("runs in server");
this.gamestart.Value = true;
this.wait_for_client.Value = false;
}
}```
can anybody help me why the value doesn't change when i start my client after that i have started my host
How Do I Make Your Mic High Pitched For Others And Others Mic Low Pitched For You Using Photon Voice And Stuff
The function can't be static. If you want spawn something with a button press then you'll have to send a serverRPC to the server. You should be able to send the index of the prefab list SO and have the server spawn it
Every player has their set of network variables. This code is only changing them on the host player
the behavior of the code is that it changes it for client only
if i log it inside the rpc it says it has been changed, however when it finishes the method everything is back to before
ok then can you guide me how to have a global sync variable between all clients and server
You'll need a game manager with those variables on it
hmm and everybody reads the variables of of that file?
that's briliant thank you i worked it around like this:
if (!gamestart && !wait_for_client)
{
wait_for_client = true;
}
else if (!gamestart && wait_for_client) {
var players = NetworkManager.Singleton.ConnectedClientsList;
if (players.Count == 2)
{
gamestart = true;
wait_for_client = false;
}
}
if (wait_for_client)
{
Debug.Log("maybe add StartCoroutine!");
}
}
else if (IsClient)
{
if (!gamestart)
{
gamestart = true;
wait_for_client = false;
}
}
thanks for the guidance 🙏
How would i get about doing multiplayer damage when using Steamworks Peer to Peer ?
The movement is done by the player themselfs and then synced by Steamworks/Mirror, but i dont know how to go about the damage.
I dont want the Player just to decide that hey i hit you for that amount of damage
but rather just the shooter decides with a hitray yes i hit with that weapon and the hit player says hey i got hit by that, time to take that damage
but i dont know how to do that reliable over steamworks
Hello everyone!
Currerntly I am using Netcode for GameObjects to test Multiplayer for my game, problem is that the Host can move and look all sides while the client can't move at all, and can only look up and down.
Any way to fix that?
Hey you whats happening is that you are using a server authoritive network transform, so only the server/host can set the positiom of an object. One way to fix it is setting the positions in a serverrpc, which would come with a sicnificat latency problem, but could make sense in vertain games, another way would be to switch to a client authorative network transform, hoe to do that is mentioned in the docs
Yeah, that did the trick. I just downloaded the Multiplayer Utility samples and used the Client Network Transform
Thanks alot, I did figured out the problem of static function, but how could I access the prefablist in code? Didn't find any docs on this, any reference code or document on this part?
NetworkPrefab hash was not found! In-Scene placed NetworkObject soft synchronization failure for Hash: 2779022876!
Failed to spawn NetworkObject for Hash 2779022876.
OverflowException: Reading past the end of the buffer
Failed to spawn NetworkObject for Hash 2779022876.
OverflowException: Reading past the end of the buffer
getting these three errors in unity netcode, can anyone help?
!code
Posting code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
if (Input.GetKeyDown(KeyCode.Alpha1)) { photonView.RPC("Equip", RpcTarget.All, 0); }
[PunRPC]
void Equip(int ind){
if (currentWeapon != null) Destroy(currentWeapon);
currentIndex = ind;
GameObject newEquipment = Instantiate(loadout[ind].prefab, weaponParent.position, weaponParent.rotation, weaponParent) as GameObject;
newEquipment.transform.localPosition = Vector3.zero;
newEquipment.transform.localEulerAngles = Vector3.zero;
newEquipment.GetComponent<WeaponSway>().enabled = photonView.IsMine;
currentWeapon = newEquipment;
}
i am trying to use an rpc to send over information that a object has been instantiated but when i call the rpc no errors or anything and it prints the rpc equip function but on the other players computer you cant see the instatniated prefab please may someone help me
Update: i have found the issue it had nothing to do with the script i was setting a camera active if the photonView.IsMine and if it wasnt it wasnt active and i had the weapon parented to the camera that was being set active so i dragged the weapon out and now i can see it
Hi, I have an issue with assigning colours to players where it shows the new colour of a late joining player for everybody else, but the new player can't see anyone's colour. I'm currently working with NetworkVariables to pass the info along, what could be causing it?
nvm sorted it
What do you multiplayer peeps recommend: Mirror or Fishnet, i like Fishnets features, but it seems so new and also Mirror has a lot more Tutorials available online to get help from
NetworkPrefab hash was not found! In-Scene placed NetworkObject soft synchronization failure for Hash: 2779022876!
Failed to spawn NetworkObject for Hash 2779022876.
OverflowException: Reading past the end of the buffer
```getting this error can anyone help?
Usually, removing and replacing that prefab will fix the issue
i am not using any network prefab in the first place
my network objects contain those hashes
when i remove the network object with a hash , same error shows up wiht hash of another objebct
and the issue is only on the client side
do you know hwo to fix this?
That is how i fixed it in the past
You might need to rebuild the client if hashes are different from the server
how?
what do you mean?
are you not building the client?
what do you mean by build?
building it to a exe and running it
if the client and host/server are running the same build then it shouldn't be an issue
it is
still shwoing the same error
i am running the host in the build and the client in the editor
showing same error
anyone
weird. no idea what's causing that
both seem fine to me. But I use Unity Netcode
can i dm you?
If you ask here people can search for a question and dont need to reask the same question
I guess you can, but I'm not sure how much more help I can be. You can also start a thread here if you don't want to clog the chat
i used netcode
thats cool ? but not what i asked
why are your choices limited to mirror and fishnet?
I mean without ever using it, fishnet looks like its just netcode with a slightly different naming scheme and better optimization on the network data end
I just used netcode because it was builtin and easy to use
yeah its that and free
so why would i use netcode
i decided on fishnet btw
very cool
cuz its better optimized and has other features
Netcode is as "built in" as Mirror etc, they're all just packages
yeah
and it seems like it has naming schemes like mirror, so i can follow mirror tutorials
well netcode is in the unity package listing by default (unless im stupid and i forgot it)
It is, but it's not exactly hard to install any of them
also, Netcode is also free. Its just the Services that are paid
fishnet is free too right?
also you can host your own dedicated server on both netcode and fishnet right
Fishnet has paid pro tier that has things like client prediction tied to it
Hi, is it possible to receive the data of a internet file without downloading it into the computer and reading?
no, magic has not yet been invented
For VR which one is more reliable? Fish-net or Photon?
It will be a P2P experience
VR and networking are orthogonal concerns
Okay, so it doesn't matter, right?
correct
And how can i retrive a json file for webgl games?
You can send it like any other string
hey there , looking for some input. I am using the new unity lobby package in version 1.1.0-pre.4 and I am failing to create a lobby on the server. The clients can create lobbies and everything is working fine, but I want the server to create a lobby as well once a match is created using matchmaker. The server has its own serviceuser and is authenticated and UGS is initialized. I do get the following error message on the server '[Lobby]: ValidationError, (16000). Message: request failed validation' and the stacktrace. According to the documentation every service call returns this nicely formatted error message https://docs.unity.com/lobby/en/manual/lobby-error-messages however I don't know how to access it. I have wrapped the call to the LobbyService in a try-catch block and intercept any LobbyServiceException however I am unable to get the ErrorStatus object which I would hope could reveal more detailed error messages. Any ideas how to access it?
from this post and the answer provided by RobustKnittedTortoise it seems that this error message is actually not propagated through the SDK so I guess I have to learn fiddler now as this seemingly has not been fixed in a long time
Are you certain that your CreateLobbyOptions is valid?
Also is there a particular reason you're using a preview version?
Hello guys! So I have a simple question. I am using Unity Relay and the Unity Authentification Service, now thing is, that the player sets it's profile which will be the UserName. How can I make a TMPro Text above a player's head, show the name of that specific player? Should I use an Network Object? Client Transform?
Check out the player name management. But in any case I would set the player name as a Network Variable
https://docs.unity.com/authentication/en/manual/player-name-management
Hi everyone, back with something else. So I decided to use the AuthenticationService.Instance.Profile as the playerName. Player Name in the player data script is A FixedString128Bytes (like in Image 1) with WritePerms to the Owner and to send the value of the AuthService.Instance.Profile to the server, I am using a void (with ClientRPC) which is called every 5 seconds (just like in Image 2).
Now gigantic problem is, that after all of that, the client can simply not write the value to their Network Variable, as I get the error every time the void is called.
Would be really grateful if someone can help me, thanks!
ClientRpcs can only be called on the server, so your problem is probably that all the clients are trying to call it through the InvokeRepeating instart. And why update your name every 5 seconds? Isn't it going to be the same every time?
That is right. I just wanted to try something, but anyways, instead of using ClientRpc I should use ServerRpc or nothing at all?
NetworkVariables exist to minimize RPCs. I would do something like this:
protected override void OnNetworkSpawn() {
if (IsLocalPlayer) {
PlayerName.Value = Authentication ...
} else {
PlayerName.OnValueChanged += OnValueChanged;
}
}
protected override void OnNetworkDespawn() {
if (!IsLocalPlayer) {
PlayerName.OnValueChanged -= OnValueChanged;
}
}
void OnValueChanged(FixedString128Bytes prev, FixedString128Bytes current) {
_userName.text = current.ToString();
}
Thanks! Will try it out :)
I have been following the two sample projects by unity for game-lobby and matchplay and they are both using preview packages. Without it some rather central logic is not available. For example in the current available package version 1.0.3 it is not possible to set a password for a lobby and many callback events for data being added/changed in the lobby are not available as well.
my current implementation of the createLobbyCall looks like this. I don't see anything wrong with it. The client uses the exact same method where it works fine so it must be related to something about authentication i assume but I was unable to figure it out so far
'''
public async Task<Lobby> CreateLobbyAsync(string lobbyName, int maxPlayers, bool isPrivate, string password = null)
{
if (_createLobbiesCooldown.IsCoolingDown)
{
Debug.LogWarning("Create Lobby hit the rate limit.");
return null;
}
await _createLobbiesCooldown.QueueUntilCooldown();
var createOptions = new CreateLobbyOptions
{
IsPrivate = isPrivate
};
if (!string.IsNullOrWhiteSpace(password))
{
createOptions.Password = password;
}
_currentLobby = await _lobbyService.CreateLobbyAsync(lobbyName, maxPlayers, createOptions);
StartHeartBeat();
return _currentLobby;
}
'''
the call to await _lobbyService.CreateLobbyAsync(lobbyName, maxPlayers, createOptions) triggers the issue with errorcode 16000
Yeah, but photon pun does not have the same performance, the same limits as Netcode.
Does anyone ever solved issues with stutter on photon fusion? Mine jitters and stutters on clients for some reason
Yes, there are plenty of games that are perfectly smooth. There must be something odd / misconfigured in your case.
Are you on the Photon Engine Discord? We've got channels for Fusion and the community there should be able to help.
didnt found any discord related to photon, can you send me the link?
Go to the Profile page of the Photon Dashboard. You can register your discord account there and join the server.
https://dashboard.photonengine.com/en-US/Account/Profile
Guys
I use photon 2
After connecting 2 players the sense changes to game scene and everything is fine
And on the scene I have one empty object called game controller
Which is supposed to handle the game overall data
And I want both players to be able to provide some data to it
I added photon view
And some code
That allows me to type some text in an input field and apply it
And after the application it changes a string variable in the game controller
At least it's supposed to
Because for some unknown reason
When I try to apply the change as the creator it's synchronised
But when I try as the other player it only changes in the scene of the non-creator player
it seems that either host cant read or other player cant write
What networking solution should I choose to learn?
NOTE: -
- I have approx 2.5 months
- I am preparing to get a placement in the XR industry as an XR dev
- I checked out the best are FishNet, Netcode, Photon Fusion
In the netcode documentation (https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/index.html) function NetworkObject.TryRemoveParent is recommended. However, when trying to access said function an error comes up saying 'NetworkObject' does not contain defintion for 'TryRemoveParent'. Am I doing something wrong, are there any alternatives?
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
It doesn't really matter. They are all structured very similarly. Depends on what your goals are. 10 weeks is not a lot of time to learn a new technology
It's not a static function. It would be something like player.TryRemoveParent()
https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkObject/#tryremoveparentboolean
A component used to identify that a GameObject in the network
I'd recommend Mirror then, it seems to be very similar to NGO but with a lot more ressources, which will help you
Additionally if you use chatgpt in a very specific way it can help you learn this things
The mistake while using this technolodgy is asking for solutions, what you need to do is explain your thoughts, like you were talking to a rubber ducky or something
But since Mirror has so many ressources it can give you additional information along the line
10 weeks is doable, if you do it right and are familiar with programming
do you have to use mirror to make a game using steamworks net ?_?
I cant seem to find anything except for one tutorial that makes a lobby system using just steamworks, the rest all use mirror
No you can use facepunch with ngo. You can use steamworks.net with ngo as well, but I was too stupid to figure it out
https://youtu.be/9CYsQ2Rsr2c
Here a link on how to use facepunch with ngo
This Unity Steam Multiplayer tutorial will teach you all about how to setup with Steamworks/Facepunch combine with Unity Netcode For GameObjects and get started with your own project!
Facepunch command link (Put this git link in Package Ma...
TL;DR: If you want Peer-to-peer learn Fusion, if you want dedicated servers learn netcode
Be aware that Fusion, Photon, Fishnet etc are business logic for networking only. When going for P2P networking this is fine but if you are planning to get dedicated servers working you will definitely have to work with some other tech as well. I have been working most with Fusion for gameplay and azure playfab for server hosting, matchmaking etc. However managing the handshake between these two libraries is a pain in the butt. Out of fusion and photon I would definitely go fusion.
But that is exactly the huge benefit of netcode because it ties in really well with game server hosting, matchmaking etc. But it is not yet as stable as Fusion.
I think I worded it wrongly. What I'm currently doing is this: GetComponent<NetworkObject>().TryRemoveParent();, so I'm not trying to accesing it as a static method. And the error is not about it being static or not, it is about it not having a definition. Maybe I'm missing an assembly?
nvm fixed it. Apparently you need to add package > add package by name to install the latest version of com.unity.netcode.gameobjects
weird. version number shouldn't cause that issue
Hello, I have the following issue is there anyone who has any idea about it ?
Well, I had 1.0.2 installed and looking at the source code (https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/ngo/1.0.2/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs) it doesn't contain a definition for TryRemoveParent() but I've upgraded to 1.4.0 and now it does (https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/ngo/1.4.0/com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs#L772)
GitHub
Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer. - com.uni...
GitHub
Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer. - com.uni...
It does. But you'll need to use v1.3.0+ and Unity Transport 2.0
I guess dedicated is the best right? I was asking in the sense that what an XR company would want to use if they are starting a new project? Or what is on the hipe in the XR industry?
any tutorials speaking about this
Yes, I understand that Fusion is a standard. So, I guess NGO is fine right? I can get dedicated and server hosting is also less of a pain?
Also, what about Unity Gaming Services (UGS)?
Not exactly. But we've got a channel for Unity Transport over on the NGO discord server
https://discord.gg/unity-multiplayer-network
Thanks! That worked! kinda... So the text does update for the host. Clients can not see the other's usernames, while the host can see everybody's usernames. Any way to fix it?
That's probably because clients are loading in later which causes them to not subscribe to the event in time for the value to change. You can avoid this by updating the value immediately:
protected override void OnNetworkSpawn() {
if (IsLocalPlayer) {
PlayerName.Value = Authentication ...
} else {
PlayerName.OnValueChanged += OnValueChanged;
OnValueChanged(default, PlayerName.Value);
}
}
```Also consider renaming OnValueChanged to something more descriptive
UGS is a collection of tools, such as Lobby, Friends, Multiplay etc. There is nothing particular interesting/something to learn that is UGS specific.
I guess that would depend on the kind of setup the game/company would go for. Generally speaking Dedicated servers is much more work and more expensive than P2P but it can provide great benefits. The developer has much more control and usually the latency for the player is much better. You should check which of the benefits of a dedicated server are useful for an XR game and decide whether these are required. If not you can get away with P2P and save yourself the struggle.
Most XR games I know only match 2-4 players together. P2P should be easily capable to handle this traffic. 8+ Users i would definitely look into server hosting. If you plan to work on games like beatsaber where latency and client prediction are not really a concern, P2P again is well sufficient. If you want to work on competitive VR shooters you will most definitely want to look into dedicated servers
this is completely wrong, fusion has nothing to do with p2p and it supports dedicated server as one of its main deployment models
[Netcode] [DestinationState To Transition Info] Layer (0) does not exist!
Anyone knows something about this error? I'm using NetworkAnimator component, server authoritative and getting this error on client side. It's regular animation with Blen Tree for walk/jog/run
hi, i've got a UI object that i want to show on the players screen when they walk into a collider but it's showing it on everyones screen and not just the client who walked into it. I'm using NGO but it doesn't have any form of networking on the object. How would I go about solving this?
You'll need to have some kind of UI manager that is networked so you can send a clientRPC to it.
I’ve sorted it now but thanks
{
Debug.Log("working1");
storeNetworkServerRpc(arr);
}
[ServerRpc(RequireOwnership = false)]
public void storeNetworkServerRpc(int[] arr)
{
Debug.Log("working2");
val = arr;
}``` the method storeNetworkServerRpc(int[] arr) is not running, the previous method is workking. do you know why?
Could it be that the console you're looking at is not the server's?
the console is the clients
not working in the clients side so kept the console at the client to check whats wrong
Well if server rpcs are supposed to be executed on the server but you're looking at the clients console, nothing is going to be there
thanks for the detailed answer. Loved it.
can somebody explain how to have my characters camera actually move up and down? I'm trying to get it to rotate but it seems to show up on the server side but not ever for the clients ```csharp
private void LookAround(Vector2 input)
{
float rotationAmount = input.x * rotationSpeed;
xRotation -= input.y * rotationSpeed;
xRotation = Mathf.Clamp(xRotation, -90, minViewRotationAngle);
//accumulate that rotation to a variable
accumulatedRotation += rotationAmount;
//apply the rotation using euler angles
playerHeadTransform.rotation = Quaternion.Euler(xRotation, accumulatedRotation, 0);
playerTransform.rotation = Quaternion.Euler(0, accumulatedRotation, 0);
//virtualCamera.transform.rotation = Quaternion.Euler(xRotation, accumulatedRotation, 0);
}
[ServerRpc]
private void LookAroundServerRpc(Vector2 inputVector)
{
LookAround(inputVector);
}``` the playerTransform is mapped to the top most parent transform, and the headTransform is mapped to the headSphere's Transform which has the camera in it
Hello, I have a question, I am learning to use the Netcode library, and I am having some problems with the movement of the client. The client compared to the host or the server moves something "strange" here I leave a clip of how the client moves compared to the host.
I don't know if you can appreciate the weirdness
Hope it's understandable
Server rpc's run in the server, so the rotation of the head will only happen in the server unless the head has a NetworkTransform component which will allow rotation values to be synced among all clients. Your head might be missing this component.
Your camera probably should not be networked. Keep it local only. Neither the server nor the other clients should care about what your camera is doing
Problem moving on the client
Correct me if I'm wrong, but I believe they're trying to network the head not the camera, the camera just happens to rotate along since it's a child of the head. Wouldn't this be acceptable if other connected player's want to know to what direction the head is looking at?
That's correct. but if LookAround() is on the camera itself, that may cause issues
Doesn't seem to be their case, the ServerPlayerMovement script is attached to the Server Player game object not the camera.
is netcode bad in 2021 unity version? (saw a 1year old video saying its better in 2020 version wondering if its still the case)
i need some help i keep getting this warning whenever i load in to my game with 2 accounts.
What do you mean by bad? It works fine in 2021
Hi guys,i am having a very strange error with unity3d,after quitting an online match i load the offline scene and the gameplay is very strange,the collision don't work and the grabbable objects are no more grabbable,do you know what dcould be the cause of the problem?
https://youtu.be/plKz12tbCLI this is a video of the error
This is the code that runs when a player quit and i return in the offline scene
can you help me?
Sorry for the audio in background...
Hi everyone
can you help me?
It gives an error about not having "UnityTransport".
When I find the code "UnityTransport", the code is empty
I get this error only in the latest version 1.4.0 "Netcode for Gameobjects" package.
I would appreciate it if someone interested in this could help me.
Hello everyone! I am working on a multiplayer game, and I am using a struct with INetworkSerializble and IEquatable<> but once I have more than one value, I get an issue with an void, which is
"No overload for HandleClientConnected" matches delegate Action<ulong>
.
This is how HandleClientConnected method looks like (Image 1). This is what causes the error (unsubscribing too) (Image 2) and this is how the struct looks like (Image 3)
Hey anyone using Unity Matchmaker + Multiplay can help me out here?
I started a new Fleet for Region Europe and suddenly nothing works anymore. When polling the matchmaking ticket status I fail with this:
MultiplayAllocationError: request error: unknown regionid: 8ca6d32c-0985-4c7f-a4dd-cb482cbcf3a8 (request-id: 8a7ff4dd-ff7a-4541-a87d-48e518e38c4e)
I never explicitly set a region id in the ticket attributes? Or is this error misleading and has another reason?
Yea. Onclientconnected callback only gives the ulong client id as a parameter. Add more will cause that error.
Hey I just completed a project using PUN2 but the network movement was pretty jittery...so I am thinking to switch (ya I saw various documentation blah blah and got some help and all but didn't got any real solution) so is Photon Fusion is a good choice or should I consider fishnet or maybe unity netcode it self? Any suggestion guys?
its generally not the job of a netcode framework to make your movement smooth, although most frameworks provide some sort of NetworkTransform and basic interpolation to get started with it. Your choice of framework should not be driven by the immediate utility of such addon/example-features.
Agreed but I really couldn't get any solution to the problem, in the end I can't seem to find any solution to that problem like ik it's something because of photon view in player, the position sync is causing the jitter but I can't seem to know why...watched a whole lotta tutorials, surfed through different qna posts but still nothing...maybe I am just dumb ^_^
hey guys anyone is on the photon discord server? I press join and it says I need to verify my account or something
nvm you just have to login on the discord website recently
it absolutely is the job of the netcode framework to make movement, transforms, etc. smooth - this is all automatic in fusion for example
some libraries make it their job to deal with it, and some persons may have the opinion that all libraries should, but I would not derive a general principle from that and discard any library that takes a different, more unopinionated view.
How can I make spawnpoints in netcode?
Try this link: https://discord.com/channels/87465474098483200
Discord
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
any one know how to make each player control their own camera using mirror and fizzy steamworks
It shouldn't be fundamentally very different from handling stuff like movement. Set things up based on whether the camera follow target is considered the local player character. Networked Mirror objects have a component that has properties for that and you can probably tell when the player object is being spawned in the NetworkManager.
the problem is that one guy gets the other guys camera while the other guy still controls his own
if that makes sense
Don't leave bunch of extra cameras active. You can disable cameras based on target object ownership
i need multiple cameras though, one for each person
what do you mean by disabling based on target ownership though?
Each client only needs their own camera active.
I'm unsure if this is the right place for it but I'm new to multiplayer game development in general and would like to test the Multiplay solution Unity offers but I'm afraid to go over the free tier stuff and get charged a lot of money due to some dumb mistake.
Is there a way to disable a feature if it goes over the free tier?
Another question I have is what does Unity considers "Sign Up" (for the 6 month / 800$ free period)? Is it the moment of account creation? Or after setting up a payment information? Where do I check such information?
The free triers of Unity Game Services are pretty generous. You are unlikely to go over it during development. Those credits are only for the Multiplay Service. It starts when you first enable Server Hosting from the Dashboard. It should cover about a month of light testing but it should be one of the last things you setup
Which networking solution is the best for fast-paced shooter games?
I was wondering if anyone could give me some insight on how to handle achievements in a multiplayer setting using Steam and Mirror. Im having a lot of trouble unlocking an achievement for one player rather than all players. I want to have 3 rats in an area. When I player "finds" (enters rat's collider) all 3 rats I want to unlock a steam achievement. I cannot for the life of me get this to work with other players also being in the scene, it either unlocks the achievement for everyone if one person finds all the rats, or no one. Ive been trying to figure this out for hours and maybe its just so simple that I cant see what to do anymore, please help! Heres my code that is on the rats:
I have a very simple achievement manager script with the AchievementUnlock() to just unlock a steam achievement
I also am trying to make it so that is saves to playerprefs, that way if you find 1 rat and then quit, you can come back and find the other 2
Would you guys recommend FishNet or Netcode for Game Objects for a 5-player competitive party game?
Unity PhotonView.Ismine always true and ownerId always null
How can i make that in multiplayer some players can go throught some object and some colide with it at the same time HELP???!!
Hello, I'm currently using Netcode for GO and i have 2 main issues with the network Animator and Transform.
-
The root motion does not apply well to from the host to the client. Maybe it's because of the very precise movement curve but there is some very weird movement on the client. For this issue, the only solution i can think of, is to write my own client prediction.
-
Maybe there is something that i did not understand with the network animator, but to my opinion this component is weird. Basically, the trigger parameter sync diffently than other animator parameter and this is fine. Except when you have some big animator with a lot of parameter. If you change the animator parameters and right after the trigger, sometimes the trigger will sync BEFORE the parameters. This can be corrected with a coroutine but it feel weird anc can cause some severe animation sync bug.
I wanted to know if anyone encountered this problem, and what is your solution. Though I will may be drop the network animator to use my own sync with RPC call
When are you checking? These values may not be set until after Awake.
I posted this on the PUN forum, but Smooth Sync can help reduce jitters
Can anyone help me with websockets and unity
Are there any assets that setup websockets for a webGL based multiplayer game
Fishnet with Server/Client based Networking
pun2 is outdated and you shouldnt use it for a new project, it doesnt support network smoothing or rollback
use Photon Fusion If you want to stay with photon, it will automatically be more smooth, just cuz it has build in network smoothing / rollback
I personally can only recommend Fishnet, its very easy and since its heavily optimized you only need a cheap server to host 100 or more players.
or you use Steamworks with Fishnet to stay completly free (besides the steam fee)
Fishnet
depends on your needs and your experience, I use netcode for game objects with steam facepunch for my game and it works fine
Alright, nice! I'm trying to do something sort of peer-to-peer. It's a remake of a game, so it's definitely not going on Steam haha.
Is it good with peer to peer in any way? (Maybe with something like Radmin VPN/Hamachi)
Youtube has plenty on Fusion, i never used Fusion myself, since i dont like Photons pricing
from my perspective i would recommend Fishnet with Steamworks or a small Server
you can use steam networking without publishing to steam, it has a few drawbacks tho, you can use the appid 480 for access to steam networking. I would only recommend it when playing with friends and not acutally releasing the game, but same goes for vpns like hamachi, appid 480 would be better if thats the alternative
Steamworks offers a peer to peer Relay server, without a Relay server the peers cant find each other.
unless you host it on the same network via hamachi, but thats not a valid way if you want to release a game to public
You could also use Unitys Relay Service, thats free up to 50 CCU
But then you would have to check how many CCU youre currently having and blocking new players from connecting, so you dont step into unitys bad pricing
I'm gonna be less vague:
So basically, this is basically a fan-made remake of a Nintendo game. I want to do something that won't get taken down, even if Nintendo steps in because of how they are with something like fan projects.
It's DEFINITELY not legal to release on steam 💀 but would it be fine if I use the steam relay?
Thats not possible
you need a relay serivce
that can get shut down
only way that happens is with hamachi or self hosting
but i think a host/client way with hamachi is a good solution in this scenario @bold birch
Alright, sick 👍 Just wanted to confirm that that was pretty much the only way.
Thank you very much!!
Then Fishnet with host/client and hamachi is a completly free option but people need to be in the same hamachi network, only good for a game with friends..
Fishnet with host/client and Unity Relay is Free up to 50 Current Users
if you know it is not legal, let me give you a tip, just don't release it, espacially in nintendos case, lawyers can get pretty expensive
and yes it is fine to use steam relay with 480, wouldn't release it that way tho, but for only with friends it works fine
I personally wouldn't touch a game which requires hamachi anymore, from a player perspective you would want to use a secure but easy solutionm
Fishnet host/client with Steamworks is one time 100$ but then completly unlimited ccu and people can even join their friends over steam if implemented correctly
- Your game is on Steam, the biggest Game platform there is
That's true 🤷♂️
At first, this was going to be an easy "just use steam" type thing among friends, until I realized that there's some kind of "demand" for a thing like what I'm doing. As like a cool "oh wow, we can play this on pc now!!" and a nice way to get some clout
I know people will use Radmin/Hamachi for things like Mario Odyssey Online or Breath of the Wild Online for sure
do it on your own risk, I wouldn't wanna beef with nintendo haha
But if your target audience is willing to use it, it is a valid option
you could do it a way that people can download the server executable and host their own Servers
yes that would work too, like minecraft
yep thats pretty easy with fishnet
Guys with unity Relay when the CCU counter is trigggered and its value incremented?
its basically build into unity, you just select server under the build menu
To decrement the CCU counter i just need to do NetworkManager.ShutDown?
i meant the programming part about server / client
I was mainly considering the virtual network option, because it doesn't require port forwarding on the end of the host.
I'm down to do this though, now. Thank you very much for all the pointing in the right direction!
Fair, haha
you just need to display the current ip in a log output from the server and tell them to foward the port on the device the server is running
?
Alright, sounds easy enough from a user perspective 🤷♂️
the user you just have a ui to enter the server ip and the name they want to have
i mean none of this is automatic, but its very easy to grasp and there are multiple tutorials online and help projects on the github/website of fishnet
Of course, of course. I think it'd be good to learn either way!
How can i make that in multiplayer some players can go throught some object and some colide with it at the same time HELP???!!
So i run into a Problem with the Dedicated Server Plattform Build with a Linux Server hosted on AWS. If i upload the Server application to my AWS EC2 instacen and start it over a console, all Logs get pushed to that console, wich i dont mind. But as soon as i close the console on my pc. The Server Application gets killed on the Server.
Hello,
My problem is that I make a multiplayer game with photon and in my script that manages the lobby and the spawns etc..., in this script I create a list of gameobject that I call players and as soon as someone spawns a l using the OnJoinedRoom() method I make sure that once the player spawns that I add it to my list, then I want to access this list so that my bot retrieves the coordinates of the nearest player and this moves towards him. Except the first player is add but the following ones are not and I don't know why.
Thanks in advance for the help.
Use a site like pastebin to post code
And also for my alivePlayerCount it doesn't work either since the list is malfunctioning
hi, i want to make every player have different character
did i need to set active to false ? (to hidden the character in prefab)
or
i need to change Local Avatar Prefab ?
do i need change this
or set active in avatar ?
local avatar prefab player character 3d model
can you tell me more detail ?
I'm a little confused by your answer
its in one of your avatar prefabs
either the local avatar prefab or local player or avatar 1 2 or 3
try one of those
configure it out test each one until it works
i didnt write the script im just going off what im seeing in the inspector
oh.....
thanks
this file for sync
but i got error every other player join
this file attach to Avatar1 Copy
Hello everyone. I've got a question regarding NetworkObjects when using Unity Netcode for gameobjects.
I've already posted it in the forum, but received no answer so far, so I thought it might be a good idea to post it here as well.
" I have the following issue: Let's say there is this NetworkObject
- Tile
-- Game
--- Traps
---- TrapA
----- MovingPlatform
'Tile' is spawned during runtime.
'MovingPlatform' has a NetworkBehaviour and NetworkTransform component. It is supposed to move when the player is jumping on it.
All other Nodes have NetworkTransform components to make 'MovingPlatform' work.
So far so good. But if for example, 'Traps' is inactive when 'Tile' is spawned and activated later during runtime (by so kind of event e.g. pulling a lever), 'MovingPlatform' doesn't know e.g. IsHost, IsSpawned, etc.
Is there a way to make it work without having to move 'Traps' into a prefab and spawn it? Like telling the NetworkObject to refresh some of its children?
It works when 'Traps' is active at first and set to inactive after spawning (at least locally, haven't tested it with Coop). But this feels awkward, is there an easier way?"
Link to the thread in the forum: https://forum.unity.com/threads/inactive-networkbehaviour-in-sub-node-not-initialized-when-activated-after-networkobject-was-spawned.1439605/
Everything has to be active on spawn. This is how the network manager keeps track of things. You could use some kind of platform or trap manager that is keeping track of the inactive objects
Thats what I thought. Its weird though, as this is kinda contrary to how you implement things in a non network game. But it is what it is 😄
Thanks for the answer.
is there any people using photon fusion ? i've a problem how to run function StartGame when i load scene from addressables
hello, i am using netcode for gameobjects, and because I have many GO's in my scene, just simple monobehaviours, this shit is destroying my playmode performance. any tips on what to do?
seems like the netcode package subscribes to EditorApplication.hierarchyChanged to find nested network managers, and it uses Resources.FindObjectsOfTypeAll to find them. If you have many GO's = lag. how the heck is this acceptable in a supposedly good engine
Netcode doesn't do anything with monobehaviors
in a sense it does
because if you have many mono's the aforementioned search for nested managers will take longer, since FindObjectsOfTypeAll searches mono's as well
super duper annoying
is there a way to overwrite a file / method inside an embedded package? for example Packages/Netcode for Gameobjects?
Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will be destroyed.
how do i fix this
delete one
i dont mean to have two, in one scene, i set it to ddol then go to a new scene, adn when i go back it says there are two and it deletes the first (the ddol one) which then throws reference errors
dont add one to your other scene then
and don't reload the scene that holds the ddol objects
how do i not reload it
im not adding it to another, i have it in the first scene and make it ddol, then when i go to a new scene and come back, there is one that spawns
how do you "come back"?
not sure, the network stuff does it for me, but i can try to find it
i think it just loads the scene again
well, don't put your DDOL network manager into scenes that you are loading repeatedly
Put it in a scene that you load only once during the game session
Not some scene you can go back to
What does the ngo documentation for the approval check mean by steam ticket, and why shouldnt someone use it in an approval check payload?
the payload is sent unencrypted. An Authentication Ticket is used to verify the user without them always having to enter a password.
I thought as much, why would someone send the ticket instead of just authenticating with steam directly?
hi guys! i'm trying to make a Dedicated server game with fishnet and having poor results. And afaik fishnet is one simple network solution too. I clearly need to study some networking, I'm pretty sure I need to get some general networking lessons for unity, so not fishnet specific. Do you guys have any recommendations on what/how to learn and where? I can't seem to get how all of this works and I've read fishnet docus quite a lot without result.
the dedicated multiplayer server build can be self hosted right?
Sure most of the time they can be hosted wherever. I'm not sure about Photon Server Hosting though.
what is photon exactly?
I want my game to have between 2 to 40 players
per instance
what would be my options?
Photon is one of the many networking frameworks out there. Check the pinned message here for the other solutions. It really depends on your game but they should all handle around 40 players
why cant I add the prefab to the network prefab list
what is the most scalable between photon and NGO
I want only 40 players in my game but possibly expand on that later on
how would i execute code on server and return it to the client? using NGO
You have to use 2 separate RPCs for that. The client will call a serverRPC to run then the server will call a clientRPC in return.
i have scripts that implement pvp turn based multiplayer game, it also utilizes mvc pattern, i have code correct but no connection to game is happening and no player are spawning.. no debug showing too
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
im using pun2 btw
Hello, I'm working on a network game using netcode and cinemachine. I have a virtual camera that's following a network gameobject. It's client authoritative so, on this game object, I have a Client Network Transform component. At the init, the owner of the gameobject sets the position of the object. There is a delay between the moment when the position is set and when other clients receive this new position. During this delay the cameras of other clients follow a wrong position. Could you please tell me how to handle this problem correctly ? Ideally I would like to have the cameras following the object after at least one position synchronization.
There should only be one one camera in the scene for the local player.
Check out the client driven sample for an example
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven/
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
{
private NetworkVariable<int> _connectedClients = new NetworkVariable<int>();
[SerializeField] private GameObject playerBoardPrefab;
private void Update()
{
if(!IsOwner||!IsServer) return;
if (_connectedClients.Value != NetworkManager.Singleton.ConnectedClientsIds.Count)
{
_connectedClients.Value = NetworkManager.Singleton.ConnectedClientsIds.Count;
SpawnPlayerBoardServerRpc(_connectedClients.Value -1);
}
}
[ServerRpc]
private void SpawnPlayerBoardServerRpc(int newPlayerId)
{
int rotation = 90 * newPlayerId;
Debug.Log("rotations is " + rotation);
GameObject go = Instantiate(playerBoardPrefab);
go.GetComponent<NetworkObject>().Spawn(true);
go.name = "setting name";
go.transform.GetChild(0).GetComponent<RectTransform>().rotation = Quaternion.Euler(0, 0, rotation);
}
}``` Im getting error NotServerException: Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead. and The object of type 'NetworkObject' has been destroyed but you are still trying to access it.
I dont get why the spawn happends in a serverrpc so the clients dont do it right?
There is only one camera in the scene. When I talked about cameraS it is the same camera but in each client.
The camera shouldn't be networked. It should be local to each client
You have something calling Destroy() on the client somewhere else
I dont xD
this is all my code
Dunno what to tell you then.
the issue lies with the Spawn the moment I put that in comments I get no errors at all
this is my network object on the preab
does anyone know what this error message might be caused by?
[Netcode] NetworkBehaviour index 1 was out of bounds for player(Clone). NetworkBehaviours must be the same, and in the same order, between server and client.
When using parallel sync, I will receive this error message and crash after joining on my other editor.
ah ok I fixed it
I was deleting the player controller script after joining my bad
🗃️ Documentation
📚 Resources
Blogs
- Unity’s new GameObjects multiplayer networking framework
- Navigating Unity’s multiplayer Netcode transition
Samples
Github
💬 Forums
Discords
- Unity Multiplayer Networking • https://discord.gg/FM8SE9E
- Mirror • https://discord.gg/N9QVxbM
- Photon
- Mirage • https://discord.gg/DTBPBYvexy
- Normcore • https://discord.gg/XvMthZG
🗺️ Roadmap
unity netcode client host connecting only in the same computer and not in other devices
can we use netcode to connect devices that are not in the same local network?
Explained in #archived-code-general
"Unity provides a relay service that you can integrate with Netcode easily iirc. " can you elaborate or send a link?
I think there's also a mention and explanation on integration in the Netcode docs.
👍 👍
that so cool✨
Some I'm a bit ambitious, and I'm making a multiplayer VR Game. With no experience networking games at all. Where should I start?
I'm guessing the best Idea will be to purchase an asset to handle this mostly for me, and if so, what are some good ones?
I have this game where a player is controlling a ball, the server is P2P - Unity's Relay (Netcode for Gameobjects)
The balls should be able to move smoothly without any noticeable delay, as well as being able to noticeably see when you collide with another player.
Would it make sense to have server-authoritative-movement?
Or should I make is client-authoritative?
I do know that Client-authoritative-movement is also less secure and can be susceptible to cheating.
But it's P2P, so does it really matter?
Are there any other ways of doing this?
If so, how?
Handle what exactly?
If networking, then start from the bottom, and work your way up to knowledge.
Unity's netcode is fine nowadays, so practice using that.
Alright, I meant handling realtime connections of players on a server
Start small, with non VR players. Then work your way up from there. VR is tricky and you'll need to know the ins and outs of networking before you tackle it
If its physics based, then you'll want to handle everything on the server. But this is going introduce input lag for the clients. Ideally you'll want to create a client prediction system to compensate for that lag.
Yes, it is physics based. Cheers!
I would use either NetworkVariable or custom messages and build my own from scratch. I can't think of a way to retrofit the exiting NetworkTransforms into a client side prediction model.
https://forum.unity.com/threads/networktransform-and-client-side-prediction.1181830/#post-7565848
Classic Unity
Doesn't include CSP, you have to make one yourself.
It's currently on the roadmap 
https://forum.unity.com/threads/client-side-prediction-and-reconciliation.1397497/
It's still being investigated and we're too early in 2023 to say anything about it. Anything could happen in the upcoming 10 months.
If you're working on your game now, I would recommend to explore production-ready prediction + reconcilition solutions (or to implement your own)

Using unity netcode, how would i find a list of hosts that i can connect to?
You can use the Lobby Service.
Is there a way to do that without the Lobby Service?
You can write your own web service I guess. Or use Steams lobby service.
When teleporting the client, it teleports to a close location instead, and when I move it snaps interpolates to the actual location, is this a bug?
I am using a server-authoritative model.
Code
[ServerRpc]
private void RequestTeleportServerRpc(Vector3 position)
{
// Teleport the player to requested position
NetworkTransform.Teleport(position, Quaternion.identity, new Vector3(1, 1, 1));
// update the position on the client-side
RequestTeleportClientRpc(position);
}
[ClientRpc]
private void RequestTeleportClientRpc(Vector3 position)
{
// Set transform's position to position
transform.position = position;
}
At the end I moved the player, which results in the player interpolating to the actual location
I saw this, but it's been marked as solved.
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1867
I'm using Unity 2022.2.19
I have tried both 2022.2.21 and latest 2023 version, both results in the same issue
Am I doing it correctly? 🤔
For NetworkTransform.Teleport should immediately teleport the transform without interpolating.
It can only be called on the server too, which is weird.
Host does not have this issue, only clients does.
I'd assume that the client interpolation is unaffected by that causing the issue. You'd need to either disable the interpolation or look up a way to set the position without interpolation.
🤔
Yea, you'll need to disable interpolation client side before you teleport. If you are using a character controller, disable that as well before teleporting
Just like this?
pseudocode
Interpolation = false
NetworkTransform.Teleport(..)
Interpolation = true
or does it require a specific delay between teleportation and turning it on again?
Since yours is server authoritative, you need to disable interpolation on the client then teleport on the server then reenable it on the client. It can be done with a clientRPC
client id 0 is always the host/server
ok ty
Networkvariables need the object to be spawned but how do check if the object is spawned in ngo
You can use OnNetworkSpawn() in the network behaviour
ty again xd
Does anyone have experience manually connecting in DOTS using UNITY_DISABLE_AUTOMATIC_SYSTEM_BOOTSTRAP? I have UI buttons triggering this code but it's not working like I'm expecting:
using Unity.Entities;
using Unity.NetCode;
using Unity.Networking.Transport;
using UnityEngine;
public class ClientServerLauncher : MonoBehaviour
{
const ushort PORT = 7979;
public void StartHost()
{
StartServer();
StartClient();
}
public void StartServer()
{
ClientServerBootstrap.DefaultListenAddress.Port = PORT;
//ClientServerBootstrap.AutoConnectPort = PORT;
Debug.Log($"Listening on port {PORT}");
World serverWorld = ClientServerBootstrap.CreateServerWorld("ServerWorld");
NetworkEndpoint ep = NetworkEndpoint.AnyIpv4.WithPort(PORT);
{
using var drvQuery = serverWorld.EntityManager.CreateEntityQuery(ComponentType.ReadWrite<NetworkStreamDriver>());
drvQuery.GetSingletonRW<NetworkStreamDriver>().ValueRW.Listen(ep);
}
}
public void StartClient()
{
ClientServerBootstrap.AutoConnectPort = 0;
World clientWorld = ClientServerBootstrap.CreateClientWorld("ClientWorld");
NetworkEndpoint ep = NetworkEndpoint.LoopbackIpv4.WithPort(PORT);
var drvQuery = clientWorld.EntityManager.CreateEntityQuery(ComponentType.ReadWrite<NetworkStreamDriver>());
drvQuery.GetSingletonRW<NetworkStreamDriver>().ValueRW.Connect(clientWorld.EntityManager, ep);
Debug.Log("Connected.");
}
}
When I host the server reports that it's listening and the script above reports the client "Connected." but then the client doesn't "connect" until after I stop play. If I open the entities tab after play is stopped it will even run some of the systems to create the player GO
Similarly, my GoInGameSystem debug log messages (for client and server) don't print to the console at all until after I stop play
how would i sync a list to the server and keep its value when other clients join?
Use rpcs to sync the list when it's modified or a new client joins.
is photon still a good choice? or is it better to go with the new unity NGO
I'm sticking with NGO but Photon Fusion is good too
been having issues with NGO and got a photon course from humblebundle a while back
Ill try that out then thnx
say i have a gameobject, and i spawn it on a player, however if a new player joins, i would like him to see it, too. how would i do this?
Depends on which networking you are using. With NGO you have to call Spawn() on the server
i am using mirror
would it be the same (NetworkServer.Spawn(obj);)?
whats a good multiplayer solution for a simple card game
i wanted to use photon but people say its outdated and that fish net is really good
Photon PUN is old but Photon Fusion is the new hotness. But for a simple card game anything will do fine. There is a new online TCG asset that's built on Unity Netcode.
i mostly care about concurrent player limits since im planning on publishing it to steam
i'm using mirror, would you know how to do what I asked on there?
I'm not current on Photon's limits. But the only limits with NGO is when using the gaming services like Relay or Lobby services. If you are using steamworks then you are only limited by Steam.
No idea. I assume any basic Mirror tutorial should walk you through spawning objects
I have question about NetworkVariables. I have some data, which can change during game, but not very often. And it is important to get right value also for clients connected in middle of game session. Is it overklill to use NetworkVariable for this? Like what about using RPC on OnNetworkSpawn callback to request actual data from server and then sync value using another reliable RPC only when value changed? I am afraid of bandwidth overload when there is lots of NetworkVariables (asume RPC are cheaper for resources). How many NetworkVariables is too much?
Network variables only cause traffic if you change their value + on client connect and are made for exactly the use case you are describing.
hey guys, is there any way to use to serializer.SerializeValue() an AnimationCurve in an INetworkSerializable struct?
{
private AnimationCurve heightCurve;
private AnimationCurve distCurve;
internal AnimationCurve newHeightCurve
{
get => heightCurve;
set
{
heightCurve = value;
}
}
internal AnimationCurve newDistCurve
{
get => distCurve;
set
{
distCurve = value;
}
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref heightCurve);
serializer.SerializeValue(ref distCurve);
}
}```
(sorry for repeat question, original channel was innapropriate)
current error message is: "Assets\workflow main\scripts\network\playerNetwork.cs(304,24): error CS8377: The type 'AnimationCurve' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'BufferSerializer<T>.SerializeValue<T>(ref T, FastBufferWriter.ForPrimitives)' "
Usually you would not serialize the animation curve itself. If your animation curve is configured in the inspector (and not changed at runtime), there would be no reason to sync it over the network. You would use some ID to map to the different curves, then sync the IDs instead so that the clients know what curve to use.
so make like arrays with animation curves basically
?
and then
Sure, and then just send the index
how would i sync already spawned gameobjects to clients who joined after the object has spawned? [mirror]
make them network objects and it happens automatically
if you mean simply adding a network identity, it's not doing anything
keep in mind these are childs of prefabs instantiated at runtime
and networkserver.spawn is also not doing anything
did you register the prefabs with the networkManager?
I've tried to get https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/session-management/
to work (I manually copied the code over because for some reason importing from git wont work with the package and causes a lot of errors)
but I'm a little lost on how it's supposed to be used.
I understand using a specific ID for the player instead of the NGO client ID's as they change based on who connects and disconnects, and I understand the concept of using the struct T to store data in relation to the players specific clientID, but I don't understand how to necessarily implement the session manager
[also yes, I'm fairly new if you cant tell by how stupid I probably sound lmaO]
For context I plan on storing 3 main vars (like "points" that will probably be ints (or floats if I get fancy with the point system and add decimals), an undecided amount of bool vars [for unlocking upgrades during the "session" of the game, these bools will allow client players to purchase things with the "points",] and an undecided amount of int vars (for tracking "fun" stats, like how certain games will show the person who did the most damage, etc.) I want this data to be linked to the player as opposed to having it linked to client ID as if someone leaves mid match and rejoins in the third round the client ID's will shift around [by leaving at least] Hence upon searching up something like structs multiplayer points or something like that I found the Session Management doc and am trying to implement that, as it seems to solve my problems but I can't quite figure out how to implement it.
If anyone knows how one goes about this, or if there is in fact a better way to implement what I intend to do, please let me know
You can use session management to keep data when a player disconnects and accurately reassign it to the player when they reconnect.
That sample code comes from The Boss Room project which is kinda over engineered honestly. Its basically just a Dictionary<playerId,playerData>. If you use Unity Authentication for Relay or Lobby, then the player id is just there for you use.
I plan on implementing steam API [I made a test project to try to get it setup [was working pretty well] and realized I should probably do that last as it makes it much harder to test projects] so would I just use their unique CSteamID ulongs?
[great pfp btw]
yep
ah very cool ty
and i presume upon the game ending I'd just clear the dictionary to get rid of all the data & restart ye?
[also would I make the dictionary be a network var? can you make a dictionary be a network var?]
Just reloading the scene would take care of the data. Someone did make a NetworkDictionary a while back but its a bit outdated now. https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDictionary
you absolute mega chad ty
sorry for asking another question but
would I need to make sure the game obj or whatever is using this doesn't destroy on load? (cause you said reloading the scene would take care of it, which I intend to happen a few times at least lol)
no prob.
But yea, if you are reloading the scene during a match then that would need to be set to Do Not Destroy on Load. It gets moved into a separate scene
very very very cool of you I appreciate the responses n the extra mile of finding a script too
saved me a ton of time ty
lol, I've got the docs permanently pinned in my browser
{
private NetworkVariable<int> _connectedClients = new NetworkVariable<int>();
[SerializeField] private GameObject playerBoardPrefab;
private void Update()
{
if(!IsOwner||!IsServer) return;
if (_connectedClients.Value != NetworkManager.Singleton.ConnectedClientsIds.Count)
{
_connectedClients.Value = NetworkManager.Singleton.ConnectedClientsIds.Count;
InstantiatePrefab(_connectedClients.Value -1);
}
}
private void InstantiatePrefab(int newPlayerId)
{
int rotation = 90 * newPlayerId;
Debug.Log("rotations is " + rotation);
GameObject go = Instantiate(playerBoardPrefab);
go.transform.GetChild(0).GetComponent<RectTransform>().rotation = Quaternion.Euler(0, 0, rotation);
}
}``` I got this code wich spawns a prefab whenever a player joins. Its not synced to the client but the moment I put the spawn command under I get errors like NotServerException: Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.
is anyone here MAYBE developing on Mac and has tried to use Unity Lobbies?
await UnityServices.InitializeAsync();
AuthenticationService.Instance.SignedIn += () => {
Debug.Log("AuthenticationService_SignedIn: " + AuthenticationService.Instance.PlayerId);
};
await AuthenticationService.Instance.SignInAnonymouslyAsync();
this returns the same playerId for two instances of the app on mac.
So if I run the game on the editor everything is ok, I get one instance in the editor and one in build
but if I open the same build in a new window "open -n -a .app"
I get the same playerId on that client instance
found the solution, so thanks anyways 🙂
For those searching this later. The solution is to change Authentication Profiles when using Anonymous Sign in on the same PC
Exactly
InitializationOptions initializationOptions = new InitializationOptions();
initializationOptions.SetProfile(playerName);
await UnityServices.InitializeAsync(initializationOptions);
AuthenticationService.Instance.SignedIn += () => {
Debug.Log("AuthenticationService_SignedIn: " + playerName + " - " + AuthenticationService.Instance.PlayerId);
};
await AuthenticationService.Instance.SignInAnonymouslyAsync();
im currently using Photon PUN to make my first multiplayer game, ive got movement synced and a room/lobby system working. the biggest part of the game is collecting randomly spawning fish but the spawning isnt synced between clients
i have no clue how to sync it, ive tried photon view on both the spawner and the prefab
im very clueless when it comes to this lol
Hello, using NGO and I have a quick question, if a parent GameObject is a NetworkObject are then all of its children NetworkObjects? Or do I have to give each child I want something to do over network its own NetworkObject component. I would also like to know that if I have a network player prefab if all children of the player prefab are owned by the owner of the player prefab
Only the parent needs a network object. And they are all owned by the parent
Thanks :D
please help
You can most likely just use the masterclient to spawn in drops with PhotonViews using PhotonNetwork.Instantiate
got it, i completely forgot PhotonNetwork.Instantiate even existed lol
yo so uh why is my test player object not properly reading who is the owner? [start a game, host, and the IsOwner FALSE CHECK gets set off (although its the host???]
I know I probably shouldn't use OnEnable for network spawned objects but I can't find what else to use in the docs for some reason [I remember there being a specific portion going over a few but I cant find it again sadly :l]
should I use this instead or what ?_?
it would also be nice to know how to do this properly so I could for example wrap the action mappings in a isowner check rather than the actual inputs in the update function [so that way only the owner maps their actions to the object and not every player]
any help appreciated sry for the essay lmao
owner isn't set until after onnetworkspawn()
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior/#spawning
Both the NetworkObject and NetworkBehaviour components require the use of specialized structures to be serialized and used with RPCs and NetworkVariables:
THE PAGE
ZORACK HAS BLESSED ME AGAIN
literally exactly what I was looking for and couldnt find
so does this mean I should call a function inside OnNetworkSpawn? Or should I do the initialization INSIDE OnNetworkSpawn?
just read it again lmaO ty gamer
alright so anything inside this OnNetworkSpawn doesn't work... I'm spawning the object as a default player object using the network manager (ik ik Ill sort out something else later)
getting 0 debug log readings from anything at all both on host and client
Why is it new and virtual? Normally you use override
for unity netcode/unity transport, is there a function or event when a client sucsessfully conects to a server/host?
Anyone know, if I have network transform sync on an object, but the object is not moving, are packets sent?
Network Manager has an OnClientConnectedCallback that you can subscribe to.
No, data is only sent when the object moves
Alright thanks homie
I get an error when I use override ill try that now [also sorry for 12 hour late ping lmao]
No worries. You can check out the docs here
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior/#spawning
Both the NetworkObject and NetworkBehaviour components require the use of specialized structures to be serialized and used with RPCs and NetworkVariables:
ok so I literally rewrote it [tried the override again] and the error it was giving me is gone now and I didn't change anything so like lmao unity moment ig danke again man is actually hard carrying this channel lmao
Is it possible to make photon pun 2 rooms stay online when someone has left
I imagine you would have to use their server software to do that. Keeping those things online isn't free.
If you're paying for a plan its not 🤷🏿♂️
Yea. PUN isn't really designed for persistent stuff
Yea you could save the state of a room somewhere else and restore it
yeah maybe
It's probably better to move to Photon Fusion (which is much more flexible out of the box for this sort of stuff) or some other networking framework
I wanna achieve a system where a player can make their own world, lock the world and so its theirs, and from there on I could probably save the information to a firebase database and when another player wants to visit their already made world while their not online in the room, they can enter the world name and load the information from the firebase database
Ill have to test some stuff out
Though I suspect you still might need Photon Server to do this with proper authority as you get into the weeds of this. All clients have a lot of control over the room they are connected to.
Hi
Hi, i want to make a 2d game with Rigidbody 2d and physics material with bounciness, player can use the bounciness to push then selves on collission. I dont know how predictable is this, but can i use that with the netcode for game objects?
maybe is better to just use the nerwork layer?
In theory you can use NGO. But syncing physics is a hard problem. You'll need to implement some form of client prediction to keep things smooth. That is not built into NGO. Netcode for Entities and I believe Photon Fusion has this as a feature.
this game will be for wifi only, and its for andoid
maybe i can use the network layer
if each player simulates the physics, the positions can be wrong rigth?
so maybe the host should be the one simulationg all the game?
I dont one such a thing like an authoritative server for this
sending the player positions is ok for me
but im not sure how to handle the physics
Unity physics is nondeterministic. The same bounce can end up at 2 different places on each client. It's best to handle all physics on the host. But you end up with input latency. Client prediction will help with that.
I kn ow what you mean, but event with that how can you predict something tha is unpredictible?
also, on a wifi game, do you think we can have to much input lag?
and what about havo physics? but i think that is not free
Havok Physics is built for DOTs, so you would probably be using Netcode for Entities in that case. It also needs to have a Unity Pro license.
and is it free with the unity pro?
I don't believe there are any additional costs, no. But Dots Unity Physics is also deterministic and does not need the Pro license
Like a year ago, i readed that havok has an aditional cost, but maybe its free now
why is my transform for the client on the host not in the right position, you can see here it is "hovering" after a jump. i am using a client network transform
I think this answer the question
Havok Physics for Unity can be downloaded from the Unity Package Manager, but only Pro, Enterprise and UIC users have access to use the features at runtime.
Havok Physics SDK License
Havok Physics for Unity is a binary-only distribution of Havok Physics (2021.2) that has the same industry-standard power but without access to C++ source code (known as "Base and Product" access) or direct support from Havok.
My game is top down and aiming is done via mouse pointing regardless of character orientation. For fast firing weapons, I just send "StartFire" and "StopFire" calls, since sending up to 100 shot info packets per second is madness. So, after sending StartFire call I just update the server with player's current aiming position which is just a float3. Problem is, it's noticeably choppy when only updating aiming target every 0.2 seconds. Is sending a packet with aiming vector every 0.03 (1\30) seconds fine? I know premature optimization is a bitch and such but I'm genuinelly not familiar with acceptable limits here 🤪
Usually that is an interpolation issue. Try turning it off on the network Transform
It's fine until it not. If you aren't seeing any issues then just keep an eye on the Profiler
Worst case scenario all 12 players are firing at the same time, which means 400 packets a second.
But I can't really think of another solution tbh 🤷♂️
bang on 👍 fixed it thanks
although movement is quite choppy now, any idea why (i do apologise im new to the networking stuff)
it does suggest to use a networked rigid body but i dont see why that would make it choppy?
Interpolation is supposed to smooth out that movement. But the threshold for interpolation can cause that jump float thing to happen
in a unity transport, what ip addres is suppossed to go into the address field
or like what do i change so that a client can connect to a given server insead of just the local host
That would be the IP address of your server
from what i can see the threshholds indicate how much an object must change in order for an update to be sent to the server. will changing these help the jitter?
Any idea why this block of code isnt setting my speech bubble as active once I click enter to send my message
Hi, i can't seem to figure out why my clients movements are not being updated on the hosts screen. I can see the camera is moving but not the player position. I am sending a Video and my main statemachine script. Thank you for any help
When I test my project via parrelsync & mirror networking, I can move the host, but not the client. I have it set as client to server. I have been looking online and see others have had this problem, but I have yet to find a good resolution
If anyone has dealt with this before, would you mind shraing how you reoslved it?
I currently resolved it by adding an if(isLocalPlayer), but would that affect multiple players playing simultaneously?
I am using Lobby service, relay and NGO hoewever everything works great, but after a little while of playing the host times out does anyone know why this could happen
I'm still stuck on the same issue, how would you handle spawning an object whenever a player joins? I got this implementation but it doesnt work ```using Unity.Netcode;
using UnityEngine;
public class PlayerManager : NetworkBehaviour
{
private NetworkVariable<int> _connectedClients = new NetworkVariable<int>();
[SerializeField] private GameObject playerBoardPrefab;
public override void OnNetworkSpawn()
{
if(!IsServer) return;
SpawnPlayerBoardServerRpc();
_connectedClients.Value++;
}
[ServerRpc]
private void SpawnPlayerBoardServerRpc()
{
GameObject playerBoard;
int rotation = 90 * (_connectedClients.Value-1);
playerBoard = Instantiate(playerBoardPrefab);
playerBoard.transform.GetChild(0).GetComponent<RectTransform>().rotation = Quaternion.Euler(0, 0, rotation);
NetworkObject netObj = playerBoard.GetComponent<NetworkObject>();
netObj.Spawn();
}
}
You have it so only the server is calling the ServerRPC, which will not work. flip the check around. It should be if(IsServer) return
{
private readonly NetworkVariable<int> _connectedClients = new NetworkVariable<int>();
[SerializeField] private GameObject playerBoardPrefab;
public override void OnNetworkSpawn()
{
if (!IsServer) return;
NetworkManager.Singleton.OnClientConnectedCallback += SpawnPlayer;
}
public override void OnDestroy()
{
if (IsServer)
{
NetworkManager.Singleton.OnClientConnectedCallback -= SpawnPlayer;
}
}
private void SpawnPlayer(ulong clientId)
{
Debug.Log(_connectedClients.Value);
int rotation = 90 * (_connectedClients.Value - 1);
GameObject playerBoard = Instantiate(playerBoardPrefab);
playerBoard.transform.GetChild(0).GetComponent<RectTransform>().rotation = Quaternion.Euler(0, 0, rotation);
NetworkObject networkObject = playerBoard.GetComponent<NetworkObject>();
networkObject.Spawn();
_connectedClients.Value++;
}
}``` Ive been going for this aproach
this works and it spawns the boards
only the rotation is not working
the rotation works on the host but not on the client
Guys if i want to play with a player in US and i am from EU can i play with him with Relay?
Yes just manually have them connect to the same region.
Hey, I cant move with the second player, somehow it just doesnt move, but the animation starts. Here is the important movement code: https://paste.ofcode.org/368BgwSYfccZWkesGfEd4Wh
hello i have little question
is "The Forest" and "Dying Light" multiplayer system client hosting (p2p) or dedicated server?
or something else?
and if isnt self hosting, is self hosting is ok for this games?
If you aren't expecting more than a dozen or so players per server then self hosting should be fine. Check out Valhiem or V Rising.
Its working fine for them so far
hey so i'm looking to learn multiplayer networking for my game and i could use some advice with which framework to use. the key points are:
- i have never worked with any kind of netcode before
- the game is designed to be played by 1-3 players using any combination of local and networked players.
- it's designed to be played with a set group of friends over multiple sessions, no automatic matchmaking or random lobbies. ideally you'd connect through an existing friends list system ie steam but i'll settle for anything that works and doesn't require a dedicated server on my end. which probably means someone has to type an ip address in somewhere lol.
i'd love any suggestions on what networking system to use and why - or which to avoid and why!
Any of the major frameworks will work for you there. You'll need to use a Relay service of some kind. Steam P2P will work with them all too. I'm a fan of Unity Necode. But Photon Fusion, Fishnet, or Mirror are all good choices. Only difference is in price and which feature come built in or not.
I might need some help with networking.
Basically, let's say I have a player script that can be controlled and stunned.
public abstract class BaseSquareController : NetworkBehaviour, IStunnable
{
...
protected bool IsStunned;
...
[ServerRpc]
protected void MoveServerRpc(float horizontal, float vertical) {...}
}```
Question number one - as you see, I tried moving the character with ServerRpc method and it proved to bee quite slow. The game is supposedly fast-pased, and control responsiveness must be great. If I understand everything correctly, Rpc sends the code processing request to the host, the host then changes player's transform and sends it back. This proved to be quite slow even on the single machine.
But giving the player the authority to move is scary - it gives a lot of possibility to cheat. What can I do to increase responsiveness, or maybe I should just suck it up and accept player authority. I saw people in another game called Omega Strikers teleport when they lag, but server rubberbanded them back if they failed to send the information about movement. The responsiveness was great, though.
My second question is:
Let's say I made some walls that supposed to stun people on collision:
public class StunOnCollide : MonoBehaviour
{
...
private void OnCollisionEnter2D(Collision2D collision)
{ ...
IStunnable stunnable = collision.gameObject.GetComponent<IStunnable>();
stunnable.Stun(forceMagnitudeVector, rotationAmount, stunDuration, rotationDuration, false);
}
}
public abstract class BaseSquareController : NetworkBehaviour, IStunnable
{
public void Stun(Vector2 force, float rotation, float duration, float rotationDuration, bool fromPlayer)
{
...
IsStunned = true;
...
}
}
public class PlayerTestSquare : BaseSquareController
{
...
private void Update()
{
if (!IsOwner) return;
if (IsStunned) return;
LookTowardsMousePosServerRpc(FindMousePosition());
ManageButtonMovement();
}
...
}
Right now they are MonoBehaviours - than means they work only on the server or host side. When my client stumbles on them it forcefully moves but on the client side the IsStunned variable is false, which results in weird behaviour when the server forcefully updates the client player location, but client isn't stunned and tries to move instead. It synchronizes when the stun ends.
If client's character would have the authority to move and walls with the StunOnCollide component are supposedly a network object, will that result in minor desync because client moves faster on the client side? I suppose the code will run on both sides, and the results will be the same, but I am worried about this minor desync. I don't know how to appoach it. I decided to ask before testing it for myself.
hello there, when i buy steam direct is steamworks giving multiplayer servers? or whats they are giving about multiplayer
i read doc about steam game servers with unlimited ccu
steamworks gives you access to the steam relay which you can use to connect clients together or connect clients to game servers. It does not host game servers for you, you have to host your own servers.
I might need some help with networking
Hey somehow my character doesnt move when I want it to move
It jumps, and IT PLAYS THE ANIMATION, LOGS THE VALUE WELL, but it just doesnt move at all. Here is the moving part:
{
if (!IsOwner) return;
horizontal = Input.GetAxisRaw(inputNameHorizontal);
//transform.position += new Vector3(horizontal, 0, 0) * Time.deltaTime * speed;
Vector2 PlayerMovementVector = new Vector2(horizontal, 0);
Debug.Log(PlayerMovementVector.x);
//rig.AddForce(PlayerMovementVector * Time.deltaTime * speed);
//rig.AddForce(Vector3.right * 100f);
if (horizontal != 0)
{
if (!canPlayWalk)
{
canPlayWalk = true;
anim.Play("Walk");
StartCoroutine(WaitP2());
}
}
else
{
if (canPlayIdle)
{
canPlayIdle = false;
anim.Play("Bored");
StartCoroutine(Wait());
}
}
Flip();```
Does anyone have some resources i can take a look at about using root motion with netcode for game objects? I've been having problems about clients character being completely still, while the host character is seen by the clients as very jittery, almost as if its string to do the animation but going back to the default pose and i'm pretty stumped about it 
i don't know what's the cause
after a client connects how do i change properties on their character that spawns?
Hi, do you have any suggestions on what approach to follow for a network "blackjack like" game?
The network transform might be overriding the animator's root motion. Try removing or disabling the network Transform
I would use network variables to change player properties
i'll try
For a simple card game just using RPCs should work fine
Yeah but how do I even access the game object?
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:
some weird behaviours happen, the host doesn't see the client moving, but the client sees the host. Animation are still jittery 😢
do I have to spawn things from the network prefab list or can i have network objects already placed in scenes?
nvm answered my own question just testing, i can
I'm having a lot of fun with NetCode. I tried Mirror and i got to say this is much better. there are lots of resorses and tutorials and information. I haven't needed to ask for help yet
❤️
How can I fix this?
So, I am making a snake eating food multiplayer game with NGO but: -
- the client is not able to eat all of its food NO (network object) but passes over it.
- the host's food NO is also visible on the client which is not eatable as well.
Everything works fine for the host tho.
What can be the issue and how can I fix it?
I just dont know how to ask for this complex netowkring help 😅
public class ObjectManager : NetworkBehaviour
{
void Start()
{
if (!hostGame.isHost)
{
Debug.Log("Client Detected, Changing Colour");
NetworkObject playerCharacter = NetworkManager.LocalClient.PlayerObject;
playerCharacter.GetComponent<SpriteRenderer>().color = new Color(116, 255, 0);
}
}
}
my debug.log is triggered but my character does not change colour.
nvm i have the error: NullReferenceException: Object reference not set to an instance of an object
but why is this variable null?
Make sure the client has completely connected. StartI() happens pretty early on.
how do i do that?
im currently working on a solution that calls this method after the relay is joined
having some issues though
If i was using Photon, this would have been an synchronization issue between host and client
Yes it is the same ig here too. How do I fix it?
I only used Photon once, still a rookie in multiplayer field.. I'd make sure that both get connected on same network... Also it should be clearly defined if changes are going to occur on remote or local pc
I think in case of NGO it might be replication issue.. but that's all I can think of
You would need to send a RPC when the food gets eaten
I am but let me try to debug around that. Thank you very very much for replying.
Hey how can I fix this?
Hi, I want to know how can I enable and disable a Unity Network object from Unity Netcode.
So that it synchronises to all the clients.
Is there a way to sync the waves in the new water system between two game instances in multiplayer
You would use network object Spawn() and Despawn() from the host
That is a good question. You would probably make a INetworkSerializable struct to sync the properties with a network variable. The distortions could probably be spawned as network objects if you go that route.
has anyone done port forwarding before?
!collab
📢 Collaborating and Job Posting
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Same goes for you @dusty plover
Hi
I am facing a issue.
I am spawning 2 Players using Relay. And the Player prefab has attached a Canvas to him, but when I test it with 2 players, 1 editor and 2nd build.
Then what happens is only host can see the both Canvas, but player 2(client) doesn't see any Canvas at all.
If anyone can help me, It would be appreciated.
I am ready to let you in by anydesk.
This is Editor as host (1st IMG)
This is Build as Host (2nd IMG)
It's not syncing at all
The UI usually isn't networked. Unless it's a world space UI like name tag it health bar.
Leave the UI local in the scene then have a UI manager that is networked and can update the UI accordingly.
Ok,I'll try and let you know if it works or not.
Thanks.
It's kinda working,
But, Why There is no player in the client?
In host side, both the players are spawned.
But in client side no player is spanwed.
Check this : #archived-networking message
Sounds like the client is not actually connecting. Check for any error messages
Here Im spawning a gamemanger, once host starts a new relay server.
But it doesn't appear in the client side. Resulting in no state change of the game for just Client.
So Host can play the game while Client can't do anything.
And when I'm trying to spawn the GameManager then from host then the players and gameManager are no syncing to the client.
And GameManager is a prefab with networkObject and networkTransform attached to it.
@sharp axle
No errors
You can't spawn anything immediately after starting the host. its not connected yet. the only thing that will happen is that it gets instantiated on the host. I would just leave the game manger in the scene as an in-scene network object
Ok thanks.
I will try to add delay before spawning
Or if it works by just making it In Scene Networked object.
If you instantate the health bar prefab on the client will not be syncd to the network
If its not a network object, then it would be completely local
This is a couple of years out of date but in theory should be able to be updated to work with 1.4
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
why not here? Unreal does that
<#531949462411804679 message> This post on #531949462411804679 talks about it.
I guess that`s why Unreal is growing faster, some one is facing an issue their community people are always eager to help and if community couldnt help their team is always coming forward to help
Hi. I'm just starting to learn how to use ServerRPCs and Network Variables using Unity's new netcode system, and I believe I'm running into a Write Permissions issue, but I need a little insight.
For context, I am making a bomberman style game where players drop bombs to try and kill each other. Before I learned how to use the netcode, I would have the player gameobject spawn bombs, and then the "stats" of the bombs (things like power, piercing, and remote control) would be synchronized by serializing my "PlayerStats" class component into the bomb gameobject, and then the bomb would be able to customize itself using that information. Then when I learned about netcode, I realized that I can't synchronize and network serialize a class over the network, but I could do that with a struct. So I created a custom struct that I use to serialize the stats from the player and send them over the network so that the server can use them to customize the bomb appropriately.
I'm running into some issues doing this, however. Whenever I spawn a bomb using the host player, I don't get any errors. But if I attempt to spawn a bomb using a client player, I run into an error, which I will attach in a screenshot. Here is the code used inside the "PlayerStats" class component:
public struct PlayerStatsStruct : INetworkSerializable
{
public int _health;
public int _power;
public int _speed;
public int _ammo;
public bool _bombKick;
public bool _lineBomb;
public bool _piercing;
public bool _satellite;
public Character _character;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref _health);
serializer.SerializeValue(ref _power);
serializer.SerializeValue(ref _speed);
serializer.SerializeValue(ref _ammo);
serializer.SerializeValue(ref _bombKick);
serializer.SerializeValue(ref _lineBomb);
serializer.SerializeValue(ref _piercing);
serializer.SerializeValue(ref _satellite);
serializer.SerializeValue(ref _character);
}
}
public void SerializeVariables()
{
playerStatsNetworkVariable = new NetworkVariable<PlayerStatsStruct>(
new PlayerStatsStruct
{
_health = health,
_power = power,
_speed = speed,
_ammo = ammo,
_bombKick = bombKick,
_lineBomb = lineBomb,
_piercing = piercing,
_satellite = satellite,
_character = character,
}, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
}
And here is the ServerRPC inside of my "PlayerBehaviour" class component that actually spawns the bomb:
[ServerRpc]
void PlaceBombServerRpc(Vector3 gridSpace)
{
var placedBomb = Instantiate(bomb, gridSpace, Quaternion.identity);
placedBomb.GetComponent<NetworkObject>().Spawn(true);
placedBomb.layer = bombLayer.Value;
placedBomb.name = _clientID.Value + _bombString.Value.ToString() + _bombNum.Value;
playerStats.SerializeVariables();
var bombBehaviour = placedBomb.GetComponent<BombBehaviour>();
bombBehaviour.playerStatsNetworkVariable = playerStats.playerStatsNetworkVariable;
bombBehaviour.bombsPlacedNetworkVariable = playerStats.bombsPlaced;
_bombNum.Value++;
}
You'll notice there are a couple of extra things I didn't mention, like naming and assigning a layer to the bomb when it is spawned. the layer assignment works from both sides, but the _bombNum value only updates from the server side, meaning all bombs spawned by a client always spawn as "0 Bomb 0". It doesn't really matter because I'm only worried about the bombBehaviour.playerStatsNetworkVariable = playerStats.playerStatsNetworkVariable; part because it doesn't seem like the power of the bombs is being properly assigned, and I'm receiving an error that the client is not allowed to write to the object.
Any insight would be greatly appreciated, please let me know if you need any more information, hopefully I provided enough.
I was trying to make my own NetwrokManager and found information from the documentation not seaming to work for me.
Do you set the write permissions on that variable as Owner or Server?
Why are you trying to make your own Network Manager?
I wanted to try and spawn my own custom player prefab
like
a girl or boy character
wait i just realised i can use the Network Prefabs List to spawn a custome player but then how do i not spawn the Player Prefab
or
do i spawn a player prefab the spawns the girl or boy player prefab after spawning the player prefab
just remove the player prefab and you can spawn the player manually
This might help you as well
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval/#changing-the-player-prefab
With every new connection, Netcode for GameObjects (Netcode) performs a handshake in addition to handshakes done by the transport. This ensures the NetworkConfig on the client matches the server's NetworkConfig. You can enable ConnectionApproval in the NetworkManager or via code by setting NetworkManager.NetworkConfig.ConnectionApproval to true.
how do i set write permissions for a server rpc?
not the server RPC. those will always run on the server. The network variable.
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#write-permissions
Introduction
ClientConnectionHandler is in NetworkBehaviour
how dose that overide the NetworkManager spawn player prefab
It doesn't. you dont need to
OH is this setting the NetworkManager PlayerPrefab remotly?
basically. its using Connection Approval to set what prefab gets spawned
thanks @sharp axle ill give it a shot ❤️ ❤️ ❤️ ❤️
I'm guessing it sets the player prefab befor you connect as a client.
I noticed i can make a custom NetworkManager. why would i need to do that?
A custom network manager? You don't. I guess maybe for unit testing or something
you can see that whenever I call SerializeVariables(), it sets the write permission to owner.
I gotcha. In that case, the server can not set the value
I asked ChatGPT to help me better understand callback and it made this: https://pastebin.com/XgAaNaaF
but NetworkManager.ConnectionApprovedDelegate and playerPrefab.PrefabHash are giving me errors
but it looks like netcode uses
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval/
and
NetworkManager.ConnectionApprovalRequest
Photon pun 2 vs mirror
Pros and cons?
I'm not trying to swayed you, but what about Fish.Networking?
Heard it's not as good as the other two
I'd like to know what you've been told if you remember, as I am currently using it without any issues thus far.
Honestly can't remember since it's been a long time, that's why I'm checking which is good
Chatgpt is about 2 years out of date. But also loves to just make shit up
Photon Fusion is the new hotness. PUN is being deprecated I believe.
But I'm a fan of Unity Netcode
Hello, I'm using unity for an uni project where I have to make a mobile AR application.
For this project I want to get Game State Integration from CSGO ( https://developer.valvesoftware.com/wiki/Counter-Strike:_Global_Offensive_Game_State_Integration ) and get player data of a live match into the mobile application.
You have to host a POST Endpoint Server to access the data. I never worked with server stuff and only have done it for the localhost to view data on my laptop.
Now my question is how would I properly transfer data from my Laptop onto my Phone in real time?
Should it be some server stuff or just a wireless connection?
Any tips and directions to look into are appreciated.
Hi, there is a script game Manager in The scene, but the gameManager only running on host side, client side's gameManager is not working.
But the NetworkVaribale is syncing to the client.
And GameManager is in-scene networkedObejcts not instantiated at runtime.
Can anyone tell what's causing the issue?
Actually, I'm toggling(On/off) UI which is a local gameObject in the scene.
So, the Host's side UI is toggling correctly but on the client side the UI is not toggling.
Do I need to attach NetworkObject script to the UI?
if i wanted to network something like a grenade, or just an object wich gets instantiated and is owned by a player, how and where would i start?
Is there like a link where it explains networking (using pun 2). Is there something the can explain authority,ownership, and how it works?
The UI itself should not be networked. But you should probably have a UI manager that is networked and can update the UI with RPCs or network variables
This depends on which networking framework you are using
You can find the photon discord here. They should be able to link you to the relevent docs
https://dashboard.photonengine.com/Discord/JoinPhotonEngine
Manage your global cross platform multiplayer game backend.
PUN 2.0?
ok, check the link I just posted for photon info
alrighty!
Thanks
Am i not able to spawn / Instantiate from "Network Prefabs Lists"
is the "Network Prefabs List" just referencing and keeping an eye out for if those things are created?
You should be able to. Are you getting an error when you try to instantiate something from the list?
You don't need the clientRPC there. Use OnNetworkSpawn() in the game manager to call the serverRPC. as long as the custom players in the game manager are also in the prefab list, it should spawn.
You should also be able to reference the prefab list directly by using FindObjectofType<NetworkPrefabList>()
how do i get prefab from list?
GameObject playerClone = Instantiate(FindObjectOfType<NetworkPrefabsList>().PrefabList[0]);???
i think i figured it out
GameObject playerClone = Instantiate(FindObjectOfType<NetworkPrefabsList>().PrefabList[0].Prefab);
Does anyone have any good resources for learning how to protect my game properly from injection attacks?
Or maybe just a resource that goes over general/common exploitative behavior to protect against in a multiplayer game
Nope not working 😿
You'll need to break it down to figure out which function is not being called or what is returning null
It's hard to give general advice since it's different for every game. The most generic advice is to always assume the client is a bad actor. Only accept inputs from the client and always double check those to insure they are valid.
I tried asking ChatGPT but its very confused.
ChatGPT is about 2 years out of date.
how do i reference the prefab list directly by using FindObjectofType
You are doing it there. You can also just make it a public NetworkPrefabList and drag it into the game manager
MyDebugger.myDebugger.Log("Setup Player Server Rpc");
//GameObject playerClone = Instantiate(customePlayers[0]);
NetworkPrefabsList prefabList = FindObjectOfType<NetworkPrefabsList>();
GameObject playerClone;
MyDebugger.myDebugger.Log($"Prefab List " + prefabList);
for (int i = 0; i < prefabList.PrefabList.Count; i++)
{
if (i == _selectedPlayerID)
{
playerClone = Instantiate(prefabList.PrefabList[i].Prefab);
MyDebugger.myDebugger.Log($"Prefab Name " + prefabList.PrefabList[i].Prefab);
}
}
Dosnt spawn anything and says there is nothing there
Oh I guess if you have more than one then it might be finding the wrong one
What is it not finding? the prefab list or the prefab itself?
It says this is the problem
Do i need to
networkManager.gameObject.FindObjectOfType<NetworkPrefabsList>();
instead of looking for it i just made a NetworkPrefabsList variable
but the player only spawns on the host not the client and i cant move the host player
[ServerRpc(RequireOwnership = false)]
public void SetupPlayerServerRpc(int _selectedPlayerID)
{
MyDebugger.myDebugger.Log("Setup Player Server Rpc");
GameObject playerClone;
MyDebugger.myDebugger.Log($"Prefab List " + plrefablist);
for (int i = 0; i < plrefablist.PrefabList.Count; i++)
{
if (i == _selectedPlayerID)
{
playerClone = Instantiate(plrefablist.PrefabList[i].Prefab);
MyDebugger.myDebugger.Log($"Prefab Name " + plrefablist.PrefabList[i].Prefab);
}
}
}
Im still trying to understand the concept of NGO and NetworkVariables, do network variables automatically sync based on some network ID?
Correct me if im wrong: My current understanding is that if i have 2 players (1 host, 1 client) and a script on the spawned player prefab, there are essentially 4 versions of this script [see image]. Then a network variable is used to sync values so there arent 4 different values of a variable, only 2?
public NetworkVariable<string> playerName = new NetworkVariable<string>("Player Name");
public void OnNetworkSpawn()
{
playerName.OnValueChanged += NetworkPlayernameChange;
playerName.Value = names[UnityEngine.Random.Range(0, names.Count)];
}
private void NetworkPlayernameChange(string previusValue, string newValue)
{
//Do something
}
I know how to use a network variable, im just trying to see if my understanding is correct
basically yea. the network variables are tied to the Network Object. Network Objects will get replicated to all clients and the server
ok thanks 
Hey I'm new to Netcode for GameObjects and Networking in general!
Any idea where the NGO SDK sits on the OSI (Open systems interconnect) model ?
Layer 7 (maybe 6 to some extent). Like pretty much any networking solution for games.
Hi, So I wanna know How Can I pass a List<Xclass> as a parameter to clientRPC call.
RPCs need to send value types and nullable reference types will throw an error
Any workaround?
I will normally use a NetworkList
You could also serialize the list as Json and send that
Can we create list in networkvariables?
Ohk
no. but I believe nativearray support is coming in the next update
Ok, thanks.
I appreciate it man🙂
I was reading this article https://gafferongames.com/post/udp_vs_tcp/ so that I could try to understand the use cases for UDP and TCP in multiplayer games. It was published in 2008. Is this a good reference, or did their use case change over time?
Gaffer on Games is one of the best resources for learning the theory. But the vast majority of game networking is done over UDP or some custom UDP variant. Only webgl with websockets would be using TCP
why dose importing Multiplayer tools Samples give me so many errors and how do i fix?
What version of Unity are you on?
What's the best way to make a multiplayer physics based game sync properly? It's turn based to latency isn't much of a problem, but collisions look either goofy because of interpolation or choppy when I use network transform. I am using normal physics rn but its not deterministic so the server sync is really visible which I don't really want
Using Netcode for GameObjects
Network Rigidbodies should be fine if input latency isn't an issue. Just make sure they are owned by the server.
Yea but the syncing looks quite choppy, and collisions look unrealistic with interpolation. Is there a way to extrapolate or something to make it smoother?
why can't i network this?
OrdnanceType Is an enum
You would have to implement your own client prediction.
Is there a way to have a player ping a server for some simple information and to validate that its online? I'm working on a current setup for it but it involves a player joining the server, sending, recieving RPC, and then getting kicked once done. Feels ineffecient
am i unable to use it with new vertions of unity?
That's the version I'm on. But I haven't loaded the tools sample before
You can use a regular Ping, but that's not going to get you much information. If you are using Multiplay server hosting then you can access the Server Query api
I'm not gonna be using Multiplay, servers will be run through the Relay service
Ill uninstall the Samples for now then
You can't even ping the servers in that case. Best you can do is query the relay service for regional connection quality
Welp guess forcing players to connect is the only option then
I'm starting out with Netcode for game objects and trying to get the camera to follow the their own player.
So im doing GetComponent<CinemachineVirtualCamera>().Follow = NetworkManager.Singleton.SpawnManager.GetLocalPlayerObject().transform
However GetLocalPlayerObject() appears to be null on the client - even though it has spawned in a player
I've also tried NetworkManager.Singleton.LocalClient.PlayerObject wit hthe same result
you can just disable the camera for other players
Currently my camera is apart of the scene, that would mean moving it into the prefab right?
I have mine currently like that, but otherwise u could try just having a script setup the cinemachine references on start
like
if(isOwner)
// setup reference
not really sure if this has any downsides, but really 1 camera for each player shouldnt have a difference in performance. Its not like they are networked or will lag anything since they are disabled
Yeah it makes sense, I think I did try something like that but had an issue with Ownership, let me try again
Oh no that's just working fine now haha just made a script with the 1 line private void Start() => this.gameObject.SetActive(IsOwner);
Checkout how the Client Driven Sample does it. Its using the 3rd person controller and cinemachine as well
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven/
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
Either Photon Fusion or Netcode for Entities
Maybe true for certain genre's ie FPS, but for sure not true for most other genre's, ie MMO's like WoW or RPG's like Diablo etc use TCP
Diablo 3 and 4 (can't speak on older ones) don't use TCP. Any modern game with high quality netcode will avoid TCP as there is 0 reason to use it over a UDP protocol that can do everything that TCP can but more and better in a way that is optimized for the game. Even the generic RUDP protocols like ENet or KCP are better than TCP in every way for realtime multiplayer.
@vagrant garden https://github.com/blizzless/blizzless-diiis/blob/5e404e774650ddfe1a04c8be9b65125dfc1c6f4c/src/DiIiS-NA/D3-GameServer/ClientSystem/Base/AsyncAcceptor.cs#L27
Yes this is for connection management and for the tls streams. But for the gameplay it uses raw udp sockets.
Hey, I'm planning to try building a multiplayer game. Haven't touched multiplayer before. For now I am planning to use Unity's Netcode.
I've a question regarding that.
A contextual summary before;
My game, in essence, will be a multiplayer car game, something similar to Forza. The player will join a kinda open map and just drive around, and challenge other online players to race if they meet in the map.
I'm thinking around the lines of having a server build (haven't done this before either) that will handle all the location updating of the online players and the players will by default connect to this server when they press play, and will spawn in.
For controlling the cars, I'm planning to use RCC (Realistic Car Controller) controller (by BoneCracker Games).
I've a spare laptop that I can probably install this server build on and it will act as the server.
Now my question is what things do I need to consider (just on the connection side) or what should I know before I can implement such server that will do what is mentioned above?
And will the RCC work with Netcode and the mentioned setup? or will I have to implement my own controller?
Sidenote, but I would make sure to check Edy's vehicle solutions. RCC is quite a mess.
Alright, I'll look into that as well
I asked how I'd sync a physics based game properly yesterday, but I think I need more help. This message is quite long but it has a detailed description of how the game works
The game is turn-based, the players apply force to coins in order to knock them off the area. The client selects the amount of force to be applied and sends it to the server which handles the physics calculations
I already set up some sort of a client prediction system, but Im not exactly happy with it, here's basically how it works
-The player selects the amount of force to be applied
-The client sends this force value to the server
-The server receives the force and performs physics calculations, using the Rigidbody2D.AddForce(force) method
-The server then sends the force value to all clients, and each client independently performs their own physics calculations using the same Rigidbody2D.AddForce(force) method
-Once all calculations are completed and the turn is over, the server sends the current state of the game to all clients
-The clients sync their game state with the one received from the server
This works, but there is a major problem. The syncing is very visible, as I tween to the server's state. This is mostly fine, but in some cases, the client's calculations may say a coin has fallen off, but the server's calculations are slightly different, and the coin is actually still in the game. The player has just watched the coin they attacked fall of the map. Then the server syncs, and bam the coin is back. This'd make them feel cheated.
Code: https://pastebin.com/aLdUMfHu
Any suggestions?
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
quick question about NGO, i have initialized a vector2 network variable (default value = vector.zero, read perms = everyone, write perms = owner), now i'm trying to modify the X value only of this vector2 but its not allowing me as its sayign that vector2.Value.x is not a variable, is there something i am missing in the inizialization or do i have to create another temporary vector2 and then assign it entirely to the network vector2?
You should be able to write something like vector2.Value = new Vector2(newX, vector2.Value.y);
Hey I'm trying to restock weapons, where if a player picks 1 up, it'll wait a second and spawn it right there where it was. But I'm doing this in multiplayer, and I despawn it whenever the player picks it up, so the weaponToRestock is null. But why?
Not sure how kosher this is but I figured I'd xpost this for exposure: https://forum.unity.com/threads/dots-manually-listening-connecting-with-clientserverbootstrap.1443439/
Does anyone have a sample / example of manually connecting using the ClientServerBootstrap?
You can find the bootstrap sample here on github
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/NetcodeSamples/Assets/Samples/HelloNetcode/1_Basics/01_BootstrapAndFrontend/BootstrapAndFrontend.md
I'll check this out. Thank you!
Hey I'm a beginner to NGO! Any idea why my my movement feels sluggish
I use character controller to move
if I tap the keyboard, it feels responsive, but if I hold it for abit, it stops after a while
oh my bad
that had to do with input.getaxis
can i network an enum like this?
Figured it out myself!
Hello!
I am working on a simple multiplayer game with Unity Netcode for Gameobjects but I'm having a issue where the NetworkList playerDataNetworkList is not updating on the client.
This is the start of the class that contains the NetworkList (Called PlayerDataManager)
//Singleton
public static PlayerDataManager Instance { get; private set; }
//Network Lists
public NetworkList<PlayerData> playerDataNetworkList;
//Events
public event EventHandler OnPlayerDataNetworkListChanged;
private void Awake()
{
//Initialize Network Lists
playerDataNetworkList = new NetworkList<PlayerData>();
//Singleton
Instance = this;
DontDestroyOnLoad(this);
playerDataNetworkList.OnListChanged += PlayerDataListChanged;
}
[ServerRpc(RequireOwnership = false)]
public void SetPlayerPieceId_ServerRpc(int pieceId, ServerRpcParams serverRPCParams)
{
if (!IsPieceIdFree(pieceId)) return; //IsPieceIdFree is just a function that checks if the requested piece has been taken
Debug.Log($"Set Piece ID. Sender: {serverRPCParams.Receive.SenderClientId}");
int playerDataIndex = GetPlayerDataIndexFromClientId(serverRPCParams.Receive.SenderClientId);
PlayerData data = playerDataNetworkList[playerDataIndex];
data.pieceId = pieceId;
playerDataNetworkList[playerDataIndex] = data;
}
And this is the PlayerData struct
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
public struct PlayerData : INetworkSerializable, IEquatable<PlayerData>
{
public ulong clientId;
public FixedString128Bytes username;
public int pieceId;
public bool Equals(PlayerData other)
{
return clientId == other.clientId && pieceId == other.pieceId && username == other.username;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref clientId);
serializer.SerializeValue(ref username);
serializer.SerializeValue(ref clientId);
}
}
I've tried different things but when updating the list on the server it doesn't sync with the client.
There's also this function that both runs on the client and on the server.
public void LogData()
{
foreach (PlayerData d in playerDataNetworkList)
{
Debug.Log($"ID: {d.clientId} - Piece: {d.pieceId}");
}
}
The Debug.Log() on the server is different from the one on the client, something that should not happen with network lists.
Make sure only one of the Singleton are in the scene. I try to avoid them at all costs. In scene items get respawned when the scene loads. That might be causing issues with So not destroy on load
I'm pretty sure I have only one Singleton, but if I don't I would be really disappointed in me :/
Indeed, I do not have 2 singletons
I'm using NGO and getting these errors
And im not sure how to hunt down what's causing it, any advise on how to debug this?
Hi everyone
Is anyone using Photon Fusion with Unity please? We have to use it on a project in class and I have to implement a turn based system that replicates and synchronise to multiplayer
But Photon's doc on Fusion is terrible for now and I'm completely lost
You can find a link to the Photon discord in the pinned message here
There is, join via the dashboard as explained in the pinned mesage: https://dashboard.photonengine.com/Discord/JoinPhotonEngine
I'm new here and I was wondering what do i need to know/learn for programming a multiplayer game
Are you new to making games with unity?
Yes I've just learned java thanks to university and i wanted to dive into unity
I'm only familiar with the user interface
You'll want to start with getting the fundamentals of C# down first as that's what unity scripting uses.
Has anyone ran into issues where it seems like the NetworkStreamDriver isn't processing messages unless the game is focused? I have a build for my server and client and the connection doesn't even complete successfully unless I switch between both .exes
RunInBackground is set in the build settings?
Hello, how can I use SetActive in Photon, to hide an object for both players? I tried this way but it gives an error:
GameObject nesne = liste[0];
PhotonView photonView = GetComponent<PhotonView>();
photonView.RPC("gizle", RpcTarget.AllBuffered, nesne)
[PunRPC]
void gizle(GameObject nesne)
{
nesne.SetActive(false);
}```
The error:
``Exception: Write failed. Custom type not found: UnityEngine.GameObject``
You are sending a custom class as an argument. you can`t do that.
You could try determining the object thru other means.
I understand, but I dont have any other idea. I'm a beginner. What can I do?
well, give me some context. what is the object you are trying to toggle used for?
It's an image in Canvas.
aha
then you could attach a script to that image and a photon view and via an RPC call you could simply toggle this.gameObject
Oh, did I get it correct?
The Image is x and it has a photon view, and there is a script on MainCamera so it's y
I will use this in y:
x.photonView.RPC("function", RpcTarget.AllBuffered);
x script:
void function(){
this.gameObject.SetActive(false);
}```
That's not a problem because I come from java and I saw that the basics are the same.
I searched on the unity learning resources but I didn't find anything about networks
I would do it like this:
<Script on the Image you want to toggle>
[PunRPC]
public void ToggleThis(bool state){
gameObject.SetActive(state);
}
<Script wherever you want to toggle it from>
public GameObject TheImage;
public bool TargetState;
public void ToggleImage(){
photonNetwork.RPC(TheImage.GetCombonent<PhotonView>(), "ToggleThis", AllBuffered, TargetState)
}
@long totem
Thank you so much!
No problem!
this was forever ago when I asked this but incase anyone else is curious, you can actually ping players server info without joining by hiding the data inside the NetworkManager.ConnectionApprovalResponse.Reason
That's not a ping though. That's just attempting to join. If the server isn't running the client won't get any info
Howdy folks! I'm working on an online-synced projectile, and I have some questions. My script currently instantiates a prefab with a script that tells the projectile what to do. It then assigns a field in that script to a ScriptableObject which has the information on that specific projectile type (eg. movement speed and damage). I currently have two ideas:
-
Use a ServerRpc to spawn the projectile online, then somehow send an ID of the ScriptableObject to the client-side projectile. Then, simulate both projectiles seperately with server-authoritative checks to make sure the transform is correct.
-
Use a ServerRpc and a ClientRpc to instantiate the projectile on all sides. Instead of sending over the ID of the ScriptableObject give the hotbar slot that the projectile was from. Then, simulate them on all sides, again using server-authoritative checks to make sure the transform is correct.
If I made any of this confusing or unclear, feel free to ask me to clarify anything.
I mean if its not running then that's still info, I'd still consider it a ping, just that the info is "Server is offline"
Both will work.
1 is more server authoritative and what I usually do.
2 gives more control to the clients. If you are in any way worried about cheating, I would avoid that one.
Great, thank you very much!
With 2 you can also just instantiate a dummy projectile on the clients just to give visual feedback. But all the real logic can still happen on the server
I may consider that, but I'll probably go with 1 so I can have the projectiles better synced.
Guys when it comes to multiplayer games, especially ones with massive player counts like 64 v 64 matches, what stresses the server to the max?
Like for instance is it voip, or guns with projectile based bullets?
Your main bottleneck at that scale is going to be network bandwidth. There is a reason why battle royales rarely go over 100 players
Ohhh, could u talk more in depth sensei?
lol, I'm no expert in this myself. But it really depends on your game. If your game has like 50kB/s of data per player. 128 player matches adds up real quick.
Where do game devs go to learn about networking exacy?
Like is there a big book or something?
Your packet size and rate also comes into play. The different frameworks have a Maximum Transfer Unit(MTU) where they will send data in multiple fragments. Sending lots of large data will fill up the queue and things will begin to lag
check the pinned message here. Resources there has some greate stuff in it
Hello. In my game I have network objects that move until they reach a certain point then teleport back to a previous point. This works for the host but for clients the network objects fly across the screen instead of going there instantly. (using network transforms) How can I fix this?
You can disable the network tranforms while teleporting. Or just turn off interpolation
Turning off interpolation worked. Thank you!
Hello, does Unity have a specific owner client ID value to represent a null ID? I couldnt find one in the docs.
public NetworkVariable<ulong> CurrentInteractorClientID = new NetworkVariable<ulong>();
I have something like this to keep track of the client that is holding an object, but when its not holding anything, I am not sure what to set this value to. I couldnt find anything in the docs, so I am curious if you all have an answer
Im considering just using the max value for ulong but I dont know if unity has a specific recommendation
my particlesystem is displaying another one slightly lower on the other end
for both the client anf host
maybe shows for host more often
Has anyone tried Multiplayer Play Mode? On two different projects, the player 2 window simply freezes up on me
https://docs-multiplayer.unity3d.com/tools/current/mppm/index.html
Multiplayer Play Mode (MPPM) enables you to test multiplayer functionality without leaving the Unity Editor. You can simulate up to four Players (the Main Editor Player plus three Virtual Players) simultaneously on the same development device while using the same source assets on disk. You can leverage MPPM to create multiplayer development work...
Client Id is a value type. It can not be null. Default ulong I believe is 0
Make sure you and in Unity 2023 beta
Yes I know 😄, this is not really my question :P
I am curious if Unity considers any specific value for the ulong reserved to represent an invalid/empty ID
It does not
I am (2023.1.16 and 2023.1.20)
so I'm making a 3d multiplayer game, I want each player to have they're individual camera, I'm having this issue when player 1 joins, everything works just fine but when player 2 joins, player 1's view switches to player 2's view, is there any way to fix this issue?
i am using photon pun 2
Dunno. Some other folks had issues with it on Linux. I think they put in a git hub issue on the main repo
Disable the camera on the remote players. There should only be one active camera in the scene
Hello, I got this error in Unity Photon. What should i do?
Exception: Write failed. Custom type not found: System.Collections.Generic.List`1[System.Int32]
Code:
GetComponent<PhotonView>().RPC("setImages", RpcTarget.AllBuffered, IDlist);
[PunRPC]
void setImages(List<int> IDlist)
{
for (int i = 0; i < IDlist.Count; i++)
{
cards[i].sprite = images[IDlist[i]];
}
}```
Sounds like you can't send lists in a photon RPC
Oh yeah, i thought that but i was not sure
Then how can I send this list alternatively
No clue. Maybe an array? I don't use Photon
You can find the discord here
https://dashboard.photonengine.com/Discord/JoinPhotonEngine
Manage your global cross platform multiplayer game backend.
it works for the host but not for client [the client calls the debug for "Server RPC Used" but none of the others]
the interaction works and is synced too its just that the non host client is unable to interact (but it calls the ServerRPC and gets the debug for Server RPC Used)
ive been debugging figured out problem i think but any advice anyway always welcome
how do i get the Player object from the client ID that owns it?
What networking solution are you using?
network for game object
NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject;?
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/
ty
The server is the one running the RPC. PlayerCameraObject in that raycast is the hosts.
Hello, I wanted to achieve it myself at all costs, but for several days I can't find a solution.
I am loading a Core scene at the start of the game, which includes Network Manager and other Managers. Then I load async the levels to have the game world scenes separated from the core part. I want to spawn the players only from the Core scene, but only when a async of the game scene is completed. How can I achieve this? I am a little bit confused after switching to NetCode and maybe I understand something wrong. Could someone shortly explain it or send maybe some manual of such thing?
You would use LoadEventComplete scene event to know when all the clients have loaded the main scene and then you can spawn your players
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events/#tracking-event-notifications-onsceneevent
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
@sharp axle omg, thank you, look promising
Is this the most appropriate channel to ask questions around Game Server Hosting implementation trouble shooting?
#archived-unity-gaming-services Might be better
Appreciate it.
I ended up fixing it, the RPC wasnt the problem at all it was the fact that I didn't put a network transform (client network transform cause im using that for the players movement) on the parent object of the camera (I have it so I can setup camera shake without ruining the raycasts from the camera)
danke for the help tho appreciate you gamer
Does someone has been working on a game and has been using Steam Inventory using Steamwprks.NET? (please reply with ping)
Anyone here used braincloud? Trying to decide between braincloud or netcode for gameobjects + UGS for an online turn based strategy game
I’m open to other suggestions as well, some detail about my game: turn based, up to 8ppl per match, will want to implement in game text chat, leaderboards, matchmaking
@graceful zephyr apologies for the tag, https://github.com/nxrighthere/NanoSockets do you know if this is compatible with android by any chance?
should be
seems unlikely?
mine works on desktop, and in editor, but doesn't on android
would you recommend anything a bit more mainstream as a replacement library? I'm thinking of using Unitys new transport, but wonder if it'll have any performance issues
going to debug this a bit more next few days, have you ever used it on an android device? It would help to know its something i've gotten wrong
no it does work on android
yes ofc i have because im one of the lead dev on fusion (the documentation page you linked to)
You need to compile android binaries yourself.
hey is there anybody whos using Mirror networking? Can anybody help me with connecting to a host via internet? FAQ doesnt really tell anything at least i dont see anything
Is there a way to get a callback or overwrite a methode when a player gets spawned with the prefab?
I want to add the player transform to my camera target list.
Any clue?
wait can I retrieve the players gameobject via the onPlayerConnected... callback?
I'm trying to add a player to my camera target list but all the callbacks provided were ID's
Hey guys I'm planning to start making a Multiplayer game and wanted to know if unitys new Netcode is in a good enough place to learn/impliment it or if I should go with a 3rd party like mirror?
Depends on the kind of game. Currently the Unity netcode (Netcode for GameObjects) is targeted at games that fall more on the smaller scale / co-op type games.
The closest game to what I'm making is "Project Zomboid". By scale I assume you mean connections, so I'd say probably say up to like 8 players tbh.
So in that case it's fine?
You can probably make something like that in Netcode for GameObjects, whether it's ideal, is another question. Most multiplayer solutions should be able to handle that so it's a matter of preference.
Okay thanks Lukesta 🙂 I just didn't want to get through my project to witness anything essential not being in the package yet
I would say it's pretty robust, definitely a good thing lately.
That's good to know, thank you!
I'm also relativly new to netcode for gameobjects, but I've managed player movement, animations & physics syncing in a couple of hours
That actually worked.
Instead of
if(isClient)Debug.log("client");
if(isHost)Debug.log("Host");
if(isServer)Debug.log("Server");
is there a
Debug.Log(network.typeThing);
?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using TMPro;
public class CreateAndJoinRooms : MonoBehaviourPunCallbacks
{
public InputField createInput;
public InputField joinInput;
public TMP_InputFieldcreateInput;
public void CreateRoom()
{
PhotonNetwork.CreateRoom(createInput.text);
}
public void JoinRoom()
{
PhotonNetwork.JoinRoom(joinInput.text);
}
public override void OnJoinedRoom()
{
PhotonNetwork.LoadLevel("Game");
}
}
whats wrong here? i want to use TMP for the lobby
Check out the examples. You don't necessarily have to load the scene on every client if automatic scene syncing is enabled.
where do i find examples?
Doesn't it come with some in the PUN folder?
idk where they are
Have you looked? 😄
oohhh u mean those?
Somewhere in the Photon folder most likely, but probably not in PhotonChat
...
im new in this so sry. idk which i should use for lobby and loading scene
Look at them to see if they look like they have the functionality you need. There should be scenes in there that you can open and play
If you feel completely lost, I would recommend doing a few more singleplayer projects before adding all this complexity.
im that guy who goes full into something. all or nothing
Sure, just don't aim into a wall 😄
@spring cranebut is this code even bad? cant i just use that?
Looks reasonable, but I don't remember the details. There is some quite similar code in the examples for a reference.
Should share some more details of what is happening. Odds are PUN is giving some sort of feedback in the console assuming the methods you posted run at some point
Good day, Multiplayer Floating Origin. Anyone have experience or willing to discuss ?
Hi, I'm currently working on a two-player football game (players switch roles trying to score, whoever has most points wins), and I have this issue where it seems to duplicate the room host on start-up rather than actually adding a new player. Anyone got any idea what the issue could be (I have very little experience with networking)?
pretty sure you need to do createInput.text.ToString()
Hi, when using a client authoritative solution (with netcode for gameobjects) and using the default position threshold (0.001), movements from either two players (host or client) sometimes cause the displayed position to be incorrect for the other one. usually this is very noticeable and is a large difference in position. Setting it to 0 fixes it but that doesn't seem efficient. Should I instead use server authoritative or is there a possible solution?
someone here? 🤔
help! NetworkManager.Singleton.StartHost(); does not work and this error is being shown. What should i do?
Hi. I am starting a new project with a friend and we want to go for online play this time. We would like to do it as "real" as possible and instead of directly connecting like our projects have done so far, create a server version that we can connect to and handle the logic on. If we create that to run on one of our computers at first, how hard is it to later transition to something like playfab as hosting for it?
So, I've got a toggleable light on a player prefab, but when I toggle the light on and off it doesn't sync that to server or other clients. Looking for how I can fix this.
If you have asmdef files you will need to add Netcode to it.
Thanks, although I am not familiar with asmdef files. How can I add Netcode to them?
You can use a relay service like Unity Relay or Steam P2P for player hosted servers
I would like to avoid player hosted servers - it's a 1v1 game similar to a card game, and we would like to host very little on the actual clients if possible.
You can build it as a dedicated server and still use the relay service to connect to players. Otherwise you're stuck setting up port forwarding and that's a major pain in the ass
Easiest way is to use a network variable bool to sync the toggle state to the other players
Thanksa lot
I'm going through the multiplayer networking tutorial, works great, but I've noticed one problem: When I use command line to spawn instances of the app to test with, audio is completely off. Any reason why this might be and how to fix it?
Works fine if I just execute the app normally or hit Run in the editor, this seems specific to launching via command line
Hello,
I'm using Photon PUN to make a multiplayer game.
I am using objectpooling to spawn the enemies and explosions that occurs on the enemies when get hit.
The enemies and explosions have PhotonView component and PhotonTransformViewClassic component with Synchronize Position enabled.
The master is working flawlessly. However the client could not get the list from the pool. When I place a breakpoint, it says the list is 0.
How can I make sure the object pool list is carried across? Or should I be approaching this in a different way?
The error I get is "ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection." which makes sense because the list is 0
See image for code
I've made the basics of a networked 2d sidescroller using NGO but struggling to deal with the latency.
- I initially started doing it server authoritative, but even running locally it was laggy, turning the Physics Fixed Timestep down, along with turning the Network Manager tickrate up helped but I feel like it was masking the problem, any real scenario would have higher latency
- Client side physics calcs for your own character, broadcasting positions - using ClientNetworkTransform, however the player often ends up hovering just a tiny amount. If it wasn't for the hover desync this would probably be fine.
- Client side physics calcs for your own character, broadcasting inputs but the desync was too strong here
I feel like having some sort of "action queue" might help, since i noticed in 1. and 2. that a jump would sometimes be missed, meaning that the frame jump frame never got send. But I'm struggling to find good tutorials on this.
Any advise on how to make it smooth and without desync?
in netcode for gameobject who can despawn network objects?
the server/host
Pooling does not carry over. It is local.
Each time some object returns to the pool, it no longer resembles a networked object and when you re-use some object it resembles a specific (new) networked object (PhotonView / viewID).
In best case, you build a pool implementation for the built-in IPunPrefabPool and make PUN use it. Then you don't have to worry about the PhotonView setup and simply continue using the PN.Instantiate.
The doc page is here:
https://doc.photonengine.com/pun/current/gameplay/instantiation#using_the_prefabpool
And most of the implementation advice is actually in the reference for the interface, methods and so on.
Most multiplayer games need to create and synchronize some GameObjects.
Maybe it's a character, some units or monsters that should be present on all...
My custome player spawn system seams to be working but
Is there a way to let the network manager know i am using my own GameManager player prefab system?
This warning can be ignored
Thanks @sharp axle
Thanks, this worked. Does it make a difference if I use the OnValueChanged event rather than put an if statement in the update loop? I couldn't get OnValueChanged to work but it seems like it should be used here.
make sure you are subscribing to it in OnNetworkSpawn()
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#onvaluechanged-example
Introduction
Why isnt my GameManager custom player prefab script working.
https://pastebin.com/C7kcEqU7
If this is for the player then you should be calling SpawnAsPlayerObject()
Thanks @sharp axle i think it worked i just need to get the player to controll its own play or sawn it so the player that spawns there player controlls there player
am i suposed to use use LocalClientId?
NetPlayerPrefabClone.GetComponent<NetworkObject>().SpawnAsPlayerObject(networkManager.LocalClientId);
I dont feel like i'm doing this right.
No, you use serverRPC params to get the sender of it.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/serverrpc/#serverrpc-ownership-and-serverrpcparams
Introduction
HELP GETTING RAYCAST TO HIT UI ELEMENTS
public void MyGlobalServerRpc(I need to Pass the LicalClientId through Here?! using an ulong)
nope didnt work
when the ray hits the ui GetComponent the ui and invoke button press OnClick()
no, you put in ServerRpcParams serverRpcParams = default there in the parameters.
then clientId = serverRpcParams.Receive.SenderClientId;
OH so you actually have to use that bit of code ServerRpcParams serverRpcParams = default i thoght that was just an example
right that makes sure the default params will always get sent without you having to constantly create new ServerRpcParams