#archived-networking
1 messages · Page 39 of 1
I just tried loading a different empty test scene, and that works just fine.. Must be something in my main scene.
whats the best way to create prefabs for objects that players shoot that are similar to projectile, woulde it be to create scriiptable objectsm and load a database of the info after the player creates it, and use the scriptable object info to spawn it on every client. Or would it be to create like a network object prefab with synced network transforms via ;unitys built in network transform. I feel like unitys built in system for network transforms is not good when it comes to calculating precision collisions etc
I think you would only use network objects for things like slower moving rockets or grenades. Raycasts and particle systems for everything else. SOs are not a bad choice for setting those up. If you keep them in a big list then you just need to send an ID or index to all the clients so they play the right effect locally
Is it normal that any other scripts that are on the prefab spawned by the network manager are not owned by the player, despite the network object script on the prefab it self being owned?
network behaviors get their owner from the network object. I don't think its possible for them to be different
If each client stores their selected materials in a singleton (StorePlayerSkin), and the server applies the materials to each player's prefab, shouldn't each player get their own unique material? Why are all player prefabs ending up with the same skin?
using Unity.Netcode;
using UnityEngine;
public class SkinApplier : MonoBehaviour
{
/*
No Inspector referênciar os Renderes
*/
[Header("Mesh Renderer Reference(Partes, para aplicar as skins)")]
[SerializeField] private Renderer headSkinRenderer;
[SerializeField] private Renderer bodySkinRenderer;
private void Start()
{
ApplySkinsServerRpc();
}
/*
Cada função serve para aplicar o material guardado no singleton "StorePlayerSkin" no respetivo mesh.
*/
public void ApplyHeadSkin()
{
if (headSkinRenderer != null)
{
headSkinRenderer.material = StorePlayerSkin.Instance.GetHeadSkin();
}
}
public void ApplyBodySkin()
{
if (bodySkinRenderer != null)
{
bodySkinRenderer.material = StorePlayerSkin.Instance.GetBodySkin();
}
}
[ServerRpc]
private void ApplySkinsServerRpc()
{
ApplyBodySkin();
ApplyHeadSkin();
}
}
Ended up doing this, now I’m trying to create custom ui system, very time consuming
Singletons are not shared across the network. If this is on the player object, then they are all calling from the same player skin singleton on each client. The renderer material will not automatically sync.
Also your serverRPC will only run on the host/server
❤️Any insights or suggestions would be greatly appreciated. Thanks in advance!
Hey, this questions has probs been asked before but can anyone suggest any good courses / books / videos e.t.c to begin learning networking? I'm interested in doing a 2-4 player co-op kind of stuff, nothing too crazy.
Also the Code Monkey multiplayer courses are probably still the most comprehensive ones out there
hey guys! anyone seen this before?
i'm having an issue with Photon Fusion — was working fine, didn’t touch anything, and suddenly it started bugging out between test runs.
feels like a config thing but not sure 🤷♂️
```FieldAccessException: Field Fusion.NetworkBehaviour:Ptr' is inaccessible from method Twinny.System.NetworkedLevelManager:set_manager (Fusion.PlayerRef)'
that looks like the access modifiers are different between what you built against and the actual library being loaded, maybe this access modifier changed in an update and you've got an old version cached somewhere or something?
So I need to reference the material by any means then ask the server I want to use that material on the local client then sync to others?
Generally, you keep the all the materials in a list then you can send then index of the material you want in an RPC or network variable. then all the clients swap the appropriate material
posted this in advanced as well but then i saw there was a networking area anyway im making a multiplayer game and im trying to use Scriptable Objects but using NGO Scriptable Objects dont network. So I come to ask what is the solution to still using the modularity of Scriptable Objects but still be able to network them
Actually same answer as above. Keep your SOs in a list and reference them by index
ok thank you
Unity sent me bill, I didn't even exceeded the relay limits prev month
I was almost at 98% and still got charged
This made me cancel my Unity subscription
am I missing something here? I thought Relay Bandwidth free tier was 150 GiB?
It's 3gb per CCU up to 150gb total. Some crazy bandwidth usage had to have been going on there with only 11 CCU.
I thought the 3 per CCU for up to 150 was just an estimate to pair with the free 50 CCU
Bandwidth is separate from the CCU limit.
I'm aware of that
At least it's listed separately
is that 119 he's being billed for 119 beyond the 150?
Seems like it - just weird if it's listed like that as everything else lists the quantity with the free tier included
That is a good point
If that's the case @waxen quest you were miles beyond 98% usage.
Either that, or there was a mistake in your billing - but that seems less likely
Me too!
What could be the cause of NetworkTransform.Teleport() still causing the player to interpolate, I can see on my clients that the player lerps towards the target position instead of appearing immediately (teleporter feature)? Netcode 2.3.2, Distributed Authority. The teleported object has no Rigidbody component or similar.
I used to check everyday and it was 98% on last day of month
🙂
Ehhhh, silly mistake, just as I write this I noticed it ofc 😄
I was updating the player transform pos and re-using it in later steps to teleport the network transform. Essentially order of operations was messed up.
That billing is for April 1st to April 26th
Sorry I meant the last day of april
I cancelled it on May 1st
The billing shows 119 GiB used which is either 119 over the free tier or 119 total - either way that’s 80% or 180% usage so I’m not sure how your dashboard usage was showing 98%
@old umbra same question here though
do you recommend any specific option for networking for my use case?
is there a particular recommendation for how to implement multiplayer? (as for the context of my use case: it's a turn-based board game)
it seems like there are several options, so I'm not sure which one would be the best for me
Really depends on the game. But the Unity 6 Multiplayer Center would recommend using Cloud Code for a turn based board game
https://github.com/Unity-Technologies/com.unity.services.samples.multiplayer-chess-cloud-code
To confirm, [ghostfield] component variable on a ghost may only be changed by the ghost owner is that correct?
Pretty sure the server always has write access and for Owner Predicted Ghosts, the owner does as well
can someone help me understand what is causing this error? (is it repeatedly printed to debug log every 1s)
I don't know if this is enough context to figure it out so please tell me if you need more code/screenshots
the line that is causing the error is driver.ScheduleUpdate().Complete();, where driver is a NetworkDriver
Looks like data is still trying to send even after the network has shutdown
hmm, ok.. I think something is wrong with my client-side code but I'm too new to networking to be able to figure it out right away
when a server is running the client does not connect successfully, and when the server is not running the client starts logging these errors on trying to connect
Are you using NGO?
what is NGO?
Netcode for Gameobjects
no, I'm just using transport since that is what's used in the tutorial I'm using as a jumping off point
also I don't need to send gameobject transforms over the network, only messages triggering certain events
maybe this is also possible with NGO but I don't know how to do it :P
I would say using UTP directly is only for advanced use cases. Its all much easier using NGO and the Sessions API
got it, thanks for the help
I missed this documentation earlier so thanks for linking it
NGO also has Custom Messaging which is probably what you're looking for https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages/
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
Can't be possible to use 119 gib in just last 2 days.
I even used filter for last 30 days usage it's under 150gib
Yeah based on the billing you showed it looks like they just forgot about the free tier for bandwidth. Probably some error in resetting it from month to month. Either that or I'm not understanding their pricing explanation.
Would be curious for an explanation if you end up reaching out to support.
Yeah, I am thinking to do it. I'll let you know
I think you got it wrong. I have once 60+ players playing at same time. It still registered as 30-40 CCU that month. I never passed over 18 after. And bandwidth is getting consumed so it will always increase while CCU can be stuck at 11.
In first 10 days of May I had Bandwidth lower than CCU
Since it will consumed. Bandwidth surpassed the CCU. It's not that I am consuming a lot of bandwidth for low CCU
I've got a funky issue with Netcode, Distributed Authority. If a player is joining a session and the host of the session leaves, the Sessions API tells me that the player joined successfully (I'm querying available sessions 1st and then join one via JoinSessionByIdAsync). Though after about 20s they get disconnected automatically as actually the connection was never established (the NetworkManager callbacks do not report a client connect).
I'm suspecting the once the host leaves, the network session gets yeeted and the joining player ends up in an invalid session. I've configured keep alive time for lobbies in Unity Dashboard to 2m, tho that doesn't seem to affect anything. Forums aren't that helpful also... Anyone have some tips?
P.S. I've also tried replacing JoinSessionByIdAsync with CreateOrJoinSessionAsync, though I get same results. I suppose the Sessions API thinks the network session is still valid and doesn't try to re-create it, while relay is actually another state 🤔
The session id should not be changing when the session owner leaves. Does this only happen when the player joins at the same time that the owner leaves?
This happens almost at the same time when the owner leaves. The session id is not changing as I'm looking at the logs - it's the same for the owner and the client that's connecting.
To clarify, while a new player is joining the session which only has the host in it (Sessions API is doing their thing), then the owner leaves. The player that's joining then fails connection (after connect_retries x connect_timeout), but the Sessions API gladly returns a valid ISession object before that happens and NetworkManager kicks in (Sessions API calls lobbies and other APIs before talking to NetworkManager).
TL;DR
Player AstartsSession Aand joins fullyPlayer Bstarts connecting toSession APlayer AleavesSession APlayer Bretrieves a validISessionobject forSession APlayer Bwaits 10s andNetworkManagertimes out
...right now my workaround for this issue is to check NetworkManager.IsClientStarted after retrieving an ISession object with a timeout of 5s. If this fails, I leave the session (LeaveAsync()) and retry connecting to the session, but this adds a lot of extra time to the connection flow...
Oh, yea. if the last client leaves a session then that will end the session.
I was assuming that Active Lifespan would alleviate this in DA 🤔
The game I'm designing works similarly to Gorilla Tag, where once you enter a specific area, you join a network session. Since the players will be running around all over the place, sessions will be destroyed and created, which means such race conditions will occur. Isn't there a way to keep the session active somehow?
Not with no clients connected to it
Perhaps this is documented somewhere? I could not find any info on this, the entries in lobby config are also not very helpful and misled me in such case
Regardless, why am I allowed to join a session from which the host has disconnected?
Sessions uses Lobbies but they are not the same thing. There would need to be some kind of keep alive state on the DA service itself. It might be worth opening a Github issue on it
Mhm, probably will do, thanks anyway
Hi all! Hopefully I'm on the right channel.
I am making a 2D card game (free-time project). The game features different cards, character and item artworks. You can interact with the character and items sprites, the cards are forming a properly working deck (you can draw, shuffle, place back cards etc.).
I want to make the multiplayer part of the game. I want the players to be able to self-host the game/session so the other player(s) can join them. Each card drawn from a deck should go the specific player (so for example after drawing a card that player can see what is the card, but the others should see the back sprite etc).
For authentication I want to use Discord, but I have no idea if it's a viable idea.
Regarding these ideas, what technology/package etc could you guys recommend me? This is a project made in my free time so far (just for fun) and because of that I want to use free solution (I'm willing to and see as an interesing challange to implement many things/logics if needed). Thank you advance!
If its purely a card game like Hearthstone then you can look into using Cloud Code. Netcode for Gameobjects or any of the other network libraries can work just as well
So it's more about how I implement the things and anything (I mean any framework) could work instead of the framework itself restricting me?
They are all generic enough to work for most game types. (except MMOs)
That's really good to hear
And am I able to use a "third party" software as an authenticator/account manager such as Discord with these?
Discord has a new SDK you can use for Authentication. But I use Unity Authentication with it
And Unity authentication is totally different/standalone from Netcode for Gameobjects for example, so I can combine both, right?
Yes. Separate packages/services.
Great, thank y'all!
Hi all, how do I make a player lobby via Steam + netcode?
I am using netcode for entities, here is my bootstrapper:
using Unity.NetCode;
using UnityEngine;
[UnityEngine.Scripting.Preserve]
public class GameBootstrap : ClientServerBootstrap {
public override bool Initialize(string defaultWorldName) {
AutoConnectPort = 7979;
return base.Initialize(defaultWorldName);
}
}
here is my error (attached as file but basically socket creation failed)
it doesn't always happen, does that mean its an editor bug
You would use Lobbies Or Sessions with a custom Steam Network Handler
Looks like its trying to connect twice to the same socket for some reason
Anything I can do about it?
You probably have another ClientServerBootstrap in your project that is also trying to connect
I don’t really know those stuff very well how would I implement it
Btw ty for your help
Any script that inherits ClientServerBootstrap will run automatically to create a client and server world and connect them. Unless the AutoConnectPort is set to 0 which then means you need to connect manually
Ohhhh I get it
I don’t think I do because I took codemonkey’s early project and now I’m editing it I didn’t do anything with the bootstrapper
You can check to see if you have multiple server worlds created when you hit play. Any samples you import might have a bootstraper included as well
How to check for multiple server worlds
Any idea why I'm getting this? NullReferenceException: Object reference not set to an instance of an object DevelopersHub.RealtimeNetworking.Client.Sender.SendTCPData (DevelopersHub.RealtimeNetworking.Client.Packet _packet) (at Assets/DevelopersHub/RealtimeNetworking/Scripts/Sender.cs:14) DevelopersHub.RealtimeNetworking.Client.Sender.TCP_Send (DevelopersHub.RealtimeNetworking.Client.Packet packet) (at Assets/DevelopersHub/RealtimeNetworking/Scripts/Sender.cs:39) DevelopersHub.ClashOfWhatecer.Player.Start () (at Assets/Scripts/Player.cs:81) I'm not getting any errors in VS, just Unity
I've tried asking AI for some help but Ai is of no help in this situation. I can't really test my game until this is fixed sadly
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
There is a drop-down in the Entities Hierarchy Window
You'll probably need to ask whoever made that networking library. I've never heard of that one before
Thank you, I'll try and get in contact with him again
ohhhh ok ty
so when using relay for multiplayer, im having an issue where my a script running on my client is saying that IsOwner = false, and i was under the impression that if it was a script attached to their character, they were always owner.
That depends on when you checking IsOwner. It seems to take a frame after spawning to set ownership of an object. If this is a player object then IsLocalPlayer should work better if your checking in OnNetworkSpawn
Hey, I could use some help with spawning a game object through a ui button over a network where the button is only instantiated on client side and is a part of a prefab itself. Pressing the button should send an Rpc to the server to spawn the object but its not registering any clicks, but the button is being linked to the variable so its not null. Anyone have any ideas
i just switched on start to on network spawn, but the thing is somehow the client isnt being considered is local player or is owner, this is in a constant loop so if it took a couple seconds it should still start printing true
Anyone know how long does it take for the ngo devs to respond to a github ticket?
After reading through the docs and the anticipation github sample, the sample is basically showing an example of a client authority anticipation where clients have fulll control of the anticipated value. It does not show examples of a server authoritative setup. Additionally there's a potential bug in the .Smooth() function which I've submitted a bug ticket yesterday.
It is not client authority. The server sets the value.
Hey, I could use some help with spawning
Are you saying the player object is never returning true for isOwner or IsLocalPlayer on its own client?
from what im seeing in my print statements, yes, the host is considered owner and local player, while the client isnt consiered to be either. the thing i dont get is that my movement code runs a script attached to the same object, and somehow that works perfectly fine
tried adding that same print to my character movement and it appears that my host is handling the movement for both characters so no clue how thats even working lol, but yeah seems like the client isnt the owner or local player in that script either
How are you spawning the player object?
im using the unity network manager component, one thing i just realized both the host and client have the same global object id hash... ide assume thats part of my issue?
owned client ids are 0 and 1 tho, so those are different
This is what you should be seeing on the host. The client would these reversed
That is really odd if the owner IDs are correct but the bools are not
okay so you're saying that using the network manager, by default the client should be owner of its network object?
Yes. You can also use networkObject.SpawnAsPlayerObject() if you want to spawn it manually
hmm interesting, ill look into that bc my current setup just isnt working how i want it to, your advice is much appreciated
Hey guys, I'm trying to do something simple in netcode. I'm using the 2d space shooter example's object pool(slightly modified) and all I want to do, is deactivate all of the objects that are in the dictionary of queues
Sounds like you deleted a ghost on the client and not the server
converting a single player project into multiplayer is going to be a bad time. Even if its just a sample.
Network Objects need to be despawned on the server and not just deactivated.
I get that. I used networkObject.despawn but the problem is that the NetworkObjectPool is a monobehaviour and calling networkObject.despawn does nothing....
This is the method im working with. For some reason when i build the list "items" and dequeue the network objects from the dictionary, only the inactive network objects are added to the queue
That should work as long as INetworkPrefabInstanceHandler was setup correctly
The object pool code works flawlessly, but I can't seem to devise a functional way of deactivating my object pool whenever I change scenes.
Huh, it should do that automatically
I may have an older version that doesn't
My object pool is in a persistent scene and thats where all the objects stay. that way i never have to recreate the object pool. Simply destroying them with the active scene was generating tons of errors
dunno about that. spawned network objects have always been destroyed on scene change. Unless you specifically set it to do not destroy on load
I will try it your way real quick and see what happens
Thank you for helping me, I am surprised anyone is up this late
lol, its only 9pm where i am
10pm here, not too far from ya. That did the trick. No errors. I had some other issues with my project but got them all resolved this week.
Yeah that’s why I’m confused because I’m not
If you go to the forwarded message I put the logger there
It says the entity was deleted by blank system
I see. I've never seen that happen before. Do you know what those entities are? What other systems are querying them?
In those functions, the client is sending a ServerRPC with the actual value (not inputs) to be set on the server's authoritativeValue. So the client is dictating the value to be set, hence it is client authoritative isn't it?
Most of the Rpcs are either SendToEveryone OR SendToServer and the value they are sending to the server, is used directly to set the authoritativeValue. That's what I mean by the samples being Client* Authoritative. A server authoritative approach would necessitate additional conditions in that ServerRPC or even (in my case) be required to be called elsewhere due to the setup. So in this regard, the samples either didn't showcase a more advanced approach OR it's limited to whatever they have included in it (where the Anticipate() must be called directly in the initial ServerRPC from the client, and cannot be called elsewhere). For this I believe no one here has the accurate answer at this point and we'll have to wait for the NGO team to get back.. Hence my initial question is how long would they take to respond to a git bug ticket (if anyone knows).
@paper summit you good with unity relay?
If this is because it's a sample that they are directly modifying the value in the ServerRPC and sending the actual Value from the Client (not input value), and that for the actual approach I should be directly anticipating in that initial ServerRPC, then I need to confirm if this is the only way to get it to work? Because this means that I can only Anticipate() whenever I send Player's Input data from the client but I can't guarantee that my AddForce will be executed before Anticipate() is called if i roll with what the Samples are doing. If so then it will mean that I have refactor my code just for Anticipation to work.. I hope this is not the case and there's more flexibility to this system.
My ServerRPCs are currently only used to send Inputs, not sending the position of the Client nor AddingForce and Anticipating() in it.
I'm using a third party relay with NGO
does that still use the network manager component? im using that to spawn my host and clients, but my clients dont have ownership of themselves
Yes i'm still using the network manager
do you know what could be causing that?
What error are you getting?
You're trying to move the client on the client side?
well im doing hotbar stuff but my issue is that when i call isowner on client its always false
i thought theyre supposed to spawn in with isowner and is local player
Where are you calling isowner and islocalplayer?
E.g in Awake(), Start(), OnEnable(), OnNetworkSpawn()
on a script that is attached to the player i spawn with the network manager, and i am checking in update
I'm manually spawning the playerobjects:
if (!networkObject.IsSpawned)
{
networkObject.SpawnAsPlayerObject(clientId);
}
else
{
networkObject.ChangeOwnership(clientId);
}
You could try ChangeOwnership to see if it works for you
yk i tried that before but had another bug i needed to fix first lemme give that another try
I see, for the default/letting NetworkManager spawn for you, try checking the clientId, see if it matches your client
now when i spawn my client in the hosts camera snaps to the clients body XD, well atleast im past the ownership issue
Nice, it seems like you will have to use ClientRPC from the server to get the Cameras on each clients to snap to their respective local player (though this is one way of doing it depending on your setup).
exactly what i was thinking. i appreciate the help
It’s a generic sample showcasing anticipation. It’s not going to show advanced approaches.
This is like saying sending inputs makes things client authoritative just because the client has full control over the value being sent which dictates what movement values are being set.
It is up to the server to validate whatever the client is requesting the authoritative value to be set to and that’s almost always game specific and would not be covered in a sample.
at the end of the day the server is the only one that can directly set the value and sync that change to all connected clients. That’s what makes it server authoritative. Validation is another topic entirely.
So it confirms what I said previously that the samples are simply covering the basics, for the issue that I'm facing I'll still have to wait for the NGO devs to respond.. It's either a bug with the handling of the Smooth() function or I need to call some other function e.g the Update() function somewhere which the samples do not cover.
Is there any free networking library for ECS? For GameObjects you have things like Mirror, but I can't find for ECS.
aside from the unity one you mean?
Yeah, that one is only "free" up to a certain point
you mean for bandwidth and CCUs? you're normally going to have to pay for that at some level regardless of what service you use, electricity costs money 😄
The free Relay services I know of are Steam P2P and Epic Online Services.
well, free as in you have to sell your game on their storefront and give them the cut 😛
That is only if you need a server. For example, a game like Minecraft only has client-host (either LAN or direct connect to a IP Address of another player). There is no lobby or central server which matches players
relay services aren't about dedicated servers, connecting two players directly to each other is harder than it sounds
Hence asking if there are libraries that does that for me
well you said you don't want the things that those libraries do, but the things they do cost money to do
That is what relay services are for. There are also Lobby services if you want
Most services will have a free tier that a first time indie dev is very unlikely to surpass
I'm not understanding. Why would LAN usage require to connect to a server? Why can't players simply connect each other?
AFAIK (haven't research much because it doesn't support ECS), Mirror is a networking library which is open source and free for example. They don't have server for lobby and stuff.
if you're only doing LAN connections i don't think you'd be using the relay anyway, which is what they charge you for (AFAIK, i'm a photon user and haven't touched unity's one in awhile)
If you are only on LAN then you would need to use Network Discovery
i guess it's worth mentioning that in unity's parlance there's a difference between the network library and the network transport, so you can use different transports (network backend) with the same library (multiplayer game code) , like you can run Photon or other third party libraries through NGO if you want to
i haven't tried it myself but i assume you can swap out the transport with Netcode for Entities like you can with NGO 🤔
Interesting
Is having one entity with ghost component for each item in a players inventory too expensive for performance? (in ECS, netcode for entities)
Only the profiler can tell you that. But I would use a Dynamic Buffer for inventory
I'm pretty sure any of the Custom Transports will work with N4E
yeah, i tried adding a ghosted dynamic buffer and then adding each inventoryitem component to this buffer but then it would send the entire buffer when just a single component got changed
I though Dynamic Buffers only sent the delta changes but that might be wrong according to this
i think its because i didnt have a fixed size, maybe i will do that
guys i got a random question, if I make a game in unity with c# and then later on I realize i want to make it multiplayer, like networked. Am I essentially gonna have to redo the entire games code?
or only things that will need packets so cant be hacked
adding multiplayer after the fact will be a bad time
it's possible to do (have had to do that before 🥲 ) but it's a big job and depends a lot on the type of gameplay, obviously it's much easier to make things multiplayer-friendly from the start
yikes ok, anyone able to link a little guide to kick start me in that direction? im doing 2d top down to just make a smaller game for practice with networking then to start.
it'd probably be best to look at some of the sample projects for NGO (or your library of choice) first of all, get familiar with the structure required for multiplayer before you start applying it to the existing game
okay and any help i can come here?
@sharp axle is multiplayer for 3d and 2d the same ? or do i need indiviual learning methods
It's basically the same. There maybe some issues if you are trying to spawn things on a UI Canvas though.
Hi I am pretty new to unity but I’m trying to make a four player game. That’s very simple. It’s just a game where you walk around how would I network it?
I am making a dungeon generator in Unity and keep running into the same error over and over when starting a Netcode for GameObjects host. I have treid re-adding the network objects on each of the room prefabs and have also tried restarting Unity, neither of those did anything. No prefabs with network objects are in the scene when starting the host.
Error:
Exception: Room_Corner(Clone) tried to registered with ScenePlacedObjects which already contains the same GlobalObjectIdHash value 272924042 for Room_Corner(Clone)!
when using photonView.IsMine everything just blocks up
i cant move anymore but other scripts work just as fine
Are you generating the dungeon before the host connects? If the rooms themselves are network objects then they have to spawned after connection
Hello ^^
I'm making a 2d game where the camera is static for both players but each player start at a different location in the scene
I'm having a problem Initializing the cameras for each player
I tried to prefab the camera and have a script that is attached to the player have a reference to it
code: https://pastebin.com/tu2Kz300
Looking at the logs the ClientRpc does get called on the host and the client but for some reason it does not init the camera for client 2 at all
appreciate the help 🙏
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.
The rooms are generated when OnNetworkSpawn is called.
Does the room prefab contain any nested network objects?
Your cameras should not be spawned. There should only be one active camera in the scene. I would have the local player object find the main camera in the scene and set its position
tried that
if (IsOwner) {
var pos = (gridIndex == 0) ? Player1CameraPos : Player2CameraPos;
Camera.main.transform.position = pos;
}
both clients get the same view if I do it like that.
for some reason it does not register the new position at all even tho it does get the right one
Unless the gridIndex is the same for both players, that shouldn't be possible if there is only one camera in the scene.
Make sure there isn't a network transform on the camera
No
Are you getting the error on the host as well as the clients? No dynamically spawned objects should be registering as scene objects
Anyone got any idea of what's happening?
I think it's because my code is destroying rooms before it's finished properly spawning on the server.
Hi I am pretty new to unity but I’m trying to make a four player game. That’s very simple. It’s just a game where you walk around how would I network it?
ple
i cant
do one my one
Yep this was the issue
Use Netcode for GameObjects.
hello, im facing an issu with vivox where audio from other players in position channels is relatively low even when close up, how can i increase it? because in the Channel3DProperties class no value can be modified.
You have to set it within the constructor itself.
the IDE can't even find the values
There’s a default constructor and then a constructor with 4 parameters. If you use the latter, none of the parameters seem to be optional so you’d have to pass in all 4. In your above screenshots you’re still technically using the default constructor
sounds pretty confusing 😅 , may i know how it's done to be able to modify the values?
Seems like the third parameter is what you’d want
yes i finally got it, thank you 🙂
Why are player ghost models always so stuttery
Like the transform pos moves smoothly
But the mesh stutters about
I saw some people online with this problem too but no solutions
You are likely fighting with the client prediction. The order of your systems is going to be very important there
Order of which kind of systems
I’m fairly sure I’m changing player velocity only in a single player movement system
What other ones might matter?
if you look at the DOTS character controller sample
You grab your inputs in [UpdateInGroup(typeof(GhostInputSystemGroup))]
Then you apply those inputs in [UpdateInGroup(typeof(PredictedSimulationSystemGroup))] [UpdateAfter(typeof(PredictedFixedStepSimulationSystemGroup))]
anything with physics would be in [UpdateInGroup(typeof(PredictedFixedStepSimulationSystemGroup), OrderFirst = true)]
Yeah I’m doing all of that though
I don't know why the rig in the hands doesn't sync between clients, and like the hand kind of moves but not right.
The prefab has a network transform and animator.
Do you have lag compensation enabled in the Netcode Physics Config?
If you are using IK then the IK target needs to have a network Transform as well
Does Steamworks (with Facepunch transport) have a voice chat solution?
Looks like it
https://partner.steamgames.com/doc/features/voice
Hey guys
no work?
I get an error when installing on version 6.1
Looks like you are using the wrong to install from the package manager
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/Transports#installing-community-transports
last version?
Yeah
I don’t think it’s lag at all
It stutters at regular intervals
Like every 1s or so
And by the same amount every time
You might want to check the profiler to see if it's a performance issue. Every second is a bit too long to be netcode related
Yes but like I’m saying it’s the mesh only
The mesh doesn't have the ghost component?
its one entity
Is it worth considering asset store solutions for networking like Fishnet or should I just put in the work to learn Unity’s Netcode? I’m not looking to do anything more intensive then 4ish players in a coop simulation type game
NGO will be more than sufficient for that. I also believe FishNet is free as its base. Any paid version is for additional features.
Thanks, just trying not to go too crazy with asset store solutions if it’s overkill
Also depends on the assets. There are some really well done assets for Fighting Games or Online TCGs that could save you a ton of time and effort.
Just wanted to follow up. Your advice helped a lot I was able to create an Item Database that successfully stored the information by using unique item IDs. After this I was able to make a full slot based inventory synced for multiplayer you are awesome tysm!
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Hi all,
I am a backend developer and I want to build my own backend that manages game sessions
chat
player profiles
player data
and so on
but the multiplayer itself, I want to use unity's netcode
is this doable or do I have to implement everything through netcode?
Definitely doable. Netcode won't provide any persistent data storage between sessions anyway, so some sort of backend solution is pretty much necessary if you want player profiles/data to be persistent.
Your backend wouldn't use netcode at all. That is usually all database and Rest APIs
how do i stop my players from being able to shoot themselves in the back, if they are moving forward while fireing.
my current logic goes like
- Player shoots and sends server RPC while moving forward
- Server receives request, spawns in the bullet from the guns current barrel transform.
- By the time the server has finished processing the request, the player is already infront of the bullet and dies
I want to help, but I'm really new to multiplayer coding. But here are some thoughts: are you using Raycast for bullets (maybe a good option); could you make it so that the bullet can't damage the object that instanciated it (this doesn't sound bad to me, although I'm quite sure how to do it. If you have a method for summoning bullets, you could and a parameter thats a GameObject where you send the player to the method. If the object hit is the player GameObject, do nothing/ignore the hit); you could maybe offset the bullet to spawn forward.
i am using a hybrid, the location of the bullet is calculated sort of like physics, but it also raycasts one physics iteration forward to tell if its gona hit something
yes
I think I understand
idk how to explain
is the bullet an actual gameobjekt that uses raycasting?
the bullet isnt a gameobject, it is a position and velocity which is stored in a list
and then you Raycast from that position in line with the unit vector from the velocity?
oh wait nvm
i mixed up something this one actually is a gameobject
the bullet is a gameobject?
yeah something like that
and the bullet is a gameobject
alright, is there a method you call to spawn the bullets in?
i use two projectile systems, one for bullets and one for shrap, which is why i mixed it up
yes
void ShootServerRpc
do you call this from the player?
yes, i think i could actually mitigate this by what you said earlier, i could just check if the bullet hit its own owner
yeah, if you make the ShootServerRpc(GameObject owner)
I think, as I said, limited time with multiplayer in unity, but have coded Java before
you mean NetworkObject as param
each bullet is assigned an owner during runtime already, i just need to add a check
alright, nice
otherwise this could be a mechanic
Js dont run too fast 🙏🥀
unintended speedCheck 🥀
that was an easy fix lmao, thanks!
😮 nice!
Check out the docs for this exact scenario
https://docs-multiplayer.unity3d.com/netcode/current/basics/spawning-synchronization/#spawning-synchronization-in-client-server
Ensuring that objects spawn in a synchronized manner across clients can be difficult, although the challenges differ depending on which network topology you're using.
can anyone help me with first-person movement / camera in multiplayer using Fishnet?
My bullet when shot in the client it spawns in a difference place instead in the place intended.
I use a server rpc that receives the transform position and rotation then spawns the bullet in that position. The spawn position has a network transform.
If the spawn position is moving then the same thing as above is what's likely happening
Even when I'm not moving
If the bullets have a network transform then make sure its set to server authority. it seems like its interpolating from 0,0,0 to where its supposed to be
yes, its set to server authority, but why it would spawn in other position, if the position and spawn are done by the server
here's the script,
using System.Collections;
using Unity.Netcode;
using UnityEngine;
public class ShootScript : NetworkBehaviour
{
private CharacterButtonsReference bt;
[SerializeField] private NetworkObject bulletPrefab;
[SerializeField] private Transform fireHole;
[SerializeField] private float cd;
private bool canShoot = true;
private void Start()
{
bt = GetComponent<CharacterButtonsReference>();
StartCoroutine(ShootCooldown());
}
private void Update()
{
if (!IsOwner) return;
if (bt.PlayerButtons.Shoot() && canShoot)
{
canShoot = false;
ShootServerRpc(fireHole.position, fireHole.rotation);
}
}
private IEnumerator ShootCooldown()
{
yield return new WaitForSeconds(cd);
canShoot = true;
}
[ServerRpc]
private void ShootServerRpc(Vector3 position, Quaternion rotation)
{
var bulletInstance = Instantiate(bulletPrefab, position, rotation);
bulletInstance.Spawn();
}
}
If it has a network Rigidbody try turning off interpolation. On clients(since they don't have authority), objects seem to still spawn at origin for a frame before getting updated to its proper position.
Is already set to none
Try removing the network Rigidbody all together
is there any way to output vivox voice chat to an audio source?
or do I need to switch to steam voice chat or similar
Ok thanks
hey y'all, this might be a stupid question but,,,
how do you do networking. period. i've tried on like 5 different projects and have failed every time, my literal only goal is to get one computer to connect to a nother, just have two players running around on a screen together from two different computers, but I don't know how to do that.
could someone help me get started, if they have some free time?
i've been using this tutorial to get started:
https://www.youtube.com/watch?v=msPNJ2cxWfw
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
✅ Learn more about Relay and UGS https://on.unity.com/3tQZLLW
📝 Relay Docs https://on.unity.com/3OjXL8z
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click...
Although I have an issue, if anyone has an idea. Using that ^ (Netcode & Unity Relay), I've been able to set up networking. I have an issue though. The client's player prefab isn't being created. I've confirmed that
1- Host's prefab is created
2- Client successfully connects to the relay (according to debug logs on client's side)
I'm not sure what would be stopping client's player prefab from spawning, if anyone has an idea
ty i'll l ook at it in a lil :)
what i was looking for was-
possibly some 1 on 1 help with setting this up so i actually learn instead of just copying what someone else does, i want to know the workings behind it and why everything does what it does
Code Monkey's complete 6 hour course is probably going to be better than any 1 on 1 help. Unless you're hiring a private tutor
6 hour course?
💬 Here is the Multiplayer Course! I really hope both of these FREE courses help you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Project Files, FAQ https://cmonkey.co/freemultiplayercourse
🎮 Play the game on Steam! https://cmonkey.co/kitchenchaosmultiplayer
❤ IF you can afford it you can get the pa...
Which Networking solution would you guys recommend? I've been trying to learn some Fish-Net, but I find it quite difficult (if anyone is knowledgeable: I'd love to pick your brain). What solutions are you guys using/would reommend?
I like Netcode for Gameobjects. But all the modern library are very similar
I mean, if I understand it right, it's all based on the same stuff, just implementing different stuff. right?
They all use some form of network variables and RPCs for the most part
Some have client prediction built in. Some have distributed/shared authority models
If I want to make a multiplayer fightning game for me and some friends, what attributes would I be looking for? Not a FPS, but swordfighting.
I'm pretty new to all of this, and the choices I can make are honestly overwhelming, never knowing whats right or whats wrong + everything feeling like it always goes wrong
Fighting game are some of the hardest things you can do. But if you are serious about it then look up Universal Fighting Engine 2 on the asset store. It's fully featured and has Rollback Netcode in the Pro version
I'm making random generating platformer sandbox which allows for multiplayer and loads parts of the maps in sections/chunks.
All players should have the same map appear to them - I do this by having a list that should stay the same through all clients and the server at all times. Currently I'm using mirror with a synclist to try to accomplish this - but this only works if the host player (there is no single dedicated server) loads the section first.
If a random player is able to get further than the host and loads a new section on its end - it won't be added to the synclist and that area can appear different for the host and other clients. I'm using [Command] functions and everything.
basically how do i add an element to the synclist on a client and have it sync to the other clients and host
You would use an RPC to the host
a targetrpc right? I will try this, thanks!
[Command] is an RPC to the host in Mirror - [TargetRpc] is an RPC from the server to a specific client
Clients should be able to send the value they want added to the SyncList through a [Command]
The problem you'll run into is when 2 clients try to generate the same chunk at the same time. Unless it's deterministic through a shared seed value, it gonna cause issues
new chunks are only generated when one client goes to the end of the world where nothing has been generated beyond it - otherwise the synclist of every previously loaded chunk tells them what they should generate beforehand
of course at that point the client who generated the new chunk adds it to the synclist
(sorry for the ping)
What if 2 clients are side by side going to the same part of the world?
Hey guys, what are the steps you usually follow for leaving a server or/and shutting it down ? Answers on the internet are bit all over the place.
Hello everyone, a game that I'm developing currently requires timers that are synced between all clients. I've currently only tried NetworkTransform and NetworkObject; as in literally just adding the component without any changes, since it seems to work with the draggable player object that I added, but none of them have managed to sync up the timers between clients. How can I accomplish this?
You would need to use an RPC to start the timers at the same time. It could also be done with a network variable
LocalTime and ServerTime
i dont understand why im getting a memory leak immediately after running my game, before i spawn in any players or anything.
Unity version 2022.3.18f1
Netcode version 1.7.1
Okay, I'm currently using NetworkVariable now, but I keep getting CS0019 no matter what operand I use in order to subtract time based on delta time, how do I make it count down now? Sorry if this is getting off topic
even when the leak detection level is set to enabled with stack trace it only showed more info once when it stopped showing it when i reload domain
disabling/removing UI elements from the scene or any netwrok objects doesnt do anything either
You only use the Network Variable to start the timer. The timer itself would be run locally
I would try updating NGO. 1.7 is very old
it doesnt show versions under version history, how do i update it then?
You can specify the version in the package managerby name and it will install if the Unity version is supported.
You can go up to 1.13. NGO 2.0 requires unity 6
1.13 is newer than 1.7?
wait yup
i see that now
well i tried both, and they both hadnt worked
this is so weird, i closed and reopened unity, run it, down to one error, went to enable stakc trace, run it, no errors
i do not understand at all whats going on
Thank you for this, it's at least gotten me progress, although more problems came up, I can at least see that a value is getting synced between clients
Normally I just use "ToString()" in order to convert a float into a string value so that I could put it on text, but for some reason the network variable just turns itself into "Unity.Netcode.NetworkVariable`1[System.Single]"
You shouldn't use a network variable for the time itself. But you should be able to NetworkVariable.Value.ToString()
Hey, can y'all help me as I'm trying to use netcode for game objects but I can never seen to execute it well and I can't find a tutorial good enough
It's for a 3d first person multiplayer stratigy game
Oh my god I can't believe that's all I needed to do, thank you so much!!
In short, can someone explain for my dumb brain how to use net code for game objects with a first person game?
Also can someone explain why prefabs don't like NetworkBehaviour scripts
Check out Code Monkey's course I linked [here](#archived-networking message)
Will do
Hi =)
I'm very new to netcode and might have bitten off more than I can chew at this point.
I worked through code monkeys course on it and my players are synced, which is great. I can't, however, get moving platforms to work.
After a couple days of experimenting, it seems like those are a lot harder in multiplayer compared single player... I gave the Kinematic Character Controller from the asset Store a try and whole that one feels great and handles moving platforms incredibly well, I just can't get it to work in a multiplayer scenario. (in short: I struggle with assigning players characters to owners in particular)
I gave top down engine a look as well, but it seems like that one is limited to local coop.
Can somebody point me in the direction of people who managed to solve this moving platform kind of issue? I think I'm running out of things to keyword search for at this point.
Syncing physics is a very hard problem. With moving platforms, reparenting the player to the platform is the usual strategy. If you aren't using Rigidbodies, then check out this example
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/tree/develop-2.0.0/Examples/CharacterControllerMovingBodies
If you really need to use physics, then you might be able to NetworkRigidbody.FixedJoint
Thank you! Already gave that a try and struggled, but there's a high chance I just made a ton of mistakes going from rotation to movement. I'll give it another try =)!
And glad to hear it's a hard problem
I have done this in 2D and 3D without issues before, but now that it is Netcode, I feel like I'm running face-first into walls where I don't expect them.
.. I only just now see the elevator body in the example...
I somehow locked in on the Rotation one...
Okay, I have a strange issue now. I'm building the game to simulate multiplayer with it + unity editor. However, the instance that doesn't open the server and only connects via client has altered rotational movement. Is this a common issue? What could cause it?
It has lowered Yaw, but increased Pitch. Super strange
post your movement code and we can see whats happening there
private void Update()
{
if (!IsOwner) { return; }
Vector2 moveActionValue = _moveAction.ReadValue<Vector2>();
Vector2 lookActionValue = _lookAction.ReadValue<Vector2>();
_horizontalInput = moveActionValue.x;
_verticalInput = moveActionValue.y;
_jump = _jumpAction.IsPressed();
_isGrounded = _characterController.isGrounded;
//Debug.Log(lookActionValue);
if (_hasMoved)
{
_yawInput = lookActionValue.x;
_pitchInput = lookActionValue.y;
_horizontalInput = moveActionValue.x;
_verticalInput = moveActionValue.y;
_hasMoved = false;
}
else
{
_yawInput += lookActionValue.x;
_pitchInput += lookActionValue.y;
_horizontalInput += moveActionValue.x;
_verticalInput += moveActionValue.y;
}
if(Time.deltaTime > 0.08)
{
Debug.Log("deltaTime was:" + Time.deltaTime);
}
}
private void TimeManagerTickEventHandler()
{
if (IsClientInitialized)
{
ReplicationData data = new ReplicationData(_horizontalInput, _verticalInput, _isGrounded, _jump, _yawInput, _pitchInput);
Replicate(data);
//Debug.Log("Is ovner" + NetworkObject.ObjectId);
}
else
{
//Debug.Log("Isn't owner" + NetworkObject.ObjectId);
Replicate(default(ReplicationData));
}
}
private void TimeManagerPostTickEventHandler()
{
CreateReconcile();
}
[Replicate]
private void Replicate(ReplicationData data, ReplicateState state = ReplicateState.Invalid, Channel channel = Channel.Unreliable)
{
float tickDelta = (float)TimeManager.TickDelta;
Vector3 move = new Vector3(data.HorizontalInput, 0, data.VerticalInput);
move = Vector3.ClampMagnitude(move, 1);
Vector3 worldspaceMoveInput = transform.TransformVector(move);
Vector3 desiredVelocity = (worldspaceMoveInput) * movementSpeed;
_velocity.x = desiredVelocity.x;
_velocity.z = desiredVelocity.z;
if (data.IsGrounded)
{
_velocity.y = 0.0f;
if (data.Jump)
{
_velocity.y = jumpSpeed;
}
}
else
{
_velocity.y += Physics.gravity.y * gravityScale * tickDelta;
}
_characterController.Move(_velocity * tickDelta);
Debug.Log("data.PitchInput:" + "" + data.YawInput + "" + "lookSpeed" + "" + lookSpeed + " for object " + "" + NetworkObject.ObjectId);
_transform.Rotate(Vector3.up * (data.YawInput * lookSpeed));
Debug.Log(Vector3.up * (data.YawInput * lookSpeed));
_pitch -= data.PitchInput * lookSpeed;
_pitch = Mathf.Clamp(_pitch, -80f, 80f);
_head.transform.localRotation = Quaternion.Euler(_pitch, 0f, 0f);
_hasMoved = true;
}
}
The problem changes if I modify the TimeManagerTickEventHandler()
- i set the if (IsClientInitialized) to if(true) then the movement bug appears. I can demonstrate it if you'd like, but its just that the controlls are not the same for client and host.
- if i have an "if else" instead of "else" that doesnt let the client into the else statemnt, movement is fine, but position and movement is not updated on the hosts side
- as it is right now with the else it is the same as in 1)
What networking are you using? When is TimeManagerTickEventHandler() called and where is lookspeed coming from?
lookspeed is a constant, 0.1f. TimeManagerTickEventHandler() gets called once per tick
its FishNet
I'm not familiar with Fishnet, but are you sending raw mouse position for the pitch and yaw input? Isn't that effected by screen resolution?
its mouse delta
the problem is most likely with the Reconciliate or/and Replicate functions
We have tested with more than 2 players now
its all clients, because the "host" probably has a "isServer" tag, which grants it some sort of exception
so all clients have wonky movements, this is probably a fundamental error
Is it expected behaviour that adding a [GhostComponent] to a ghost entity in the Server Simulation World at Runtime in an ISystem will not replicate that component to connected clients in the client simulation world?
This is unlike any [GhostComponent] that exists at creation time during the authoring/baking process, which are correctly added and sync to the client.
Is there something behind the scenes I need to do?
Here is a short video showing the issue: https://www.youtube.com/watch?v=mdp6-avfK1g
Bearing in mind I've been working in Unity 6 w/ entities on this side project for just a couple of weeks. But curious about this behaviour!
I don't believe you can add GhostComponents at runtime. They have to be prefabs that are on the clients and the server in order to spawn and replicate. As far as I know they can only be created at Edit time
Most unfortunate... In the event I wanted to influence an entity from the server side that the client needed to represent in some way.. what would be the approach if runtime components can't be synchronized?
Manually writing RPC calls to keep something 'up to date'?
Trying to design things such that the above scenario is never required? (this seems.. difficult)
I guess I would need to have everything added to the prefab and use server side tag components as indicators for server side systems to "act on" and remove those tag components when a given update has been performed maybe?
RPCs are really your only option
But Enablable Ghost Components are a thing as well
yeah.. just "thinking ahead" I can see use cases for both approaches.. maybe this will suffice. thanks for the input
hey there
do you guys know if one needs to pay fusion photon for using they networking package for production even if one hosts the server build themselves?
Yes.
do you have any info on their pricing?
i couldnt find anything online
oh no no
the pricing for their self hosted builds
That is the pricing for self hosted builds
nah its jsut the PUBLIC CLOUD and PREMIUM CLOUD pricing
Every user connects to the cloud even if they end up directly connecting to your server.
not necessarily tho?
cant we handle other online related stuff ourselves?
why would we connect to their cloud if we dont need them
Likely to enforce the CCU licensing fee
It can also act as a relay
You can roll your own stuff, but Photon Cloud is still in the picture.
oh so its enforced?
Afaik, yes.
but still theres got to be a difference on pricing
whether we use their servers or deploy them on our own
Afaik they don't provide gameplay servers
You can attach plugins to their relays for custom logic, but I don't believe they host Unity server builds.
ill do some digging and let you know
Hey, is it known how many CCU (in combination with entity culling) the Unity Dedicated Server can currently handle? I was told it only works for 300–500, but I need significantly more—at least 1,000 CCU.
That is almost entirely based on server specs and network bandwidth. Also depends on you game type. A card game server could handle more users than an MMO
Okay, let’s assume the server has the following hardware:
CPU: AMD Ryzen™ 9 7950X3D
RAM: 16–32GB DDR5 at 5600 MHz
Storage: NVMe RAID 10
Network: 10Gbit fiber
It’s an RP-based game, so there will be a lot of moving entities—let’s say between 2,500 and 7,000 entities, including the players.
Would it be possible to handle more than 1,000 CCU with this setup?
Anything is possible. That is well into MMO territory. Question is do you have the money to throw at a server development team to make that happen.
okay, ty. I’m doing all of this on my own as much as possible. For me, it’s not a priority to finish quickly or anything like that. I’m just doing it because I enjoy it and want to learn new things.
Unless you are already an awesome server programmer, you are likely not going to get more than a few hundred CCU per server
when i attempt to get the game object of a network object that i gained using tryGet on a network object reference, the game object returns back as null
and i have no clue why
[ServerRpc(RequireOwnership = false)]
void NewGrabbableObjectOrderServerRpc(NetworkObjectReference grabbableObjectReference, bool isAddingToOrders)
{
if (grabbableObjectReference.TryGet(out NetworkObject grabbableObjectNetworkObject))
{
GameObject grabbableObject = grabbableObjectNetworkObject.gameObject;
if (!isAddingToOrders)
{
grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>();
}
grabbableObject.GetComponent<GrabbableObjectScript>().allOrders.Add(orderMarker.transform.position + new Vector3(0, grabbableObject.GetComponent<Renderer>().bounds.center.y, 0));
grabbableObject.GetComponent<GrabbableObjectScript>().sentToLocation.Value = true;
}
}
either the network object has been destroyed or the object was not spawned
So, i have canclled my UGS subscription due to high cost. The free tier is'nt really free. Unity didnt auto stopped relay servers when it reached free tier. Instead i got this warning saying i have to forcefully move to pay plan otherwise services will stop on 26 June. So i technically still got billed.
And since unity does not immediately update usage in realtime so we never know if we reached 99% truly so we can stop players from creating allocationms
it still exceeding
There should be option to either let servers stop until it resets next month or this
I think I understand the reason why they do it that way, but I agree it is not very user friendly and it's not well communicated
so i'm making a function here for the host to load in a gameobject for all players to see - but when i call networkserver.spawn on the object i get an error on the other clients telling me that the object with netid x has no valid assetid or sceneid - basically telling me that it does not exist.
what i don't understand is why it's doing this when creating the object on these clients is the entire point of networkserver.spawn
here is my code https://pastebin.com/3Dq4KR1c
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.
You're not going to be able to spawn objects like that. GameObjects are not something that can be serialized so the way networking libraries get around that is by having you register spawnable prefabs beforehand, so that the network can just send an ID to the clients for them to look up the spawnable prefab and instantiate it locally.
You could also just use a [ClientRpc] to make all clients run that same code.
alright. i tried using clientrpcs before but of course it only worked for players already in the server
i would keep that same command function though right? and call the clientrpc function inside it
Yeah, that would be the downside. You'd have to keep track of objects you spawn that way and manually create them for late joining clients. As well as updating any data that might have changed after they were originally spawned.
i tried to do that with a synclist, but accessing the object in there from another client would result in a null value
You'd be better off going the prefab route I'd say. Making some generic prefab with a RawImage and then using SyncVars for tag, width, height, etc.
alright, thanks
(just to clarify i added the elements in a command function which i called from clientrpc)
I did this but still networkserver.spawn only spawns it on the host - no errors this time though.
i still can't figure out what it's only spawning my object on the host even when another client is connected
this is my current code that does this https://pastebin.com/Cwbp9NUH
unless i'm misunderstanding what the function does - but it seems pretty clear and says that it will spawn the object on all ready clients.
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.
It should spawn the prefab as long as the prefab has been registered, but you will still need to send the image byte array to all the clients in an RPC. Honestly, I wouldn't be sending image files in an rpc in any case
i registered it in the "spawnable prefabs list" on the network manager
Honestly, I wouldn't be sending image files in an rpc in any case
this is functionality for user mods
i checked in the editor and the object simply just does not exist where it does on the host
if it means anything - the prefab is a rect transform image under a canvas environment
I'm not sure which networking you are using, but are you sure you are able to spawn a network prefab as a child of another game object?
In Netcode for Gameobjects, this is not allowed
i'm using mirror - i'll try removing the network identity and i'll see what happens
and i'll spawn it in the root
A Network Identity is required to spawn an object at runtime
sorry for late response, have been out all day since. Have now fixed the network object issue however within the same function, it is unable to find the network list allOrders
which is literally defined as a new NetworkList() upon declaration
yeah that was the problem
thank you!
i had to spawn it in the root hierarchy
I would cache your GetComponent calls and make sure that they are not returning null
will try that
is literally finding the list in the line above and then drawing an error when trying to find it
Is new NetworkList<> getting called?
where?
if (!isAddingToOrders)
{
grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>();
}
yup, is being called
if (!isAddingToOrders)
{
grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>();
Debug.Log(grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>());
}
It's probably orderMaker that is null in that case
yes you were right
they only provide some essential services to keep us dependent on them which is also how they keep track of our usage and charge us accordingly
i tried it without and it still gives the same error
How is allOrders declared in the grabbable script?
public NetworkList<Vector3> allOrders = new NetworkList<Vector3>();
Network lists can't be initialized inline like that. You can remove the new there and still be fine since you are initializing it later anyway.
You can also try making it a NetworkVariable<List<Vector3>>
Are you even creating the NetworkList properly?
ah okay, thanks
really weird thing happening to me right now
so if i host a server and another player joins, and i spawn a gameobject while that player is in the server and apply my image texture to it - it looks and works fine.
however if that player leaves and rejoins - my synclist states that the spawned object count is zero and i lose track of the objects that the host has spawned so i can no longer apply the textures and client-size customizations.
if the user was never in the server before and simply joins after the object has been spawned it also works fine the first time - unless they join again
how to test my own game to display the lobby and enter the lobby on one computer I use FacePunch +netcode 480 appid
suspecting this is a networking issue.
Issue: the object is bouncing infinitely (vibrating).
Physics material bounciness is on 0.5
Code only gives a start speed
has network rb, network transform and network object components
How can a client destroy a game object that was instantiated by the host?
Depends on the library you're using, but generally through an RPC to request the host despawns the object
Could be the collision detection mode on the rigidbody or the position threshold value on the NetworkTransform
been at this for a while and i still can't figure it out
for reference - this is the function i call in "onstartclient" https://pastebin.com/zG9MF4RZ
"objs" is a private readonly SyncList<GameObject> objs = new SyncList<GameObject>();
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.
here
position threshold doesnt seem to solve this, changing col mode only works like 25% of the time, other 75% still vibrate
does it having a circular collider have anything to do with this?
are there any details i can provide to make arriving at a solution easier?
Potentially. You might just be able to set it’s position and zero out it’s velocity when it starts moving slow enough.
Does the same thing happen when you remove the network Rigidbody?
I need a networking programmer to help me out in ym game especially NGE
how to make server picking random maps in mirror
ive tried that but it doesnt budge
yes, just less often that it happens
Hey yall, I've got a weird bug I am dealing with. So... I have a game... the game has vehicles... All of the vehicles move butter smooth on the client... Except when the client boards a vehicle.....Client moving the vehicle is jittery AF.... The NPCs and clients use the exact same code to move the vehicle.... The server moves all vehicles in fixed update....When clients board, they request ownership of the vehicle.... I thought that may be the issue; however, the problem is there with or without the client owning the vehicle... Has anyone encountered this?
At this point i should put a bounty on this 💔
what is a servertick prediction error
Networking doesn't really interact with physics. The same thing should happen without a Network Transform.
pretty much what it says. The client received a server packet that was 18.7 ticks old. dropping that many packets usually results in a timeout
hmm i suppose, i just spawned one, paused, then removed its network rb and network transform, and it still vibrated, so i guess not a networking thing
but if not, then what is the issue? or do i take that to a different channel
might ask over in #⚛️┃physics but you might have to increase its mass or its drag
I am not sure how to describe this as I am pretty new to multiplayer/networking, but I notice a strange thing happening with Netcode for gameobjects and specifically the network transform/rigidbody, when pushing the other player on the host player (LEFT), it seems to apply the correct force (with enough distance), but then moves the player back to a closer spot slowly (which is also the spot on the client, but it is suposed to be further acording to the force), The correct position should be where it initially gets pushed to before moving back. But on the other player (client) it seems to work fine when pushing the host player (except maybe some interpolation needed on the other machine to make it look smooth). Does anyone have any ideas on where to look for what could be causing the host to move the Client to the wrong position? Also if helpfull, this is my current code: ```cs
private void OnCollisionEnter(Collision collision)
{
if (!IsServer) return;
var other = collision.gameObject.GetComponent<PlayerController>();
if (other == null) return;
float myScale = _netScale.Value;
float otherScale = other._netScale.Value;
Vector3 directionToOther = (other.transform.position - transform.position).normalized;
Vector3 directionToMe = -directionToOther;
if (myScale > otherScale * 1.1f)
{
Debug.Log($"I am bigger. Knocking back {other.OwnerClientId}");
Vector3 force = (directionToOther + Vector3.up * 0.5f) * _knockbackStrength * myScale;
// Server applies knockback to authoritative object
other.ApplyKnockback(force);
// Tell client to apply knockback too
other.ApplyKnockbackClientRpc(force);
}
else if (otherScale > myScale * 1.1f)
{
Debug.Log($"They are bigger. Knocking back me.");
Vector3 force = (directionToMe + Vector3.up * 0.5f) * _knockbackStrength * otherScale;
ApplyKnockback(force);
ApplyKnockbackClientRpc(force);
}
}
public void ApplyKnockback(Vector3 force)
{
Debug.Log($"[ApplyKnockback] Player {OwnerClientId} applying force {force}");
Vector3 cleanedForce = new Vector3(force.x, .25f, force.z); // Ensure no downward force
_rb.AddForce(cleanedForce, ForceMode.VelocityChange);
}
[ClientRpc]
public void ApplyKnockbackClientRpc(Vector3 force)
{
// Only apply locally if this is our object
if (IsOwner)
{
Debug.Log($"[ClientRpc] Player {OwnerClientId} applying force {force}");
Vector3 cleanedForce = new Vector3(force.x, .25f, force.z); // Ensure no downward force
_rb.AddForce(cleanedForce, ForceMode.VelocityChange);
}
}
Looks like you’re applying the force twice. If you’re using Network Transforms and/or Network Rigidbody you should only be applying the force on the authority, and letting the Network Transforms sync the resulting position from the force being added.
With Network Rigidbody, OnCollisionEnter() only gets called on the host/server.
Yes you are right thanks, I now changed the logic to make the server tell which client should apply forces, after that it automatically updates the transform with network transform. One small issue still, how would I make it less "instant", currently it sort of looks like the other player gets teleported when hit. Could I make it actually fly away? my current code: ```cs
private void OnCollisionEnter(Collision collision)
{
if (!IsServer) return;
var other = collision.gameObject.GetComponent<PlayerController>();
if (other == null) return;
float myScale = _netScale.Value;
float otherScale = other._netScale.Value;
Vector3 directionToOther = (other.transform.position - transform.position).normalized;
Vector3 directionToMe = -directionToOther;
if (myScale > otherScale * 1.1f)
{
Debug.Log($"I am bigger. Knocking back {other.OwnerClientId}");
Vector3 force = directionToOther * _knockbackStrength * myScale;
// Use RPC to tell the client to apply the force (if client-owned)
other.ApplyKnockbackClientRpc(force);
}
else if (otherScale > myScale * 1.1f)
{
Debug.Log($"They are bigger. Knocking back me.");
Vector3 force = directionToMe * _knockbackStrength * otherScale;
ApplyKnockbackClientRpc(force);
}
}
[ClientRpc]
public void ApplyKnockbackClientRpc(Vector3 force)
{
// Only the owner should modify their rigidbody
if (IsOwner)
{
Debug.Log($"[ClientRpc] Player {OwnerClientId} applying force {force}");
Vector3 cleanedForce = new Vector3(force.x, .5f, force.z);
_rb.AddForce(cleanedForce, ForceMode.Impulse);
}
}
You either have to anticipate/predict the interaction, or slow it down and pair visual elements with it to mask the delay/interpolation
Ok I will give that a try thanks
I am spawning enemies only on server/host
player1 starts the game, clicks start host, set itself in a Manager as a reference being the host player and enemies start spawning, take the reference from the Manager, and start following this reference on update
I let this run for a minute and it's fine
but when player2 joins as a client, for some reason it throws an exception on player2 console that the script EnemyFollowPlayer has a null reference of target player to follow
even though the enemies are set to only set to spawn on the server
any idea what's going on? please note this suddenly starting happening today it was running fine before
You should probably use a network variable for the target player so the client can get updated when it joins.
but the client shouldn't care about this value
he's just a coop player & enemies are spawning on server
Kind of just sounds like clients shouldn't be running that code at all
You would need a IsServer check in that case
they don't
the part where enemies spawn and are told to follow the host player is wrapped in if(IsServer)
but for some reason when the client join, he starts throwing exceptions that the EnemyFollowPlayer script has a null value of hostPlayer
//in SpawnManager.cs
void Update()
{
if (!canStartSpawning || !IsServer) return;
timer += Time.deltaTime;
if (timer >= spawnRate)
{
SpawnInCircle2(GameManager.instance.GetPlayer().transform.position, _radius, 1, objectToSpawn);
timer = 0f;
}
}
public void SpawnInCircle2(Vector2 center, float radius, int count, GameObject prefab)
{
Debug.Log("Spawn neemy called");
float x = Random.Range(center.x - _radius, center.x + _radius);
float y = Random.Range(center.y - _radius, center.y + _radius);
Vector2 randomPosition = new Vector2(x, y);
GameObject _enemy = Instantiate(prefab, randomPosition, Quaternion.identity);
_enemy.GetComponent<NetworkObject>().Spawn();
}
//in PlayerController.cs
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
spawnManager = GameManager.instance.GetSpawnManager();
Debug.Log($"Is server in player controller inside OnNetworkSpawn: {IsServer}");
if (IsServer) GameManager.instance.SetPlayer(this);
if (IsOwner)
{
_camera = Instantiate(CameraPrefab);
_camera.GetComponent<FollowPlayer>().Init(gameObject);
spawnManager.StartSpawning();
}
}
//and finally we call this on trigger of OnClientConnectedCallback from NetworkManager
void HandleClientConnected(ulong clientId)
{
if (!IsServer) return;
// Prevent double spawn
if (NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject != null)
return;
GameObject player = Instantiate(playerPrefab);
player.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
if (hostPlayer != null) hostPlayer = player;
}
//and start spawning is guarded with IsServer
public void StartSpawning()
{
Debug.Log("Start spawning called");
if(IsServer) canStartSpawning = true;
}
If the following of the player is in Update on that script, you should be checking if the NetworkObject is spawned IIRC
Yea. if its a scene object, Update will get called a few times before the network connects
public void LeaveLobby()
{
if (currentLobby.HasValue)
{
var lobby = currentLobby.Value;
lobby.Leave();
currentLobby = null;
}
LobbyManager.Instance?.LeaveLobby();
if (LobbyCreationUI.Instance != null)
{
LobbyCreationUI.Instance.ResetCreationUI();
}
if (NetworkManager.Singleton == null) return;
NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnected;
NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnected;
NetworkManager.Singleton.Shutdown(true);
}```
Player left the lobby, how do you update slots with the host?
What solution could we use if we want 2 people to play together around the world in a coop game. The closest example game to describe it would be portal 2's coop mode.
Any of the popular solutions can achieve this. Just comes down to personal preference. Would just watch some beginner tutorials on a couple solutions and see which one appeals to you the most.
Thanks and where could I see which are these "popular" ones?
(and what do you personally like?)
Netcode for GameObjects, Mirror and Photon are the ones I see most commonly.
Alright thanks. I saw Fishnet too is that worth a try too?
I would probably choose NGO for the game you were described if it was my choice.
Oh yes, forgot about FishNet. Commonly used as well.
Thank you very much i'll check a few examples of these
its a rather laidback game dont need stuff like valorant for anticheat etc..
just need the ease of starting a game with your friend and interactions like seeing eachother, walking around, triggering stuff etc etc
I guess I can do the "join code" thing with NGO as well like I saw it in Photon Quantum.. Just not sure about payment 🤔
You can use the Lobby/Relay service for that. A small indie game doesn't have to worry about passing the free tiers.
Can entities which do NOT have the same archetype have shared component values?
Ok. I'm learning netcode and so far I'm extremely confused. It looks like a single server corresponds to a single game session. Like, I'm running a server, it starts a scene and all my clients are connecting to that scene, and I can't separate them into multiple sessions. Is this the intended way? I have to run multiple servers if I want to run multiple sessions? Then how do I make a lobby, matchmaking, etc?
Server is a pretty broad term. You're kind of overlapping two different things. A single machine could run multiple server builds in order to have multiple sessions run on a single server's hardware.
Lobbies and matchmaking generally happen before and outside of an actual game session.
Ones that happen in game are more complicated as they're going to have to direct you between different servers/game sessions.
Generally, its one Unity Server per session. If you are self hosting then you could run multiple Unity Servers on a machine.
might try asking over in #1064581837055348857
oh Lobbies and Matchmaking use a separate service
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session
Thank you. I'll look into it
Hi, I'm trying to learn to code for multiplayer. I've tried out fishnet for a bit, but honestly. What's the difference between using Fish-Net, Mirror and NGO?
Fish-Net has poor documentation (imo), barely any tutorials online, and no one responds in their dc for days
Isn't every Networking solution build upon the same base? Would you not be able to achieve similar results with all solutions?
Those three are all very similar. They all have some additional/extra features of their own, but at their core they're all just about the same. NGO probably has the best and most active development being done on it.
Basically, yea. most modern libraries all have some flavor of RPCs, Network Variables, and Network Objects
What do you guys prefere using?
All I really want is being able to connect some clients (<10) together and having it be somewhat secure
But without "a lot" of desync, which I'm experiencing now
NGO makes things really easy to start
But you will always have to deal with Latency and Lag at some point
How do multiplayer games deal with that? I know rust, and tarkov, is built with Unity
Yeah. Desync and latency are two different things.
Maybe built in Unity but I'd imagine their networking is custom.
Yeah, of course
But if they're built in unity, don't they have the same resources as I do?
just that they utilize it way better
I think you'll find that most games use a custom network solution specific to the game

There are a lot of ways to reduce the effect of latency on player experience, it's kind of a hard question to answer in a general sense.
Your resources will not be the same if you don't work at that studio
I mean, if you could just name-drop some of them that'd help a ton
I just want to know what I can do, not how to do it
I'm pretty new, so a lot of issues arise because I don't even know how or where to start searching
Tricks and patterns to hide latency, what's acceptable to manage client side with client authority before sending it to the server, prediction, server rewind, action anticipation, etc.
this documentation is more extensive than fishnets thats for sure
Anticipation, Client Side Prediction, Lag Compensation, using a Shared/Distributed Authority network topology, allowing Client Authority, using visual elements and animation - it can become a long list
You'd be best starting off small, and just researching how to tackle the problems you're facing as you go
Will do, but will def save a ss of what you wrote for later
Okay so I'm watching some tutorials and learning about NGO. So I understand that there is Server-auth movement, and also Client-auth movement. I want a "competetive" game. Therefore both choices come with drawbacks, i.e Server-auth gives latency, and Client-auth makes it exploitable. I have an idea, however, that I was wondering about. What if I do both? Say a client presses W. It both moves and sends it to server, which simulates what would happen, if the client's position etc matches with what the inputs say then nothing happens; client movement feels somther. If the inputs don't match what happened, the server intervenes.
That is literally what client prediction is. But its not quite that easy
Congrats! You have reinvented client prediction
Hi. for this. How many users can a single user create? is it one only? or he can create many? and if the player closed the game. will he be signed out?
(the people I've watched haven't mentioned client-prediction, mbmb)
Nah it's a great idea. And even better that it's already been done and there are tutorials on it
there is no limit
Mainly because its pretty hard to get right and its very game specific
Why is it hard to get right?
So it is possible to implement a system where I'm the only one who can create accounts and give them to users?
Sure
Great. for my other questions. will users be signed out when they close the game?
default physics is nondeterministic. this means that its hard to sync across the network.
only if you code it to do so
So the default is they stay signed in?
I don't really understnad what "default physics" is refering to"
Unity's default physics engine is Nvidia PhysX
Your predictions have to be pinpoint accurate. Even the smallest of mispredictions results in large amounts of desync over time.
It also technically requires rollback which means storing a history and being able to rollback to points in that history. Depending on how many things you're predicting, this can get more and more complicated.
There is also a Unity Physics and Havoc for DOTS
yeah I can see why it's difficult, but I'm guessing client-prediction feels a lot better than just running server-auth
in general, yes. but also depends on your game. A card game is not gonna matter as much
yeah, but if you imagine something similar to Mordhau, that's the kind of game I'm trying to build
Pretty much anything with combat is going to require prediction or at least anticipation
whats the difference between prediction / anticipation
Client anticipation is only relevant for games using a client-server topology.
It's discussed briefly at the top of this page
Client anticipation in NGO doesn't take physics into account and generally is only for individual objects/variables
When a player leaves the lobby, for some reason the data slots are not updated why so?
normally you have to manually update the lobby data on the client side. I'm not sure how steamworks handles it.
how do you make it right?
Looks like there is a event you can subscribe to
The lobby metadata has changed
ty
What are some ways to reduce latency issues in a VR collectathon game using DA? We started playtesting and the experience when players connect from different countries is sub-par, the delay when collecting objects is very annoying. I’m finding difficulties on how to do prediction as I can’t rely on player input due to each player being a rigidbody (our locomotion method is players flinging themselves with their arm movement, flying essentially). Would appreciate any tips or articles
Can you describe the collection mechanics further?
Also you shouldn't have to mess with any sort of prediction for player movement in DA as the movement would be client authoritative.
Essentially you fly around with a set of players in a level and collect objects, demo here (imagine sonic rings). The difference between regular collectathon games I suppose is that the players are flying about really, really fast.
Now the issue issue is confirming collect actions and making sure these actions occur fast. Otherwise, you collect an object and there is a very noticeable delay in FX and similar, to the players it seems like they're missing objects some in cases.
When collecting objects I send a "request" to the owner of the object to confirm if an object can be collected, once confirmed I send back a "response" which updates score, triggers VFX & SFX locally. This is done to avoid race conditions during scoring, I thought about collecting objects immediately locally, but I can't think of a good way to "revert" collect events without messing with UX.
The player object itself is simulated on all clients and is able to trigger collect "requests" on all of them (it has a trigger that collects stuff and the same "request/response" logic), but the issue is that its always way far behind from the owner position-wise, so it doesn't solve the lag issue. The player objects are client authorative and are replicated using ClientNetworkTransform + NetworkRigidbody. Also, the collectable objects can also move due to powerup metchanics (players act as magnets), these are also synced using ClientNetworkTransform. The reason why I mention prediction, is that I'm thinking I could "move ahead" the replicated clients so that the collect action triggers sooner on the owner of the collectable (keep in mind that collectables are distributed between all players in the session).
I'm also thinking maybe DA is not the right choice for this type of game 🤔
DA is most likely not a good choice for this unfortunately.
Too fast paced.
Something you could do for collectables is make your best attempt to keep switching the owner to the closest player so the majority of the time no request has to be sent.
Still wouldn't solve all issues though - so I'd say client-server is pretty much needed unless you sacrifice on the pacing of the game quite a bit.
Does anyone know if autoproperties can work with networkvariables?
eg. [field: SerializeField] NetworkVariable<int> myNetworkedInt {get; private set;} = new NetworkVariable<int>
or no luck
I'm not sure how SerializeField would interact with it, but yeah you could make it work
private NetworkVariable<int> _myNetworkedInt = new NetworkVariable<int>();
public int MyNetworkedInt => _myNetworkedInt.Value;
or something similar should work
Was curious about doing it directly
Probably not - most serialization systems don't allow for it
the door animation is not syncing when a client plays it. I did override the network animation
the player animation is syncing well. but the door animation isn't
this is the script that plays the animation. ani is refrencing the Animator
This could still work in DAm but you would probably need to use raycasts instead of triggers to then request ownership change of the collectibles
The door is not moving at all? Or you are still seeing a delay?
not moving at all. when the host play the animation it does. but when a client do it it doesn't
The door is still owned by the server. You need to send an RPC to call OpenCloseDoor()
then why does the player animation works fine?
Client owns the player
Oh thats not a bad idea actually, I could predict the length/radius of the ray I think
how can I make an objects owned by a certain client?
Right, make it longer the faster they move
Send an RPC to call ChangeOwnership(clientId) on the server
NetworkTransform.ChangeOwnership? or NetworkObject ?
A NetworkObject is a GameObject with a NetworkObject component and at least one NetworkBehaviour component, which enables the GameObject to respond to and interact with netcode. NetworkObjects are session-mode agnostic and used in both client-server and distributed authority contexts.
Great. thank you for the help
After I fixed it I got this error
I have no idea what is it. but the game works fine
if the gameObject is inactive in the scene to which the above Script(CreateLobbySettings) is applied. and i am running this function in another script with different gameObject which is active. Will the function still work ? As it is not updating the lobby list in my scene, i thought there might be a problem.
OK. Fixed it by attaching script to an active gameobject. ✅
I'm working with NGO, I'm connecting 2 players, 1 host, 1 client. But what is weird is that there is a "remnant" hitbox where both player-instances started (when both connected). And the two players dont actually have hitboxes that collide with each other. I'm using a CC as well
Can anyone tell what is the issue here
private void StopClient()
{
if (NetworkManager.Singleton == null)
return;
if (NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsHost)
{
RequestDespawnServerRpc(NetworkManager.Singleton.LocalClientId);
}
}
private System.Collections.IEnumerator LoadLobbyAfterShutdown()
{
yield return new WaitForEndOfFrame(); // LET COMPLETE SHUTDOWN
}
[ServerRpc(RequireOwnership = false)]
private void RequestDespawnServerRpc(ulong clientId)
{
foreach (var obj in NetworkManager.Singleton.SpawnManager.GetPlayerNetworkObjects(clientId))
{
obj.Despawn(true);
}
NotifyClientDespawnedRpc(clientId);
}
[ClientRpc]
private void NotifyClientDespawnedRpc(ulong clientId)
{
if (clientId == NetworkManager.Singleton.LocalClientId)
{
StartCoroutine(FinishShutdown());
}
}
private IEnumerator FinishShutdown()
{
yield return new WaitForSeconds(0.2f);
NetworkManager.Singleton.Shutdown();
StartCoroutine(LoadLobbyAfterShutdown());
}
This code for disconnecting client. Is there any error here ?
How can i fix it
Sounds like you just moving the character model and not the parent network object
None of these RPCs are necessary. Calling Shutdown on the client will automatically respawn the client's network objects.
Ok.
I hve the object and transform on the same prefab
You'll need to disable the character controller on the remote players
I tried to write " characterController = gameObject.AddComponent<CharacterController>();" inside of the character controller and now the player spawns at y = 0 and then gets swapped to some other
But they sitll do not have hitboxes
You shouldn't just add a character component. It already has one. You will need to disable it in OnNetworkSpawn() if IsOwner is false
Hello! Would it be possible to invoke an RPC method event if the user is offline (aka not connected to any server, not even itself)? Right now, if I go into offline mode and try to call this method, nothing happens, I would like it to run if not connected.
void DoSomethingRpc()
{
Debug.Log("Do Something");
}```
When I pair netcode for gameobjects with lobby and relay. Where the player prefab gets spawned the moment he join the game. Which scenario should I implement?
1- Main menu and game in a single scene. Handling lobby, relay and connection
2- Main menu and game in separated scenes. Where main menu handles lobby and relay data and then load the game scene. Through a playerPrefs I know if I startHost() or startClient()
3- another approach not mentioned?
I don't want the lobby to get destroyed unless the host leaves. I want to allow players to join mid game
No, you need to connect to yourself as localhost for RPCs to run
I would use sessions so you don't have to manually manage you lobby and relay connections.
What is this?
We just put our demo out, and for the most part things are going well. But we have some lobby/connection/NetworkManager bugs that we need to sort out asap.
Are we allowed to hire and recruit contract work here? We’re looking for a veteran with experience, someone who knows exactly what they are doing and have shipped live games using Netcode for GameObjects, Relay, and Lobby.
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
I'm trying to make a physics based box that you can push around, but only the host can move it, clients just run into it. i have a network object, network transform, and network rigidbody on both the player prefab and the box prefab. Anyone know how i can get the clients to be able to push it?
Network Rigidbodies that the client does not own are set to kinematic. You can either request ownership of them or send RPCs to add force when needed
how could i request ownership then?
call GetComponent<NetworkObject>().ChangeOwnership(clientId); on the server
A NetworkObject is a GameObject with a NetworkObject component and at least one NetworkBehaviour component, which enables the GameObject to respond to and interact with netcode. NetworkObjects are session-mode agnostic and used in both client-server and distributed authority contexts.
@sharp axle is there not a way for multiple clients to own the same network object? all players need to be able to push around the boxes
or maybe i could change the ownership to whatever player hits it right when they collide?
You'll end up with race conditions if multiple clients try to move the same object at the same time.
so would this be a good way of doing it then?
You'll want to change ownership slightly before the collision. It takes a network tick for the owner to change
oh i see
why does the "authority mode" default to "server"? Nothing seems to work when its on that mode instead of "Owner". Does that mean I'm doing something wrong, or does this have do with client- vs server-auth movement?
Why, do I have to disable the CC?. Then they can't interact with each other. No hitboxes
If I have the CC disabled, then enable it. The hitbox tps to where the clone was standing when enabled, however, this hitbox doesnt move with the charcter
The CC, network-object script and the transform is all on the same root, which is parent to all the player objects (for 1 player)
That sets who is allowed to commit changes to the transform that will be synced to all others.
Character Controller will override the Network Transform, unless you are calling cc.Move() in a client RPC. But then you wouldn't need the network transform at that point
NGO defaults to server authority
What does this mean 😭
this is how I move the char
it is using cc.move
this makes no sense to me. There is an invisible hitbox that I can't move through right infront of the selected capsule
I feel so incredibly lost it actually hurts
tl;dr - you should be checking IsOwner in OnNetworkSpawn and before your movement code, so that only the authority is driving the movement and syncing it to all others
is this not enough?
Also some friendly word of advice, multiplayer is no walk in the park. If you're not already quite comfortable with development in Unity, I wouldn't recommend jumping in to multiplayer.
The non local player objects will need their character controllers disabled so the network transform can sync their positions
so in short, if (!IsOwner) {characterController.enabled = false;}. But I tried that, which resultet in the two objects not colliding
I assume theres more that I'm missing
you can have a separate collider if needed.
If I'm getting this right, its about server vs client auth movement. In both cases you need to disable the cc-component of other clients (please tell me this isn't wrong). Client-auth: clients CC needs to be enabled for the specific client, disabled for other. This way, he moves directly through recorded input through the CC. For server-auth it's a bit more confusing to me. You disable the clients CC and make the server listen to the inputs and move the player through Network transform.
This line in the article linked by Dylarno, is hard to understand "Enable the CharacterController on the server instance and disable it on the client instance(s)."
Does this mean that the server has "copies" of the players which has cc's that are enabled and that is simulated. Then that movement is applied to the actual client?
The server runs the application just like the clients do. Server authority is not much different from Owner authority in your current case. CC enabled on the authority, disabled on all others.
The only difference is that with Owner/Client authority, you can perform the movement locally and immediately. With Server authority, the client has to send a message to the server who is the authority, sending information on how to move the object for the server to perform.
If I want "the server to drive the CC" (assuming this is equiv. to server-auth movement). What would that set up look like? Would you have a manager-script that existed in the world that read a players input and moved them?
a very barebones example of a client requesting movement to be performed on a transform with server authority
void Update()
{
Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (input != Vector2.zero)
{
MoveServerRpc(input);
}
}
[ServerRpc]
void MoveServerRpc(Vector2 input)
{
Vector3 movement = new Vector3(input.x, 0, input.y) * Time.deltaTime;
transform.position += movement;
}
😮 wow, thanks for writing that out. So the Server exists within the player script?
Or is it meant as in: the two methods are in different scripts
RPCs are sent to the server
wait. No yeah im stupid, sorry
[ServerRPC] Means that the client is sending a RPC to the server
Just like I mentioned above, it runs the same as the clients do unless told otherwise. This is what the IsOwner, IsClient, IsServer flags are for, as well as the [Rpc] attributes, to send specific messages to specific connections.
Well, shit. Thanks for helping me. Understand if it feels frustrating trying to, essentially, explain calculus to a toddler. I'm going to bed and then reading a lot of doc tomorrow, hopefully understanding some of this better
Hey everyone, so I have script A being the one with the singleton, and it has a method MethodA. The Instance is set upon Awake.
Script B contains a Start method where I attempt to call script A's methodA. Why is scriptA's Instance null?
https://www.ghostbin.cloud/soo55 hi this is my first time with multiplayer. i was wondering why the player cant see the bullet come out of the gun? but the host can still see the bullets after the client clicks, the bullets just dont show for the client. any help appreciated, thank you!
Any errors? Is bullet in the NetworkPrefabsList?
no errors and yes it is in the list
Can someone tell why this error comes, when i call NetworkManager.Singleton.Shutdown() on a client.
You have code somewhere on the client that is trying to destroy or respawn the player object. Switching scenes before shutdown will cause that as well
I try to refrain from using singletons in networking. Scene objects get spawned when the scene loads and the timing of Start() and Awake() is different
Check the client inspector to see if the bullet is actually getting spawned on the clients
Ohh. i think switching scenes before shutdown might be causing it. Thanks 🤝
the hosts bullets are spawned but not the clients
Have you put Debug.Log calls in to check if .Spawn is actually getting called?
I see there's a return in your ShootGunServerRpc which could be unintentionally getting called
lemme check rn
you might be right, spawn is not getting called
even removing the return, though, still doesn't work
You'll want to make double sure that bulletclone is a network object instead of just a game object
yea it has a networkobject component
Have you tried storing bullet as a GameObject? This is the example of how to spawn things in the docs
var instance = Instantiate(myPrefab);
var instanceNetworkObject = instance.GetComponent<NetworkObject>();
instanceNetworkObject.Spawn();
I think you need to explicitly type NetworkObject for Instantiate()
That's odd. Are you using GetComponent<NetworkObject>()?
yes
You could also try using InstantiateAndSpawn()
If NetworkObject.Spawn() isn't getting called then something else is wrong
No longer relevant advice for this one but in the future another thing to check is if the thing running that code is correctly spawned too
good point
its on my player tho
which has network transform and object and stuff, and both can see each other so it should be fine
You sure you have no errors? It's very rare a synchronous method would just stop execution like that without warning
@wild mortar you tried this as well?
var bulletClone = Instantiate(bullet);
bulletClone.transform.position = bulletSpawnPos.position;
bulletClone.transform.rotation = cam.transform.rotation;
bulletClone.GetComponent<Rigidbody>().AddForce(cam.transform.forward * bulletSpeed, ForceMode.Impulse);
bulletClone.GetComponent<NetworkObject>().Spawn();
i did this
i got networkcomponent and spawn
heads up regardless
The add force you do is potentially wrong
Since that line of code won’t fire on the clients spawned bullets
If it has a network transform then it should be fine
ye it has network transforrm
You might need to attach a debugger to see where in the RPC it stops executing
Basically NGO has a big list of networkobject prefabs and when you do .Spawn() that just finds the list index of that prefab, and tells the clients to spawn the prefab at that index.
If you have a network transform your fortunately fine here but any code run on the instanced prefab from the host like that won’t inherently sync with the clients one
as long as the prefab has an active network object there is no reason it won't spawn
how do i do that
Its adding Force in the ServerRPC so its fine
The other thing to try is just spinning up another NetworkBehaviour script and another Network Prefab and seeing if you can get that to spawn
that makes sense
Depends on your IDE, in Visual Studio there is an Attach to Unity button at the top
I've seen NGO mix things up under the hood in editor before, and sometimes remaking scripts or prefabs from scratch can fix problems like this
You also need to add a breakpoint so it stops executing and you can see whats happening
Probably wouldn’t do anything that would silently fail tho right
ok added one
At this point, doesn't hurt to try anything
where shold i be looking i dont see anything different
It should pause at the breakpoint. You can then step through the code
but the debugger didnt do anything
it didnt do anything when the client was in the inspector though
it worked when host was in inspector
I'm on the Unity 6.2 beta and I'm having quite a few issues with Netcode for GameObjects. My scene is very simple, it simply has a NetworkManager which I've left purely on the default settings. I have a button which calles NetworkManager.StartServer() and another button which calls NetworkManager.StartClient(). After the connections finish, another scene is loaded. In that scene, I have the following extremely simple component on the same GameObject as the NetworkManager:
private NetworkManager _networkManager;
public void Start()
{
_networkManager = GameObject.FindFirstObjectByType<NetworkManager>();
Debug.Log($"Is server: {_networkManager.IsServer}");
if (_networkManager.IsServer)
{
_networkManager.OnClientConnectedCallback += ClientConnected;
}
}
private void ClientConnected(ulong id)
{
Debug.Log($"Client connected {id}");
TestRpc();
}
[Rpc(SendTo.NotServer)]
public void TestRpc(RpcParams param = default)
{
if (_networkManager.IsServer)
{
Debug.Log("SERVER Test");
}
else
{
Debug.Log("CLIENT Test");
}
}
The server is correctly logging "Is server: True" and the client is correctly logging "Is server: False", but TestRpc is only ever getting executed on the server despite the fact that it's marked SendTo.NotServer. I tried to debug this by using SendTo.SpecifiedInParams and then calling
TestRpc(RpcTarget.Single(id, RpcTargetUse.Temp)); but when I do that, I'm getting Cannot access non-static method 'Single' in static context as a compile time error.
This is a fresh project, this is literally the only code that exists in it. I'm just trying to play with Unity's RPC to compare to Godot RPC.
Start() runs before the network is connected so that might be causing your issues
What behaviour in the Start() function would be causing issues? All it does is check to see if it's the server, and if it is, subscribe to the client connected callback.
IsServer won't be properly set because its doesn't know if its a server by then
The actual connection is being done in another scene, so by the time this Scene loads, the connection part is already done. Plus, this part is working. As I said, the server and client are both logging the correct info in Start(). I amended my original post to reflect that info.
If its in a new scene that might be OK then. But i believe OnClientConnected is too early to call a RPC. is should be done in or after OnNetworkSpawn()
I can pretty much confirm this isn't the issue. Before I stripped this code down to its basics, the server was running a coroutine which called an RPC to the client every 5 seconds for a minute. None of those RPCs got called on the client, they all got called on the server, again despite the RpcTarget.NotServer attribute. I stripped the code down to its basics to be able to come explain it more simply here.
I guess I should note that I'm following the docs here: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/
So OnNetworkSpawn isn't a relevant part of the pipeline here. I'm not using any NetworkBehaviour objects yet.
How are you sending RPCs without NetworkBehaviours?
They won’t work properly unless they’re in one.
Can anyone explain this? This is a barebones setup with a script that checks if (!IsOwner), then lets the player move the capsule with some basic code. What's weird is that if I change a variable in the inspector (even to the already existing value), the capsule stops responding to inputs. Can confirm inputs are not even going through from Debugging. But am still Owner of the script
And there it is. I had to extend NetworkBehaviour, not MonoBehaviour. D'oh! Now I'm having another issue though. The code is throwing a KeyNotFoundException whenever I try to RPC to anything that isn't the server.
Means the NetworkBehaviour can’t be found on the receiving connection. Usually happens when the entire object is disabled or components of the object have been destroyed.
Hmm... I must be doing something else stupid. There's no more complex code happening here than what I've posted. The scene consists of a single object which is trying to send RPCs back and forth. Nothing is disabling or destroying anything.
Could also be what evilotaku was referring to early. The RPC being sent too early before the network starts up and this NetworkObject has a chance to spawn on all connections.
I've changed the code so that the server has a long delay before trying to send the RPC - but the same error was happening either way. I suspect that the way I'm doing this just isn't right. Is it enough to just have a Network Object in the hierarchy in the scene? Do I have to do something special with it to make it synchronize between?
NetworkObjects in the scene hierarchy should spawn automatically and be able to send/receive RPCs.
I would think so too, but that doesn't seem to be the case. I've noticed that when my Server starts up, the NetworkObject which is trying to do the RPC calls has a "Spawn" button on it instead of the normal info, which leads me to believe it's not spawning properly. When I click that button, the client then throws an error saying it couldn't spawn the NetworkObject. Which is weird because even after it throws that error, the server then shows that the client has registered as an observer.
I think I'm just going to wipe all this out and go back to tutorial land. It's been a bit.
Thanks for your help folks
If you are switching scenes then you have to make sure you are using network manager scene manager to load the scene
Post your code
I redid the whole thing from scratch this morning and I got to a working product thanks to your and @tame slate 's help.
The keys were:
- Changing scenes with networkmanager's scenemanager
- not having any network objects in the same scene as the networkmanager and instead deferring adding those to the hierarchy until after the networkmanager had been connected
- Doing setup stuff in
OnNetworkSpawninstead of onStart - I have no idea what fixed
RpcTarget.Single, it just mysteriously works this morning in the exact same context I was using it yesterday
honestly ngo is not as hard as i thought as long as you know basic network conecepts its easy to get into
all requires minimal code
sorry for late reply, hda to go to bed (3am)
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerNetwork : NetworkBehaviour
{
[SerializeField]
private float mvmtSpeed = 10f;
[SerializeField]
private InputActionMap playerActionMap;
private InputAction moveInput;
public override void OnNetworkSpawn()
{
if (!IsOwner)
{
Debug.Log("WAS");
enabled = false;
return;
}
}
private void Start()
{
playerActionMap = InputSystem.actions.FindActionMap("Player", true);
moveInput = playerActionMap.FindAction("Move", true);
}
void Update()
{
Move();
}
private void Move()
{
Vector2 readMoveInput = moveInput.ReadValue<Vector2>();
float moveX = readMoveInput.x;
float moveY = readMoveInput.y;
Vector3 moveVector = new Vector3 (moveX , 0, moveY);
moveVector.Normalize();
transform.position += moveVector * mvmtSpeed * Time.deltaTime;
Debug.Log(readMoveInput);
}
}
I tried debugging by Loging the MoveInput values, after I edit a variabel in the inspector related to this very script, the MoveInput values (Vector2) is (0 , 0)
So, I can enter the Field, but if I ever change it, it just stops working
Its any [SerializedField] Variabel actually. I just put another one in the script that doesn't even get used for anything. If I change it, inputs stop being read. I tried changing other properties of the object (i.e its transform) and that didn't ruin anything
Okay, I found the problem. With some help from GPT I found out that I CAN NOT, and I repeat, CAN NOT [SerializeField] on the InputActionMap
Removing this completely solved it. Why? GPT tells me its because of something called "Domain reloads", is that correct?
Do you need to wrap Rpcs with if(IsServer)
or does it automatically run on the server only?
I've never seen that before. But there is no reason for the actionmap to be serialized for the inspector in that script.
Yeah, sure you dont think so. But I like seeing what goes where and what values everything has.
If its [RPC(SendTo.Server)], no
i use the inspector in Debug mode if I need to see private things there
hm, didn't know that was a thing
3 dot menu next to the lock
thanks! thats really usefull
whats the difference betwwen that and [ServerRpc]
[RPC] is the newer version. it does the same thing but is more flexible
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
Hey, um... I wanna make a LAN game, and I know Unity can be kinda tricky with multithreading. So I was wondering if you guys know any libraries or something that already handles the connections? Like, I just wanna manage the packets myself, from reading them to serializing them to send. You know, a library that takes care of the basic stuff
i don't see what that had to do with multithreading but iirc you can use the transport package directly if you don't want to use one of the normal networking packages. but don't do that unless you have some crazy requirement that makes it necessary lol, if you want to write it all yourself i'd say start with NGO and use custom messages for communication
I saw that there were these buttons as well for hosting but I wanted to go trough the lobby (well I could remake everything but I just wanted to try out the existing Unity options first) @spring crane
This function only gets called when I use these buttons but not when I use the provided Unity Widget UI
Don't ping the mods.
If you are using Sessions, check the docs
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-your-first-session
Sorry, thank you for the link !
Not familiar enough with specifics of how NGO is set up.
@sharp axle Context: <#archived-code-general message>
I'm mostly familiar with traditional Client/Server stuff but not the whole setup in Unity
If needed then I'll just go trough a bunch of tutorials but I thought that the widget would at least ease the whole process since it's provided with the Multiplayer Center
Widgets are real good for rapid prototyping but it does a lot for you under the hood.
Yeah I see
Sessions combines Lobby and Relay services. without the widgets it's still just a few lines to get connected
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/create-session#example
Got it, thank you !
What does this error means?
It happened when I tried executing this function
are the components on the network behaviour the same between client and server?
what do you mean exactly ?
if you are talking about PCID. each one has a unique PCID from 0 to 7 (lobby has a max of 8 players)
and on start the player with localClientID will have OwnerShip of the object with the same PCID
all of it's data stored on PlayerPrefs
So when trying to access one which is not yours. you should get the data from the owner's playerPrefs
when I open mine it works fine. but when opening someone's else I get the error
i just mean does the object you're sending the rpc from/to have the exact same components in the exact same order on both ends?
if you add/remove components dynamically anywhere, it can mess things up
You will need to make sure that this is being called after OnNetworkSpawn()
it is. since the PCscript won't exist until the player with the same Id joins the game
how does the system work? there are 8 pcs each with id from 0 to 7. and they are disabled until a player join and have the same id as one of them. then they are enabled. the player prefab is instantiated once he joins the game (host or client)
I don't know how your system is setup. What is disabled? Any in scene network objects must remain enabled for RPCs and Network Variables to sync
in the first function OpenPC
the isOpen is false until a player joins
and when he joins he sends an rpc to update the isOpen for all clients
it is not when he joins instantly. it is when he do certain action
to be exact. when a player do a certain action. his NetworkManager.Sinlgeton.localClientId is used to change the value of isOpen in PCScript that match the same PCID
So I'm pretty sure it is executed after the network spawn
Can you post the full script? You only get that error when the RPC has not been registered in the Network Manager. Either the network object or network behavior being disabled can cause that
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.
the SetPcStatus is called by an rpc function. Rpc(SendTo.ClientsAndHosts)
while the SetPcStatusAnimation is called by the owner
Since the animation is a network animation. it is automatically synced
The FileSystem is a MonoBehaviour
And the root parent object this script is on is an in-scene network object? Or is this on the player?
It is in the scene and part of the map. It is not a network object
Does the parent have to be a network object?
That is your problem. RPCs need a network object to sync
isn't the network object be on the object with the PCscript?
Or do I have to add it to the room parent too?
Not if it's a child object. Network object parenting is rather complicated
Only the root object should have the network object
Wait a moment. I guess I forgot to add the network object to the pc
I will check later. Thanks for he help
I added the network object but got another error
I found the reason and fixed it
Does view.IsMine work right with how im making these 3 scripts? Sorry if I make a dumb mistake I'm trying to get into networking haha! FirstPersonMovement.cs: https://hastebin.com/share/itokeqahuf.csharp Jump.cs: https://hastebin.com/share/iceqafijiv.csharp Crouch.cs: https://hastebin.com/share/gagoloboce.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It should work. but there's no real reason to split them into different files.
Hey! Thanks for the help, is there going to be a performance issue with it being 3 different files?
no. you just have to make sure that all them on your players.
Everything I do is regular and controls myself, but once another player joins, i only control them and they only control me... something wrong in my code?
Anything input related should be within the view.IsMine check. You also need to make sure that View's ownership is getting correctly assigned to each player that joins so that IsMine is accurate. I'm not sure how Photon handles ownership.
how hard would it be to make peer to peer multiplayer in unity? i looked into it with ue5 and it would be kind of hack work to make it function
Probably an easier endeavor in Unity. P2P is a popular choice among indies making multiplayer games with any of the common networking libraries that are made for Unity.
https://www.ghostbin.cloud/sukr0 hello i have a problem where when the player shoots it does not shoot the right direction. i am using a raycast but it doesnt seem like the bullet is actually going the right direction
by the way the raycastGunPoint is a child of the camera and it is at the cameras position
is the direction somewhat close?
Like it's not completely wrong?
it is pretty close but still somewhat to the right
I'm guessing you're just experiencing the effects of latency. By the time the server receives the message to shoot the gun, the client can already be looking somewhere else.
You can calculate throwDirection in this block
if (IsOwner)
{
if (playerInput.actions["Shoot"].triggered)
{
ShootGunServerRpc();
}
}
and send it through the ServerRpc
It still may look off in some regard, but at the very least the bullet will be shot in the direction the client was looking when they clicked shoot
ok cool thank you
True peer to peer is not really supported. Its kind of a security nightmare so at most folks will use a Relay service if they don't want dedicated servers
i didnt even think about security, probably not going to do p2p then. how much do you think a very simple 1v1 multiplayer game's dedicated server should be able to handle? like less than 1 gigabit per second?
normal game bandwidth is measured in kilobytes per second. Dedicated servers can also get very very expensive at scale. I believe most indie games will use client hosts with a relay service.
ill probably do that then, thanks
NGO is largely designed for smaller scale cooperative games. The closest you can get to prediction with built in features is with Client Anticipation.
Building a custom prediction system is not a trivial task and becomes much harder if your game uses physics based movement as Unity's physics system is not deterministic.
Its not impossible but it will take a lot of work to do it properly
I don't think Quake ever had client prediction.
But there are other ways to deal with latency
Tricks and patterns to hide latency, what's acceptable to manage client side with client authority before sending it to the server, prediction, server rewind, action anticipation, etc.
huh, maybe Quake 3 did have it
The original Quake did not have it. It was just fully server authoritative with no prediction system. And this was largely fine as the game was commonly played on LAN.
Looks like Quake World did
It's not an absolute requirement. Many games don't have it
Client Anticipation will get you most of the way there
Client anticipation is only relevant for games using a client-server topology.
it just doesn't take physics into account. Its not a full rollback solution
It really depends on your end goal. If you want a production level of competitiveness and security, you're looking at making something almost entirely custom on top of a low-level networking library. Netcode for Entities boasts a lot of the systems you're wanting, but if you're not familliar with ECS/DOTS that's going to be a bad time.
But I would tend to agree with evilotaku is saying. Unless you truly truly want what I described above, you can get 90% of the way there with other techniques and by making some clever gameplay choices.
DOTS for the most part is completely different from OOP design. Data Oriented Design takes a bit of getting used to but its actually very well suited for networking
If you want to dip your toes in, there is a Competitive Action Multiplayer template you can take for a spin
Photon Fusion has client prediction but you are stuck using their Photon Cloud service. Fishnet also has prediction that is locked behind a paywall.
Yeah that’s been on the roadmap for several years now. While it might come someday I can’t imagine it’ll be any time soon.
This is a number of years away. Unity 7 or later
That being said, definitely exciting nonetheless.
Hasn't this article been published for 6 years now?
That is from April of this year. They haven't been talking about unification for that long. It's being called "ECS For All" now
I'm trying out different interpolation types for network transforms and am curious, what is the actual difference when comparing Smooth Dampening vs Lerp (non legacy). Which one is more preferable in which situations?
Testing locally with network simulator I notice that dampening is more jittery, however I can't confirm if its more accurate or not 🤔
Hey everyone. Please explain, does Unity use TCP+UDP or UDP with selective reliability?
Depends on what you are using. Unity Transport based things use UDP (and TCP on browsers). https://docs.unity3d.com/Packages/com.unity.transport@2.5/manual/index.html
Specifically Netcode. It's UDP, right?
If you haven't changed the transport and are not exporting to browser, yes.
Thank you!
This goes into a little bit more detail on the different Lerp options
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/pull/3355
@tame slate So they told me this.
Here is the free tier limit from the UGS Pricing page:
3 GiB per CCU for free up to a max of 150 GiB / month (combined US/EU/Asia Australia)
I have done some investigation in your Cost and Usage page of the Unity dashboard. Unfortunately, it looks like the confirmed Relay bandwidth usage exceeded the free tier limit in April 2025.
Relay CCU: 11
Relay Bandwidth APAC: 1.7
Relay Bandwidth US + EU: 133.54
While you may not have exceeded the 150 GiB bandwidth free tier limit, it appears that you exceeded the 3 GiB per CCU free tier limit.
The last para
I was under 150 gib they confirmed, charged me because of exceeding the per CCU 3 gib limit
Right. Now that makes sense.
But how do we know if we are exceeding per CCU bandwidth limit?
I thought it was 3GiB for the first free 50 CCU you get. But if you only average 11, your bandwidth usage can only be 33 GiB to remain in the free tier.
I mean it all depends on the type of game and how optimized it is. There’s plenty of genres of games that wouldn’t even come close to that limit.
When I was not subscribed to Unity services. I used to hit 80% of relay usage with 15-20 CCU. But I got never charged
In my game players create lobbies, lobby sometimes have 10-15 players. Support upto 30.
I use network list for player data struct
You’re currently averaging 4x over the limit at over 12 GiB per monthly average CCU which is roughly 40kbps. That is a lot of bandwidth to be using. Even competitive shooters with voice chat don’t use that much.
I would definitely profile your game to see what is using so much bandwidth.
Yeah, can you guide me how I can do that please?
For bandwidth
I also have chat made with rpc. Is it that causing this?
To use Multiplayer Tools, such as the profiler or runtime stats monitor, you need to install the tools package by name.
This package should have a Network Profiler which you can use to monitor bandwidth.
Thanks
Something to consider if that NetworkList is using a lot of bandwidth.
Thanks, I'll check these out
I want to ask. How do you set Max Packet Queue Size and Max Payload size? I set this at runtime with a formula I found on forum.
private void UpdateTransport()
{
int maxPacketQueueSize = networkManager.ConnectedClientsIds.Count * 32;
int maxPayloadSize = (networkManager.ConnectedClientsIds.Count + 10) * sizeof(float) * 3 * 3 * 10;
if (maxPacketQueueSize > transport.MaxPacketQueueSize)
{
transport.MaxPacketQueueSize = maxPacketQueueSize;
}
if (maxPayloadSize > transport.MaxPayloadSize)
{
transport.MaxPayloadSize = maxPayloadSize;
}
// Utils.DebugLog("Updating values " + transport.MaxPacketQueueSize + " and " + transport.MaxPayloadSize);
}
is this okay?
To my knowledge this won't have any effect when setting it at runtime.
Changing this value also has no effect on bandwidth usage in case that's why you're messing around with these values.
how would i reliably move the player for all clients to assume that if the player is seated, it will always be located at the seat
nvm, im gona resort to parenting the player visible model under the car, this works, but i have no idea if thats good
Parenting the player to the car is the way to go
Epic
Yea ParellSync was used before Multiplayer Play Mode
I'm using parellsync rn, is it inferior to mpm? From what I could see, I like the dual-editor setup more
From what I know it’s slower and has less features than MPPM.
Because?
If you are using Unity 6 there is no reason not to use MPPM. But i wouldn't say that ParellSync is inferior. Its still recommended by Unity if you are on earlier editor versions
Building is a perfectly acceptable way of testing. I’ve completed an entire project doing so. I would also assume there’s not much urgency for them to build an in-house solution when there’s a production level plugin available to the community that does the same thing.
There was already a free open source tool that did the same thing. I wouldn't waste the development time reinventing that wheel either
I have a strange issue using the PlayerInputManager while also using Unity Netcode for Game Objects.
It seems that whenever a device joins as a client (not a host or server), their PlayerInputManager picks up the other player's (owned by other devices) player inputs and calls OnPlayerJoined() on these.
The only way I can currently think to stop this behaviour is to have a menu before the player connects where players can join and then I disable the player input manager after this, but is there another way I can stop the PlayerInputManager from detecting the networked objects as "joining players"
Setting it to join manually should work
Hm OK thanks, do you know how I can replicate the whole 'the player who pressed the controller joins a player with that specific device) when it's set to join manually?
There is a JoinPlayer() you can call. It would have to call a RPC to SapwnWithOwnership(). But since that player won't have its own clientId it will be tricky to determine proper ownership
My issue is more assigning the specific controller to that object's player input
I have managed to get the whole spawning with ownership part working
Just how do I let players press a button on their controller and detect the input device(s) it came from and then I call JoinPlayer() on it?
Actually looks like if the player has an active PlayerInput, it will automatically be joined. I'm not sure how the input manager assigns a controller when a new PlayerInput joins