#archived-networking
1 messages · Page 38 of 1
and when I tried fixing the last 50%
I get to stackOverflow now so idk if thats progress or downgrade xd
not with only 2 players. What is the client clicking on to join the lobby?
first he needs to type the code thats generated when hosts creates lobby and then button with linked OnJoinClick
Where are they getting that code?
private string GenerateLobbyCode()
{
return System.Guid.NewGuid().ToString("N").Substring(0, 6).ToUpper();
}
That's on the host, how is the client getting that. Also, you are not setting the client Connection Data that I can see.
I have changed the code considerably let me update you
before I Will send it please dont kill me :/
A tool for sharing your source code with the world!
I tried using Cloude for help it broke it even more xD
@sharp axle
If I want a "client authority" server for a voxel game, is it as simple as keeping a list of all block updates, and syncing them when someone loads a chunk?
I feel like keeping the actual chunks of every player would be expensive, and im not sure how something like terraria handles that.
what's that?
Hello readers, I’m no longer posting new content on gafferongames.com
Please check out my new blog at mas-bandwidth.com! Introduction Hi, I’m Glenn Fiedler and welcome to Networked Physics.
In the previous article we explored the physics simulation we’re going to network in this article series. In this article specifically, we’re going t...
hmm makes sense
my game would probably be simple enough not to need that though
is deterministic lockstep not something you can do with fishnet?
No idea, not unless they made their own physics engine
any frameworks you can suggest that do support it?
I think Photon Quantum. I haven't used it either though
Quantum exposes the entire game state though, which makes cheating (like removing fog of war) unstoppable
but I doubt I need deterministic lockstep
That will happen with any deterministic networking system.
Usually in RTS games, there are thousands of objects, which can be way too much data to sync.
That's why RTS games in the past used input sync with deterministic simulation, to only sync inputs (less than 50 bytes per connected player) instead of the state of those thousands of objects.
Today you probably can get away with using a traditional state-sync networking solution like Mirror or NGO.
Just be aware that 99% of the most popular RTS games are all built with a deterministic simulation.
ServerRpc not executing Unity NGO
Should I be using il2cpp with steamworks.net? Or does it matter
I don't think it matters.
You should always use IL2CPP, it provides better performance than mono, and your game code cannot be extracted in 3 minutes.
Your game code not being as extractable can be a con depending on the author
How does a building system work for a dedicated servers hosting a persistant game map? (like base building in rust or dayz for example)
There are loads of different ways to do it. I would save a prefab id and transform into a database somewhere. either locally or remote
it just confuses my brain haha how the inventories of objects get loaded etc
inventory would be a list of item ids and amounts and maybe durability if the game has that. Probably stored in a different database from the building database
ah right then the only cloud database id need is for monitoring users like when users first launch game retrieving steam id, gamertag etc and what skins they have unlocked
then the server side database would store all the inventories etc
Then if i had a global inventory system like a global vault that is common across all server clusters i need a cloud database for that
Would Netcode for Entities be suitable for an RTS with 100s / 1000s of units?
Or do I really need a deterministic system for these larger scale battles?
I'm not sure how complex my game is going to be, but I'd rather not waste a ton of time just to figure out it doesn't work without a deterministic system.
I do think my combat will be fairly simple, closer to an auto battler than RTS
are you planning on server hosting or client hosting?
it would be server authoritative
If your game is not already going to be built with DOTS, then stick with Netcode For Gameobjects.
Yeah I mean dots + netcode for entities
I guess the question is if you already know how to use DOTS for your game. It's a hell of a learning curve
Hmm, I've seen some videos about dots, it didn't seem that complicated, but never tried it.
Would it be worth learning for a project like this? I do have the time
Can anyone send a tutorial or something, how to make my game multiplayer, so my friend can join? i made a snake game, and i want it to work as multiplayer, what are the steps, youtube tutorials are outdated
i want to host it on my pc and so my friend can join via code or something
and it will spawn 2 snakes and each of us could play on same board
It took me about 6 months to fully wrap my head around DOTS. Learning NFE added even more time
Check out Code Monkey's multiplayer courses. But trying to convert a single player to multiplayer is going to be a bad time. It's often easier to start over from scratch
i mean it's just a pretty simple game, i just have movement done
it's constantly moving forward and you can just press A/D to steer
1 script literally
any ideas why a null ref is getting stuck in here? driving me crazy! completely bricks the update loop and freezes all the objects on the client
nvm i think i fixed up? seems caching this value even locally seemed to cause it to get stuck
nvm i didnt fix this i just broke something different
i'm using mirror and i have nametags above each player corresponding to their steam persona name, i want the nametag for the local player to be blank but everyone else's to be normal (so each player doesn't see their own nametag)
i'm sure this is possible, but i just can't figure it out. currently what i'm doing is using a command to trigger a clientrpc function that uses a local boolean to figure out if the player sent the command or not - but this doesn't work when a new player joins. i tried to use a list to keep track of the previous nametags created before a player joins and assign them in OnStartLocalPlayer but it doesn't do anything.
Are the nametags a child of the players gameobject? has mirror got something like NGO's IsLocalPlayer check to see if the tag belongs to the local player and disable it?
Shouldn't need any RPCs to do this. Can make their username a SyncVar and use something like recommended above. NetworkIdentity has a flag called isLocalPlayer
mirror has islocalplayer but when i set the player nametag blank when islocalplayer is true it still displays for the local player
as if i never even did anything
why dont you disable the gameobject or renderer? doesnt sound right
possible you're doing it before the network object is spawned?
if its similar to NGO
that did the trick, but let me see if it works as players spawn in
oh dang now it doesn't show for any of them
no, my script requires the player to be spawned for it to work
oh and as you asked earlier, the nametag object is a child of the player object
i will show you guys the functions i'm having trouble with
hold on let me make a pastebin
How exactly does unity multiplayer hosting hosting work for netcode for entities
https://pastebin.com/1g2CLf5i there we go
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.
ui camera and "name tag" are the same thing by the way, i accidently put "name tag" instead of its actual name
still in the script its correct
have you tried moving the contents of start into OnStartLocalPlayer?
in NGO there is OnNetworkSpawned which you can use to perform scripts once your object is spawned, usually things like IsLocalPlayer or IsClient or whatever wont be reliable until its spawned
so cant be used in Awake or Start
i'll try that
as far as i was concerned onstartlocalplayer was just an alias for void Start() {if (!isLocalPlayer) return; }
is there a Mirror equivalent to OnNetworkSpawn?
I would assume it is called when the Gameobject is spanwed and registered to the network manager
Start could be called before the object is even registered as being network, just your local copy of the object
mirror treats the player object and generic network spawn objects completely differently
i can't even list the player object as a spawnable prefab without getting an error
(you're not meant to)
thats intense, i feel like the idea still stands tho
calling on Awake and Start, thats for your client, not for handling networked things
i'm pretty sure mirror runs an identical copy of the script both on the client and server except of course for the relevant values being changed like isLocalPlayer
also i did this but only the first player sees the nametag on the other player who joined after him
the player who joined after him can't see anything
basically i'm at where i was before i asked the question
i guess start by shoring up your scripts, i wouldnt rely on strings and .Find for absolutely anything, why not use serialize fields?
setting yourself up for headaches
usually i'd agree but there's two lines in the script where i use find on the nametag and objects i use constantly are serialize fields like you suggested
player.Find("UI Camera").transform.Find("Name").GetComponent<TextMeshProUGUI>().text = SteamFriends.GetPersonaName();
and
player.Find("UI Camera").gameObject.SetActive(false);
last one is now in onstartlocalplayer
Not sure how much i can help you with mirror but this is pretty much how my nametag works for my current project
no problem, thanks for the screenshot
i'll probably be fine i just wanted to speed it up a little
like you probably realized there's many things i didn't try
i hope you get it!
For a server browser like unturned or rust or dayz whats the best way to check online servers in server list? do i direct ping the server? or do i try send a special packet to the server and server interprets that packet as a "online test" or what
since when a dedicated server is launched current it sends a heartbeat to my global main database of all servers, then client side server browser loads all servers that have had a heartbeat in last 5 minutes but we also do something ourselves for each server in that list that have been online in last five minutes to actually check that each are still online
You probably don't want to do this as it would be an unnecessary strain on the servers. Normally your servers, as you said, will send a heartbeat to the master server, and clients get the server list based on the state of the master server.
oh right but then surely, if a server sends heartbeat 3 minutes ago then shuts down all the clients would view that "shutdown" server on the serverlist and if they try to connect it wont work
Correct. You want to balance the server load / ping frequency with the frequency of your server shutdowns.
If your servers are very short lived (ie if the chance of connecting to a server that recently shut down is high), you want your heartbeat more frequent.
Ideally it will be rare that players try connect to a server that shut down, but if they do you'd just let them know "The server you are trying to connect to is no longer available"
ah right and if i want it to be even better i could just trigger "shutdown =true/false" on my master database and that gets triggered on a true server shutdown (obviously server crashes wont trigger it so then it would default back to heartbeat) and then client side id also just ignore any shutdown tagged servers on server list 👍
got it tysm ❤️
would a simple rest api get overloaded? for example if each time i press refresh server list it requeststo https (obviously will be real link when pushing real build but for now hosting myself)
how to use netcode for entities with unity multiplayer hosting?
Its the same, you just only create a Server World in the bootstrapper
https://docs.unity3d.com/Packages/com.unity.netcode@1.5/manual/client-server-worlds.html#customize-the-bootstrapping-flow
So can I just develop peer to peer and then change it right before publishing?
Yea. the client and server worlds are naturally separated.
Alr ty
0x00007ffd57f5f9de (Unity) Stacktrace::GetStacktrace
0x00007ffd564b2c9a (Unity) DefaultBurstRuntimeLogCallback```
what are the common causes for this error when connecting to dedicated servers?
Usually firewall issues when sockets fail
Ah, but for production if i launch my game how would i fix it on a global scale?
Open the ports on whatever machine you are hosting that server on
I'm trying to setup a simple multiplayer demo using steamworks.net
I have steam running, however it gets stuck waiting for the steam relay to initialise (SteamNetworkingUtils.InitRelayNetworkAccess())
Since the relay never initialises I can't use the steam p2p stuff.
I haven't created a steam app yet so I am using appid 480 which too my knowledge should be fine to use for testing.
I have tried disabling my firewall.
Has anyone got p2p to work before?
Usually done through your hosting service provider
ohh right thats why because i am self hosting a dedicated server for testing purposes so likely 7777 isnt setup to recieve traffic
What network library are you using?
None, just steamworks.net https://steamworks.github.io/
Enable logging for steamworks gives: SDR RelayNetworkStatus: avail=Attempting config=Attempting anyrelay=Waiting (Attempt #1 to fetch config (only-if-cached) from https://api.steampowered.com/ISteamApps/GetSDRConfig/v1?appid=480)
Never manages to get past Attempting to Current
I can open the api link in browser and works, so not sure why the application is getting stuck on it
What's the best method for making an inventory system in my 3d horror game using unity's netcode for gameobjects? Or is there some way I can modify my current setup to make it work?
My current setup:
Pickup prefab: a networked gameobject that has an ItemPickup script that calls the player's Inventory component's "Pickup" function. That's about it
Inventory component:
saves 4 uints that represent item IDs in a NetworkList<uint> to represent 4 item slots
After the user equips an item, it calls a serverRPC that calls a clientRPC that looks up a ScriptableObject based on the new equipped Item ID and creates a local (not networked) visual for the item in the owner's hand based on the prefab in the SO. This is where the problem lies. If the item is functional (a flashlight, a gun, etc.) then it needs to have network functionality (turning on/off for a flashlight, spawning bullets/reloading for a gun) and save state (battery percentage, ammo count) but it also needs to be non-networked so that I don't need to do any kind of FollowTransform type script because of unity's weird NetworkObject parenting rules.
Is there a tutorial out there somewhere? Or could one of you guys point me in the right direction?
Just my advice others may disagree.
You should probably just follow Unity’s NGO parenting rules.
I avoid parenting by using network Rigidbody fixed joint to attach them
If I were to do that, would this be the approach I'd have to follow? This is my current understanding of it, and it seems pretty crazy to have to do this:
When a client connects, spawn the player prefab and the player's "hand" prefab separately
Manually make the hand a child of the player
Then make any items children of the hand
Does that sound right?
Are there any downsides to doing this? Like visually lagging items when the player turns their head or anything? It seems like a roundabout way of doing this but if it works I'm down to try it
NetworkObject transform values are not synced
You’d need a NetworkTransform for that
which in my experience works fine but in regards to your question is unrelated
I believe that process is roughly correct but iirc you should be able to spawn the hand and parent it in the same step with one of the params but can’t confirm rn
I meant like would I have to do something like how the unity docs describes here:
It seems like the seats are to the vehicle as the hand is to the player in my situation, so it appears that this is the approach I'd need? Unless I'm completely wrong
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
ah gotcha
I'll have to look into that
With parenting, you would parent the item to the root player object. Then set the item's local position to the hand bone or whatever
You can totally just parent it to the hand though?
Not saying your incorrect, just that both are valid
Only if the hand is also a network object.
I think Batby is right there, but that does mean I'll have to put NetworkObject components on every child leading up to the hand I believe.
Yeah
both valid, just depends on what you would prefer to deal with rn
if I have a complex model though, it would be tedious to put all the pieces together in code, no?
A Parent Constraint can be nice if you wanna go evilotaku’s route though
You don't really want to make every bone a network object
Would the fixed joint approach have any visual bugs with it? I tried an approach where the item would just update it's transform to match the hand's location, but it would lag a little and wasn't a great solution. Would I run into something like that using the fixed joint?
I haven't used it in a bit, I don't think you should see any lag. But since it's physics based, you can any movement to be updated in fixed updated
Relay service is expensive 🥲. My game is F2P
They didn't even sent me the Budget Alert (I have setted it) it's still showing 0$ usage
100+ CCU?
Using these services with unmonetized games is a bad time. If your game is monetized in some way other than donations, covering these costs should be pretty easy.
40-50 CCU. Bandwidth costed me. No CCU charges
I do have in game purchases and ads in mobile platform
You can't set budgets for Relay
I thought it's common for all setvices
I would expect mobile ads to easily cover relay costs. Make sure you aren't doing anything silly with bandwidth.
The budget amount is a monthly value that will reset each month. It applies to the total spend in your organization across all projects. You can select which UGS products to include in your budget. UGS products included in budget alerts are Analytics, Cloud Code, Cloud Save, Economy, Lobby and Voice and Text Chat (Vivox).
My previous version tho was unoptimized. Now i did many bandwidth optimization
Ooof
I was checking it all 15 days regularly lmao
If you are exceeding 3 GiB per CCU for free up to a max of 150 GiB / month, I think you are doing something very wrong
My new version does have some reduced usage
Are you sending files over the Relay? That's kinda crazy bandwidth for the amount of users
No, I do send structs in Network List
It contains player data
Ideally you should figure out how to measure your actual bandwidth usage so you can determine whether you're maybe not optimizing it as well as you could be.
.. Or you could switch to Epic Online Services, which offers the same thing but for free*
Loading a scene does not bring other players
Hello, I'm trying to move in the client, but when instantiated its rigidbody turns kinematic, making unable to move how I fix this?
Setting linear velocity of a kinematic body is not supported.
UnityEngine.Rigidbody:set_linearVelocity (UnityEngine.Vector3)
PlayerSoccerController:NormalMovement () (at Assets/Script/CharacterScripts/SoccerRelatedScripts/PlayerSoccerController.cs:59)
MoveState:UpdateState () (at Assets/Script/CharacterScripts/StateMachine/States/MoveState.cs:15)
PlayerSoccerController:Update () (at Assets/Script/CharacterScripts/SoccerRelatedScripts/PlayerSoccerController.cs:41)
When using network Rigidbody, only the owner can apply physics to it.
Anyone got experience with Quantum?
Is it worth learning? How hard is it? How are the docs?
What % of my earning should I expect to pay them total?
but then who I move the client without the rigibody?
You can move it with the rigidbody. He's just saying the owner has to do it.
If the RB is getting set to kinematic, that likely means the local client is not the owner and the server is.
if im not mistaken this is kinda not true right? network rigidbody relies on the networktransform which only the server can apply physics to it. Unless you implement a client network transform that allows non-server owners to write to it?
In NGO2, Network Transform now has a Authority Type enum so you can switch between Owner and Server without the need for a client network transform
ah i see
i actually don't know what the vibe is on this server for default version assumption
I assume most people have moved to Unity 6
I personally don't know anyone working with it yet, honestly hard to gauge the average
I don't understand .
When I start a host then connect a client, the client will never be the owner so the rigidbody will be kinematic making it unable to move.
Then you would need to send an RPC to the server. Or you can use Distributed Authority
The distributed authority network topology is one possible network topology available within Netcode for GameObjects. Distributed authority games use the distributed authority model.
You need to use a client authoritative setup where the client owns the object, or you have to send requests to the server for it to move the rigidbody.
Right you can also request ownership of the object
I would say it's pretty easy to gauge. We're 6 months in to LTS releases of Unity 6. The only people not switching over with legitimate reason are those with larger scale production apps that have older systems/packages/etc. that don't work with Unity 6.
Anyone else has either switched over, and if they haven't, should be switching over.
I mean I personally don’t upgrade until I have a reason to
You would fall in to that last group I described 😛
how I ask ownership of the object of the client, can be done in the onClientConnect?
And I have been testing , the client sees the host, but doesn't update the host position, the gameobjects have the network tranform and network object
also I wanted to spawn the host, clients manually.
for example the host starts but doesn't spawn the player prefab only after something happens, and the clients also don't spawn right after they connect they wait for something first to happens too.
I didn't know how to do that, so I just asked chatgpt how to do it.
It give me this
using System;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class AddNetworkPlayer : MonoBehaviour
{
[SerializeField] private GameObject playerPrefab;
[SerializeField] private List<Transform> playerSpawnPoint;
private int nextSpawnIndex = 0;
private void Start()
{
if (NetworkManager.Singleton.IsHost)
{
NetworkManager.Singleton.ConnectionApprovalCallback += OnClientConnect;
Debug.Log("[Host] Spawning local player...");
SpawnPlayer(NetworkManager.Singleton.LocalClientId);
}
}
private void OnClientConnect(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
Debug.Log($"[Server] Client {request.ClientNetworkId} is trying to connect...");
response.Approved = true;
response.CreatePlayerObject = false;
Debug.Log($"[Server] Spawning player for Client {request.ClientNetworkId}...");
SpawnPlayer(request.ClientNetworkId);
}
private void SpawnPlayer(ulong clientId)
{
Transform spawnPoint = playerSpawnPoint[nextSpawnIndex];
nextSpawnIndex = (nextSpawnIndex + 1) % playerSpawnPoint.Count;
GameObject newPlayer = Instantiate(playerPrefab, spawnPoint.position, playerPrefab.transform.rotation);
NetworkObject networkObject = newPlayer.GetComponent<NetworkObject>();
networkObject.SpawnAsPlayerObject(clientId);
Debug.Log($"[Server] Successfully spawned player for Client {clientId} at {spawnPoint.position}");
}
}
You can either call SpawnWithOwnership() or Change ownership() on the host
and I don't know if its the right way to do it
SpawnAsPlayerObject should also work. Use that or either of the recommended functions above.
SpawnAsPlayerObject() changed to SpawnWithOwnership() it now works
should this be happening?
[Netcode] renderTime was before m_StartTimeConsumed. This should never happen. renderTime is 69,9273291252212, m_StartTimeConsumed is 69,9333333333333
It's an open issue on the NGO GitHub, still awaiting a response. Most people seem to say it doesn't cause any issues for them beyond the message being logged, a few have said it seems to come with issues. Just keep an eye on things.
There's also this reply from a Unity staff member says it's likely just an ignoreable rounding error.
Can you just download the multiplayer packge and add network object and network transform scripts to your game objects to make it multiplayer? Lol
yesnt
There's a lot of foundation you gotta lay out to handle clients joining leaving/ syncing values on your code etc.
but once you get into the rhythm of it, kinda yeah
Trying to convert a single player game to multiplayer is going to be a bad time. Technically possible though
hey does anyone know how to correctly setup lobby and public list of lobbies?
for some reason I keep getting
I would use Sessions for this
I mean this is possitive right? xD
first one is unity relay and second one is lobby
If anyone could help me out on #1359248262263210085 I would appreciate it 😅
I am getting desperate as I can not find out what is going wrong and it has been days. ALL help is appreciated thank you everyone who checks it out
left is the client and right is the host.
why when the client moves the respective animations don't play on the host side? clearly it plays and shows the idle animation but doesn't update.
and when it turns right or left it looks clunky, and the client when is to apply force there's a huge delay.
hi,
i have a syncing issue. I have the script as a networkbehaviour, i have the objects as network objects yet it doesn't sync. Is there anything else i need to add?
p.s. it returns if !IsOwner is false,
this is also unity netcode with unity 6
depends on how you want to sync it
networkbehaviours on their own don't sync any of your stuff
i just want it to update so when the player grabs an object, the other player can see that object move when the player moves it
you can try to add NetworkTransform to each of these grabbable objects.
it should sync the transform over the network
Oh its network transform i need? I’ll try that now. Thank you!
depends
that would sync the object moving
but its likely youll need to use network based code to handle the pickup being synced instead
Hello,
I'm developing an application for Meta Quest 3 using Unity, BuildingBlocks and Fusion. Every time I install and test a new build on the device, the app asks for runtime permissions — specifically for microphone access and spatial data access (like positional tracking or scene understanding).
The issue is that these permissions are not requested all at once. Instead, the app asks for one permission (e.g., microphone), and after granting it, I have to close and reopen the app for it to ask for the next one (e.g., spatial data). This cycle repeats multiple times, making the testing and development process frustrating and time-consuming.
Is there a way to pre-grant these permissions, or configure the app so that all required permissions are requested together on the first launch, avoiding this repeated back-and-forth?
I've already added the necessary <uses-permission> entries in the AndroidManifest.xml, but the runtime prompts still happen separately.
Any guidance on how to streamline this permission workflow would be greatly appreciated.
Thank you!
What bbdd works fine with Unity and NGO? Some advice
What is bbdd?
Seems to be an abbreviation for databases in another language?
my game : farm idle + social game (no combat/fighting)
multiplayer element :
simple interaction between players (waving , laughing etc)
simple interaction to scene object (sitting on chair, opening a door)
players might able to interact with farmland
size : 1-4 ppl , max 4 per instance (room)
matching : like genshin, lobby like matching system
expected DAU : below 100
after serious consideration , i will go for netcode on unity 6, is it fine for this? cuz many game companies here will have their own backend system + websocket to connect to it, very complicated
NGO and all the other popular networking solutions would be able to make that kind of game.
thank you 👍
Yes sorry database 😂
Database sorry
Depends on the game. If you just need backend storage of simple data for players and the game itself, Cloud Save is a good option. Especially if you’re going to use other Unity Services.
is like tibia game
Hi, i am able to spawn the player but i am unable to move
the log works
the player is kinematic for some reason, I tried to add force at the start and that won't even work
Not sure what that is either. But you can always make webrequests to whatever database you decide to go with.
If the player is kinematic, that means that client is not the owner of the object. Or you have a server authoritative network transform
no the client is the owner, i verified multiple times
even this box is kinematic and it has a rigidbody
it's floating if you can't tell by the image
This box is not a network object. It's also not kinematic. You got something else going wrong. Like time scale or gravity set to zero
Sounds like you are in the wrong channel, but that is 2 pipe symbols. It's above the enter key
Yep i already found a solution for that , since my keyboard is azerty its alt+6 and i got the script to work! Also didnt notice i was in the wrong channel my bad
I've managed to fix it, thanks
now anyone on the same wifi can join the game but now do I need to use relay so others can join the game?
Yea, unless you are hosting a dedicated server with port forwarding.
I tried to use it and i was asked to migrate to MultiplayerServices but now i am facing these 2 errors that I couldn't figure out how to fix
With the new package, you don't need to create the Relay manually. This is all you need.
I am using Unity 2022.3.42f1 and am getting an Object reference not set to an instance of an object error from a network variable that fails to serialize something I suppose? I do not believe that I have changed anything related to a network variable recently so weirded out at the error. I do not know how to trace it back and having checked literally all the network variables I have, none of them are set to a null-value.
Paste Mod: https://paste.mod.gg/azddjcfhwchw/0
A tool for sharing your source code with the world!
Looks like it's related to a fixed string. Are you maybe reading/writing to a NetworkVariable<FixedString> too early before the Network is able to fully start up?
One second, checking it out!
I have two FixedStrings, one for the player name and one for a notification system. I have not touched any of them but maybe the newer version of NetCode is more strict.
Player Name:
new("Name Unknown", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);```
Notification Text (Does not get accessed at time of error):
`public NetworkVariable<FixedString64Bytes> TextContents = new();`
When is the error? When/where in code are you reading/writing to NetworkPlayerName?
I would also update your NGO to 1.12
Okay. I am now seeing the effect of the error: the second player's player name is not being set for the host. Both names work for the host but not the client, host still gets the error. There are other effect but I believe that is only due to the fact that Unity errors and cannot continue with the rest of the setup.
I also get two deferred messages that aren't received with type OnAddPrefab
PlayerSettings script: https://paste.mod.gg/skydbbsmkybw/0
A tool for sharing your source code with the world!
1.10.0 is latest Release for me, at least in the Package Manager. I suppose you either have to get 1.12 by getting it manually or having a later Unity version that supports it?
Can add by name and then specify version number
How does that look like? :) Something like: com.unity.netcode.gameobjects:1.12?
Nevermind! Found it
Updating it!
Will report back on the effects
Updating solved my issue! So stupid... (Not bugs per-say, but when they don't indicate their root)
Updating literally solved two other issues I was having with objects not properly spawning...
Thanks a lot @tame slate, and @sharp axle!
I am also getting a lot of deferred triggers that are annoying but that'll be for another time!
Good night :)
Any way to lock an already existing session manually? I am trying to prevent more players from joining once the game has been started. Essentially so that ISession.IsLocked becomes true?
The session owner can set IsLocked to be true
it is a { get; } only though?
does not let me set it regardless its a compile error
I figured there is some sort of "update properties to make it locked" solution but google suggests that you HAVE to use the connection approval system
You gotta use session.AsHost().IsLocked = true
https://docs.unity.com/ugs/en-us/packages/com.unity.services.multiplayer/1.1/api/Unity.Services.Multiplayer.IHostSession#Unity_Services_Multiplayer_IHostSession_IsLocked
Sessions is new. Documentation is pretty barebones and there's not many forum posts or third party resources on it.
Yeah I've noticed that, it will get better with time
Any way to try-catch the SessionExceptions that get thrown? I know it is awaited so its on a different thread so the try-catch block wont work, but how can I handle these e.g. stop it from crashing if the user enters a join code that doesnt exist?
Why wouldn't a try-catch block work? That is how you would handle those exceptions.
nvm, im an idiot
hi i was following this tutorial to set up lobbies/relays to be able to launch my game, and this works fine for a build. Problem is the devices have to be on the same wifi for it work which kinda defeats the purpose haha. Im using this simple matchmaking script for it which came with the docs but not sure how to fix: https://pastebin.com/4jpLqC8v
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.
oh yea, tut: https://www.youtube.com/watch?v=fdkvm21Y0xE
Global matchmaking has never been easier with Unity's new Lobby and Relay systems. With just a few lines of code you can match players from around the world to play together. Bypass network hassles using relay and create customized games using lobby.
Lobby & Relay: https://on.unity.com/3HMloU8
Netcode git url: com.unity.netcode.gameobjects
Pr...
ye and unity cloud is registering all this too
Relay and lobbies works over the internet. But I would start using the new Sessions API if you are on Unity 6. It makes things a lot easier
is the new sessions api for testing only or allow for different wifi ? Also wdym relay and lobbies work over the internet ? Isnt that all networking ? Or did you mean they only work on the same wifi ?
Sessions can be used for production. Sessions/Lobbies/Relay all connect to an online backend service meaning they work independent of whether or not devices are on the same network.
oh so ur just confirming that there's something wrong that I did, but lobbies/relay should work on devices that are not on the same network ?
Yea. They all work across different networks
ty, do you have any solutions/direction i could go with ? I pasted the script from the docs I used with some modifications of course but im not seeing anything that specifies same wifi only or anything along those lines
the only changes were ui stuff to show players connecting
var options = new CreateLobbyOptions
{
Data = new Dictionary<string, DataObject> { { JoinCodeKey, new DataObject(DataObject.VisibilityOptions.Public, joinCode) } }
};
var lobby = await LobbyService.Instance.CreateLobbyAsync("Useless Lobby Name", maxPlayers, options);
transport.SetHostRelayData(a.RelayServer.IpV4, (ushort)a.RelayServer.Port, a.AllocationIdBytes, a.Key, a.ConnectionData);
uh nvm, guess the 5 times i retried it didnt work, but just retried again and it works lol
heyy anyone familiarized with fish-net networking?
I have an issue with SceneManager.LoadConnectionScenes. When I call it from the server to load a scene for a specific connection, the scene loads in the Server but not in the client, but when I use LoadGlobalScene it works. The scene is added in the build settings.
In server bootstrap scene:
private async void OnRemoteConnectionState(NetworkConnection conn, RemoteConnectionStateArgs args)
{
// Check if this is a new connection
if (args.ConnectionState == RemoteConnectionState.Started)
{
Debug.Log($"[ServerConnectionsManager] Client connected: {conn.ClientId}. Redirecting to lobby.");
// Create scene load data for the lobby
SceneLoadData sceneLoadData = new SceneLoadData(lobbySceneName);
sceneLoadData.Options.LocalPhysics = LocalPhysicsMode.None;
while (!conn.IsActive || !conn.IsValid)
await Task.Yield();
sceneManager.LoadConnectionScenes(conn, sceneLoadData);
}
}
Hi, does netcode have voicechat?
Vivox is the voice chat service
Is netcode for game objects good?
By most definitions of "good", yes
What are the downsides? Would you recommend a better free networking solution?
How do I setup first person multiplayer so that the player cant see their own body but other players can do I just put two models on the player one for the other players and one for the local player en do I just disable one depending on
I guess the major thing missing from NGO would be full client side prediction. Unity Physx is nondeterministic so it makes creating your own rollback netcode kinda difficult
That would be the way I would do it
So for example put arms under one gameobject and the full body under another and say trough code if IsOwner gameobject with full body .enable = false ?
thank you but there's barely any documentation for it
I would use IsLocalPlayer but yea
The docs are a bit of a mess but a lot of info is actually there
https://docs.unity.com/ugs/en-us/manual/vivox-unity/manual/Unity/Unity
Ah ok thanks. Is there a better free networking solution, or would NGO be sufficient?
depends on what you mean by "better" and what you are trying to make. But I would say that most of the currently supported network libraries are roughly equivalent
They're all viable and mostly very similar. Giving an edge to a specific solution comes down to personal preference and what your game requires.
does anyone have any good server and client code examples for player movement and interpolation etc or a scene i can import to understand how it works
If you are using NGO, the bitesize samples are good to look at
The Bitesize Samples repository provides a series of sample code as modules to use in your games and better understand Netcode for GameObjects (Netcode).
❤️
Guys if I want to use pathfinding software for multiplayer is NavMeshAgent good or will it send too much information thru Relay that it would make me bankrupt
pathfinding is usually done locally. So only the Owner should be running it. Network Transform will sync the agent positions.
and the limitations on that like if 100 zombies were alive at one time will performance drop too much?
I mean on Host like he would have to have idk like I9 12gen to run it or some other high end things
Navmesh is not really meant for 100s of agents. At that point you need to start looking at flow fields or something
do you by any chance have any recommendations?
or should I just create walk to the player in straight line
and make that if they hit a wall just climb it or break straight thru it
Yea, or just move left or right around walls
time to use my random ineffective skills to make that if collider hits anything with tag wall go left or right to whatever is closer to the player when you hit the wall if you hit another wall go to the other side
I cant think of anything else :/ xD
Flow fields are pretty rad though
https://www.youtube.com/watch?v=xV0pFUAb7wc&pp=ygUcZmxvdyBmaWVsZCBwYXRoZmluZGluZyB1bml0edIHCQl-CQGHKiGM7w%3D%3D
✅ Get my DOTS RTS Course! https://cmonkey.co/dotscourse
💬 Learn how to get MASSIVE PERFORMANCE to build any game you can imagine!
Write code that runs 260x FASTER!
✅ Get my C# Complete Course! https://cmonkey.co/csharpcourse
🌍 Game Dev Report Newsletter - https://cmonkey.co/gamedevreportnewsletter
🎮 Play my Steam game! https://cmon...
I mean if I want to make that the zombies would follow the closest player to them like individualy I feel like this would be bad
You would need a flow field for each player, yea.
I feel like for this I would need 200h course just to understand how would you make it for each player differently AND how to optimize it to not crash older pcs
Its not terribly complicated but you would need to use jobs if you are tracking the player and not like mouse clicks in an rts.
I am going to stick with zombies running straight into walls and then just around them like in 7dtd
feels easier ngl
When developing server authority, for players which have network transform component added do i set authority mode to Owner?
But then i just actually validate it server side so if movements are too big i would just reset their position
Since i think there are 2 modes Owner and Server but with Server only the server can allow movement which lags alot
That is the trade off with server authority. Now you can use client anticipation if you want to mitigate that lag and maintain server authority
Client anticipation is only relevant for games using a client-server topology.
Thanks ❤️
but just to make sure setting it as Owner would be alright? although id just have to have extensive checks for invalid movements?
Setting it as Owner makes it client authoritative. No amount of server checks will fix that
Ah ok ive misunderstood then so doing that is a huge security flaw?
It gives the client full control, yea.
alright thx ❤️
How do i check if the socket is valid. I am trying to create the logic for when users to try connect with a client while the server is off. (Endpoint is invalid)
should i just ignore the exception from the unity job?
updateHandle.Complete();```
its throwing the error on driver update, but i check if the driver is created and the connection before i update it and itll just return ```NetworkConnection.State.Connecting```
You would put the connection attempt in a try catch block to handle the exception
This doesn't work because unity's NetworkDriver is using a job
should i use kinematics for vehicles if im networking them as opposed to using rigidbodies and doing some client side prediction and server reconciliation
i think if you regenerate project files in preferences and reopen it that will fix it
thanks
Is it possible to connect to unity transport UDP using a python client?
Im using Unity NGO with the Multiplayer widgets, but it is so tedious to always have to create a session, then enter the session code in the second editor window every time I start and test the game. Is there a simpler way to automate joining the same session?
No, unity transport can only connect to itself
Use the Quickjoin widget
Rust servers use app id 480?
Server: Rust.GG Server PVP
Address: 191.114.67.166
AppID: 480
GameDir: rust
Map: mapbymysticgamerpro
Tags: mp20,cp3,ptrak,qp0,v2275,h82c1c1bc,stok,born1742662653,gmrust,oxide,modded```
If that's steam it should not be. 480 is the test app SpaceWar
yea, thats what im using for my server browser
however whats weird
is im using facepunch steamworks since its got actually decent methods
but facepunch also develops rust
public void RefreshServerList()
{
if (isRefreshing) return;
isRefreshing = true;
if (loadingIndicator) loadingIndicator.SetActive(true);
if (refreshButton) refreshButton.interactable = false;
SetStatus("Refreshing server list...");
foreach (Transform child in serverListContent) Destroy(child.gameObject);
availableServers.Clear();
selectedServer = default;
connectButton.interactable = false;
CleanupSteamRequest();
try {
serverListRequest = new Steamworks.ServerList.Internet();
serverListRequest.AddFilter("appid", "480");
Debug.Log("Filtering for Spacewar (AppID 480) servers");
serverListRequest.AddFilter("and", "1");
serverListRequest.AddFilter("gametagsand", "mygame_v1");
if (!string.IsNullOrEmpty(gameVersionFilter)) {
serverListRequest.AddFilter("and", "1");
serverListRequest.AddFilter("gamever", gameVersionFilter);
}
if (showOnlySecureServers) {
serverListRequest.AddFilter("and", "1");
serverListRequest.AddFilter("secure", "1");
}
Debug.Log("Applied server filters: appid=480 AND gametagsand=mygame_v1");
serverListRequest.OnChanges += OnServersUpdated;
serverListRequest.RunQueryAsync(searchTimeoutSeconds);
StartCoroutine(RefreshTimeoutCheck());
}
catch (Exception ex) {
Debug.LogError($"Steam query error: {ex.Message}");
SetStatus("Error refreshing server list");
CleanupAfterRefresh();
}
whats even weirder if i look them up
hey everyone, im looking to dive into a different type of multiplayer game, ive done smaller 4-8 player ones before but wanted to do a larger shooter. i was thinking of doing max 64 or 32 players per game. ive done only netcode for gameobjects in the past but wanted to try either fishnet or netcode for entities. any suggestions on which i should go with?
Likely someone's pirate server using the default app id
I would only use N4E if you are already familiar with DOTS and are already planning on using it in your game.
ah
oh i figured the issue. i was retrieving all the servers then filtering them client side instead of sending the filter in the request to steam server
wrong type of networking. check out !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
Am I getting this right that ghostcomponent syncs only the existence of the component on a ghost?
anyone have any ideas on why this might be happening? I have given my characters ragdoll bodies that can be activated and they will flop around, as always works well on the local client but the rigidbody freezes dont work for other players, and their ragdoll bodies become decentered
the green circles being their centers, you can see the player on the left (the remote player) is not connected to it, even though i froze the x and z positions on the rigidbody
Im assuming the network transform effects the rigidbodies in some way that prevents them from freezing on the players centre
maybe the freeze constraints arent reliable enough, not sure
okay nvm gang, i used configurable constraing with locks and its okay
is it feasible to sync wheel colliders and such with client prediction and reconciliation
[GhostComponent] doesnt actually sync anything by itself. Its only used to specify where its [Ghostfields] will be synced to
Not sure I understand
What do you mean by specifies where they will be synced to
If the ghostcomponent attribute does not sync anything then what is the difference between using it and not and just using ghostfield
when connecting to steam server you are hosting on your own pc should you use localhost? when i try to use ip i recieve socket errors
There is no difference. You don't need GhostComponent at all. You can just use GhostFields. GhostComponent is use to specify id snapshots will be sent to the owner or only interpolated prefabs or if child entities will be synced
https://docs.unity3d.com/Packages/com.unity.netcode@1.5/manual/ghost-snapshots.html
Steamworks doesn't use IPs at all. You can set the network manager listen address to 0.0.0.0
what do people use for dedicated server?
wdym
oh im still using unity netcode for the conection thats why
are most people using multiplay hosting or an alternative?
alternative i believe but it depends on your game
I use Multiplay when i need a dedicated server. Don't know about most people, but Azure, AWS, and Google cloud are all viable options
im making a crab game copy basically
really just comes down to price
and multiplay is good for price or bad?
depends on your usage, how many servers you end up running per month. Last time I checked Multiplay was slightly more expensive. But you'll need to run your own numbers
Another thing to note is that Multiplay is using Google Cloud Servers
This tool makes multiplayer games ridiculously easy to make
https://www.youtube.com/watch?v=kzDnA_EVhTU
SpacetimeDB is an all-in-one backend server and database designed for building and running multiplayer games and apps with incredible speed.
Give us a star! https://github.com/clockworklabs/SpacetimeDB
Join our Discord! https://discord.gg/spacetimedb
My Twitter: https://x.com/TylerFCloutier
My BlueSky: https://bsky.app/...
hey there,
I accidently closed the multiplayer play mode Player2 window. how do I reopen it?
leaving and entering playmode does not fix it
also restarting the Unity engine and re-activating the player2 on the menu doesn't do anything
it's just a db but for games right?
a readme window of player2 opens. every player has the default readme that I made long ago just open when I start the editor.
Not too sure about that. Executing db modules is not something new - and I personally would never use that thing, since its extreme vendor locking. I am writing an open world mmo and the server part is not as difficult as they make it look like. And the real networking challenges are not even addressed. Like client side prediction, state reconciliation and what not. Also as far as I see its scaling depending on the overall load but sharding based on in game location seems to not be doable with this solution. So I do not see why it would be useful for a scope like an mmo - but hey maybe im wrong 😄
any idea how they made it so?
You'll need to reverse engineer the udp protocol they are using. You can check out the Unity Transport source code in the package.
It would probably easier to use a regular c# TCPClient to connect to you custom server
is facepunch steamworks compatible with the normal steam transport or do i need to use facepunch transport
If using NGO, you would need to use the Facepunch Transport
anyone experienced an issue where a "ghost" player spawns in? I decided to not use the default spawning of the player and manually instantiating them instead, and even though I have tracked player's in a dictionary, and there's only 2 players in this dictionary, the client spawns in an extra player: https://pastebin.com/d6rapVkS
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.
found issue, simple server check worked uwu
hi, so i have this class with a generic parameter for data that could be sent: ```cs
/// <summary>
/// A generic form of <seealso cref="ItemAction"/>.
/// </summary>
/// <typeparam name="T">The type of data sent in <seealso cref="InvokeRpc(T, RpcParams)"/>.</typeparam>
[GenerateSerializationForGenericParameter(0)]
internal abstract class SerializableItemAction<T> : ItemAction
where T : INetworkSerializable
{
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="data">A network serializable object.</param>
[InheritedRpc(SendTo.Everyone)]
protected abstract void DoActionRpc(T data);
/// <summary>
/// Sends a message to the server to perform the action.
/// </summary>
/// <param name="data">The data to send.</param>
[Rpc(SendTo.Server)]
protected void InvokeRpc(T data, RpcParams rpcParams = default)
{
if (IsAllowed(rpcParams.Receive.SenderClientId))
{
DoActionRpc(data);
}
}
}```
however, even though i have the attribute, my type is not being serialized
/// <summary>
/// A generic form of <seealso cref="ItemAction"/>.
/// </summary>
/// <typeparam name="T">The type of data sent in <seealso cref="InvokeRpc(T, RpcParams)"/>.</typeparam>
[GenerateSerializationForGenericParameter(0)]
internal abstract class SerializableItemAction<T> : ItemAction
where T : INetworkSerializable
{
/// <summary>
/// Invokes the action.
/// </summary>
/// <param name="data">A network serializable object.</param>
[InheritedRpc(SendTo.Everyone)]
protected abstract void DoActionRpc(T data);
/// <summary>
/// Sends a message to the server to perform the action.
/// </summary>
/// <param name="data">The data to send.</param>
[Rpc(SendTo.Server)]
protected void InvokeRpc(T data, RpcParams rpcParams = default)
{
if (IsAllowed(rpcParams.Receive.SenderClientId))
{
DoActionRpc(data);
}
}
}``` this is the implementation
i know theres an easy workaround but i dont really want to do a workaround
ii will if i have to but if anyone has a better solution than [GenerateSerializationForType] that would be great
Hi everyone.
I have a problem where when I am switching scenes in my Multiplayer project using NGO, it is telling me that destroying Network objects can only be done on non-host client is not valid.
[Netcode] [Invalid Destroy][PowerUpPrefab Variant(Clone)][NetworkObjectId:9] Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead
While I assume that this happens because loading a new scene automatically unloads all network objects on the server, I have made sure that there are no scripts that allows the client to destroy the object. I have also tried to manually despawn the object before switching scenes(I have confirmed that the gameobject is gone in the inspector when the scene changes). Yet, the error still haunts me.
Does anyone have any clue what to do in a situation like this?
Make sure that only the host is calling NetworkManager.SceneManager.LoadScene()
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/using-networkscenemanager/
Netcode for GameObjects Integrated Scene Management
Right now, I am using this code for switching scenes:
{
if (NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer)
{
StartCoroutine(ReturnToCharacterSelectSequence());
}
});```
Would this normally not be enough?
(The NetworkManager.SceneManager.LoadScene() is within the coroutine)
Yea, that should work. Clients shouldn't be getting that Invalid Destroy error in that situation
Wellp, I suppose I am stuck then😢
Thank you for your reply anyway!
You'll need to find out where the clients switching scenes on their own
That makes sense, thank you! I will scour the scripts and see where the culprit is!
Lobby management with additional data
for me theres only one question left for NGO now
one of my senior friend warned me, if i ever need to have a multiplayer project, i will need an actual server/database? to store user account data
can NGO alone do that?
No. Unity's solution for this is Cloud Save
and its expected to be used with NGO right? maybe like NGO for gameplay and once its done the data saved to clouds using cloud save?
Yeah. That'll work. It's meant to work with other Unity Services/Packages as it uses a Unity Authentication ID to tie a player to their data.
ty 👍
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Is anyone here using multiplayer play mode? I'm having trouble getting the secondary players to identify themselves as clients on launch
You'll need to check CurrentPlayer.ReadOnlyTags()
https://docs-multiplayer.unity3d.com/mppm/current/player-tags/target-instance/#set-a-tag-to-server-client-or-host-in-a-script
This example shows how you can use Netcode for GameObjects to run a Player as a server, client, or host in Multiplayer Play Mode.
Has anyone ever had this? My MPPM has broken.
I've:
Confirmed URP asset was correctly assigned in Graphics and Quality settings.
Created a new URP Render Pipeline Asset and assigned it.
Confirmed no custom render pipeline or RenderPipelineAsset.CreatePipeline() duplication.
Disabled all custom editor scripts.
Verified no duplicate Blitter.Initialize() calls in code.
Made sure Multiplayer Services and Netcode packages were installed correctly.
Fully deleted Library/, Obj/, and Temp/ folders.
Reimported all packages via the Package Manager.
Ensured URP debug textures like DebugFont.tga and ProbeVolumeNumbersDisplayTex.png existed in the PackageCache and weren’t deleted or missing.
Tested in a blank project - no errors appeared once MPPM was installed.
Uninstalled MPPM from the Package Manager and reinstalled.
Deleted all cache from: AppData\Local\Unity\cache & AppData\Local\Unity\upm.
I cannot for the life of me track down the cause.
The levels in my game are prefabs, some of which contain NetworkObjects like moving platforms and such. This is the spawn logic that I am using but it is incorrect and does not spawn the NetworkObjects for the client. Everything works great for the host/server, but the client receives deferred AddPrefab and Spawn-messages despite of the fact that the prefabs trying to be spawned are in the NetworkManager's prefab list. The level parent is not a NetworkObject since that prevents spawning the other NetworkObjects. Any suggestions helpful!
Spawn Logic:
[Rpc(SendTo.ClientsAndHost)]
private void InstantiateLevelClientRpc(int levelIndex)
{
GameObject randomLevel = levelPrefabs[levelIndex];
randomLevel = Instantiate(randomLevel);
ComponentManager.CurrentLevel = randomLevel;
levelSettings = GameObject.FindGameObjectWithTag("Level Settings").GetComponent<LevelSettings>();
if (IsServer)
{
foreach (NetworkObject levelObject in randomLevel.GetComponentsInChildren<NetworkObject>())
levelObject.Spawn();
}
else
{
foreach (NetworkObject levelObject in randomLevel.GetComponentsInChildren<NetworkObject>())
if (levelObject.IsSpawned == false) Destroy(levelObject.gameObject);
}
}
Warnings:
That's great thank you
What version of Unity and MPPM are you using? Usually deleting Library and reimport will reset everything
You'll need to make that RPCs are only getting called after OnNetworkSpawn(). Also Clients should not be Destroying network objects.
The OnNetworkSpawn is on the objects being spawned by the RPC. I was thinking that not destroying the not-yet spawned objects would create duplicates but I understand why not. I think I need a better way of instantiating the level. Do you have any tips? Could switch to scenes making it easier but will have to add a bunch of donotdestorys
You'll need a Level Manager in scene network object that is responsible for spawning the levels. That manager can have the RPC that gets called in OnNetworkSpawn
Yes, that is what I have.
Do you have Levels already in the scene? Those deferred messages are usually when RPCs are getting called before the object has spawned
public NetworkObject Spawn(GameObject obj, Entity owner) {
GameObject newPrefab = Instantiate(obj);
NetworkObject networkObject = newPrefab.GetComponent<NetworkObject>();
newPrefab.GetComponent<Owner>().owner.Value = owner;
return networkObject;
}
public void Spawned(Entity entity) {
Skills skills = entity.GetComponent<Skills>();
if (entity.IsServer && skills) {
foreach (GameObject skill in skills.skills) {
if (skill == null) {
continue;
}
NetworkObject spawnedSkill = EntityManager.Instance.Spawn(skill, entity);
spawnedSkill.Spawn(true);
}
}
}
i dont get it why duplicate Jump object in client?
skills list is here
Im calling Spawned method when spawn Player object, and Player object have Skills Component
When a new round starts, the server calls the RPC to spawn a new level that will be played ~10 seconds later after an intermission/other stuff.
Does the Level prefab have other network objects in it? Nested network objects are not supported.
You need to make sure that only the server/host is Instantiating and calling Spawn() on network objects.
The level parent is not a network object, that is why I am instantiating it for both. There are network objects and they are the problem. I want to instantiate the static objects and also spawn the network objects.
I checked IsServer property in code
if (entity.IsServer && skills) {
foreach (GameObject skill in skills.skills) {
if (skill == null) {
continue;
}
NetworkObject spawnedSkill = EntityManager.Instance.Spawn(skill, entity);
spawnedSkill.Spawn(true);
}
}
this code
You have network objects in the prefab?
Yes, like moving platforms
That is not going to work
You'll need to switch to scenes and load it additively
You've got skills being instantiated somewhere else then
No, the Instantiate method exists only in that function. (translate)
and that method called by only Spawned method
Is this getting called before OnNetworkSpawn()?
Calling directly from the OnNetworkSpawn method
See if entity.IsServeris returning true on the client. You might need to use NetworkManager.Singleton.IsServer instead
same error
Debug.Log it out to see if its returning the correct value
client, server, code
Oh so its not just duplicating on the client. the server is spawning it twice
Oh nono take a look HoldThrow object
that object count in server is one
i just put in skills list Jump, HoldThrow, Jump values
weird. I have no idea why the client is instantiating them twice. Usually that only happens when the client doesn't have proper server checks.
The latest on both 😭
Is it possible to import everything into a new project without having to reconnect everything in inspector? Thinking it's my last hope if I can't fix it
You can export your scenes and assets as a package
Can always fall back to ParrelSync https://github.com/VeriorPies/ParrelSync
How should a multiplayer inventory system be structued? client authoritive server authoritive etc? like to prevent any cheats stuff like that
To prevent cheats it has to be server authoritative. Or at the very least cloud based with Cloud Code/Save/Economy
so server rpcs
client is graphical changes only
It doesn't have to go all the way in that direction. But it depends on the game. It could be that only the inventory is save to the server/cloud
kk 👍
Heyo, anyone know if there there an event I could sub to which gets fired after all manually spawned network objects get synced with newly joined client? Distributed authority, auto scene management off. There exists OnNetworkSessionSynchronized callback, however it seems to behave oddly and not as described in docs (called once only on session owner), I'm assuming this is due to auto scene management being off. Sadly I must use manual scene management due to converting an old SP game to MP which uses additive scene loading...
Speaking of which, I've tested NetworkSceneManager and tried to make it work with my additive scene flow - its very inconsistent or is it just me? The arguments received in OnSceneEvent are unreliable, in some cases SceneName is a path, in some its just a name, in some its blank. The Scene arg seems to be very inconsistent as well, most of the time its just invalid (null scene)...
OnNetworkPostSpawn() should work for you.
Scene Events will only work correctly when Scene Management is enabled. The different events all have different parameters
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events/#sceneevent-properties
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
OnNetworkPostSpawn() should work for you.
I don't think this fits my use-case, I need an event when the whole game state (spawned objects) get spawned on the client, rather than just one NetworkObject and its hierarchy.
According to the docs (in the source code, could not find anything on this in Multiplayer Docs) OnNetworkPostSpawn is scoped to one object only:
/// <summary>
/// Gets called after the <see cref="NetworkObject"/> is spawned. All NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked.
/// </summary>
/// <remarks>
/// Will be invoked on each <see cref="NetworkBehaviour"/> associated with the <see cref="NetworkObject"/> being spawned.
/// All associated <see cref="NetworkBehaviour"/> components will have had <see cref="OnNetworkSpawn"/> invoked on the spawned <see cref="NetworkObject"/>.
/// </remarks>
protected virtual void OnNetworkPostSpawn() { }
Scene Events will only work correctly when Scene Management is enabled. The different events all have different parameters
Mhm I'm aware of that, however when I pass in a fullscene.pathto load a scene viaNetworkSceneManager, in the events I no longer receive a scene path (Scenes/Foo/Bar_01.unity) but rather a scene name (Bar_01). Sometimes theSceneNamedoes contain a path
Regarding OnNetworkSessionSynchronized, am I correct to think that it only works with scene management on? I'm a bit confused reading the docs on this part. It does fire on my end, but only on the object owned by the player. In my case I spawn "manager" objects to handle state sync, and since the owner is the session owner, this is not very useful for me - I need this callback on the clients
looks like OnNetworkSessionSynchronized is similar to OnNetworkPostSpawn in that its called on each NetworkBehavior. It doesnt seem to be related to scene management
The SceneName not being consistent sounds like a bug
Mhm, it does look like a bug 🤔 Did a quick scuffed test on this. I guess its workaroundable...
Debug.Log($"Starting to load scenePath={scenePath}");
sceneManager.LoadScene(scenePath, LoadSceneMode.Additive);
private void OnSceneEvent(SceneEvent sceneEvent)
{
var sceneName = sceneEvent.SceneName;
var eventType = sceneEvent.SceneEventType;
var scene = sceneEvent.Scene;
Debug.Log($"{eventType}: sceneName={sceneName}, scene.name={scene.name}, scene.path={scene.path}");
}
Starting to load scenePath=Assets/Scenes/GameScene_02.unity
Load: sceneName=Assets/Scenes/GameScene_02.unity, scene.name=, scene.path=
LoadComplete: sceneName=GameScene_02, scene.name=GameScene_02, scene.path=Assets/Scenes/GameScene_02.unity
LoadEventCompleted: sceneName=GameScene_02, scene.name=, scene.path=
Still curious on OnNetworkSessionSynchronized, has anyone else tried using this and could pitch in on how this should be used and when its actually called?
I'm looking at the source right now, it looks like OnNetworkSessionSynchronized should be called after ALL spawned objects get synced. Why its not called for non-owners tho 🤔 Can this be relied on in distributed authority at all or is this unrelated?
Created a bug for the scene name issue: https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/3418
I didn't realize you are using DA. That does change things a bit. Clients are responsible for spawning their own objects. OnInSceneObjectsSpawned might work for the non authority objects
Haven't fiddled with this one, will take a look
Currently checking if I can get away with using in-scene-placed objects, as I always keep the same scene open during networking and don't switch, previously I'd just spawn everything on network start using my own networked spawn manager. But now I'm just getting:
NetworkPrefab could not be found. Is the prefab registered with NetworkManager?
...even though the prefab is defo registered in my NetworkPrefabList and the docs state that even with automatic scene sync off it should work, ughhhhh
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
Whats the best free or cheap solution for an RPG using self-hosted dedicated servers with chunked zones (each zone as a separate server)? I’m currently looking at Mirror or Fish-Networking in Unity. For handling user registration, login, email verification, and password reset, I’m considering PlayFab or Firebase since I want to avoid building a custom backend. Are there any better alternatives or solutions for both dedicated server networking and user management?
Showing my work
That type of server meshing usually requires custom server backend. I don't know of any services that support it out of the box
can you not call rpc methods on networkbehaviours from a monobehaviour script? i swear you used to be able to
Has to be a NetworkBehaviour. Pretty sure this has always been the case.
huh interesting
i wonder how this works for a larger call stack
like, does ith ave to be networkbehaviours all the way through?
or can i go
mono -> network -> network (rpc)
or network -> mono -> network (rpc)
Just the actual RPC has to be defined within a NetworkBehaviour. It can be called from anywhere.
oh yeah thats what i was asking about
because recently i was trying to call an rpc on a networkbehaviour from a tester component and it wasnt going through, but changing the tester component to networkbehaviour as well fixed it
im not sure what was going on there then
i just tested it in isolation and it did work so weird
Yea, you just have to make sure that the networkobject you're referencing is active and spawned
When dealing with in scene placed network objects, is there a way to apply or hide the object id hash changes if the in scene placed object is a prefab? Apply All doesn't seem to do anything in this case.
Context: I have some large-ish prefabs which have sub-objects beneath them, I made those sub-objects networked, but if I drag in the parent prefab with networked sub-objects into a scene, Unity shows changes. Its a bit annoying having to deal with this as it makes me think that a level designer has forgot to apply changes to a prefab. We have a lot of such prefabs in our game as it makes it easier to deal with conflicts in Git.
Currently just testing things and checking if I could go with in scene network objects 😅
Multiple plugins with the same name 'steam_api64' (found at 'Assets/Scripts/SteamworksFacepunch/redistributable_bin/win64/steam_api64.dll' and 'Packages/com.community.netcode.transport.facepunch/Runtime/Facepunch/redistributable_bin/win64/steam_api64.dll'). That means one or more plugins are set to be compatible with Editor. Only one plugin at the time can be used by Editor.
i installed facepunch transport and facepunchsteamworks
why do i get this error? are they incompatible or how should i install both
You just need to remove one of the duplicate dlls.
Ah
Hello everyone, I’ll try to keep it brief.
I’m currently working on a year-end project at my school and I’m using the MultiplayerService for sessions. The problem is that the school’s internet connection is quite slow, so I can’t create sessions and I keep getting timed out (knowing that it works fine at home or using 4G).
I wanted to know if anyone here had any workaround solutions that could help me out? (aside from being on 4G all the time).
Thanks a lot!
It doesn't look so bad at first glance, but the problem doesn't occur all the time, and in the evening when there are fewer people, it works without too much trouble
My theory is that the client is trying to join the session when it hasn't been created
Since the function is in async
I don't have a lot of knowledge on the subject, so I don't have an overview, if someone can tell me the potential causes of this issues
Some code
Network bandwidth will not be an issue connecting. You are connecting to localhost. Other PCs will not be able to connect. Using Relay to connect will be best for testing. I would suggest using QuickJoin https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session#find-a-session-with-quick-join-using-unity-lobby-service
When i switch in relay connect i have this error (and I prefer to just create my session)
This error is not from creating the session. Looks like a typo in the session join code. Its way easier to use CreateOrJoinSessionAsync
After somes issues with the AuthenticationService player id, i do the CreateOrJoinSessionAsync and ... i had the same problem
Is this error on joining client? The host shouldn't be trying to use a join code?
This error come when i tried to create a new session, the host tried to use a join code but is wrong/expired
The fact is that I receive all the replies
I suppose the school network could be blocking ports. But I don't know why the host is trying to use a join code when creating a session
because when host create a session, host need to join this session
The host does not need to join the session it just created.
Still messing about with automatic scene management and encountered an odd issue - my client player doesn't spawn on host in Distributed Authority + Multiplayer Play Mode! This happens if I manually spawn it (even with a 5s delay) or choose to spawn it automatically via player prefab.
Been stuck on this the whole day and can't debug whats going on. I also have a separate project setup with the exact same configuration and it spawns players just fine. If I disable auto scene sync - player spawns correclty q.q
The only thing I noticed in logs was this line getting logged on the session owner, apart from that no errors... In scene placed objects seem to spawn just fine also
[Netcode] [Deferred OnSpawn] Messages were received for a trigger of type NetworkTransformMessage associated with id (20001), but the NetworkObject was not received within the timeout period 10 second(s).
The 20001 is the player network object id that should spawn. Anyone have any pointers as to why this could be happening?
If the same code is working in a fresh project, then the scene might be taking too long to load and is timing out
The scene seems to load quickly (I get sync message in under a second after connecting). Hence why I added a player spawn delay to check if its related to this...
All you can really do at this point is start moving pieces over to the working project and see where it starts breaking
Hmm, its not just the player it turns out, any dynamically spawned object does not get replicated, only if auto scene management is on, what - this doesn't make any sense
is client server prediction and reconciliation only for movement or what else would i need to apply it to? for example gun gameplay, resource gathering, inventory shit etc
Any player input. or anything you don't want to see delayed by ping
For any poor souls having the same issue - DON'T USE UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode
In my case I use custom editor tooling to load scenes not added to build settings so its easier to test prototypes. LoadSceneAsyncInPlayMode allows to load such scenes in Editor. Guess I'm not using that anymore >.>
Will report a bug still, seems like a valid use-case to me, or at least could have some warnings
Wonder if anyone can help, below is two videos, from either perspective of my two players on the boat. Boat players individually have great and smooth movement. But from each players perspective the other player can be at the wrong position. Boat is a network transform, and players are client network transforms, using NGO. What’s the solution here?
Hey folks, I got some feedback on my MMO project regarding movement and sync issues.
Someone pointed out that the player character looks like it’s sliding, with no proper foot connection to the ground, and that NPCs seem to be ticking or snapping strangely. They mentioned it looks like a networking issue, possibly missing interpolation.
There is any tool that comes with Unity that can help me to solve this? I wrote a NetworkManager, and with that I proliferate events to the subscribers.
when using steamworks steam id and other steam data cannot be spoofed right? or do i need to handle that or does the steam c# wrapper handle that
Your game's steam id is public. You can verify game ownership through steamworks
👍 so every now and then i just add dlc ownership or game ownership checks?
probably enough to check when the game starts.
for some reason if i trigger an explosion on the client it only shows it on the server/host, and the output says i'm trying to instantiate a network object from the client, even though i have the function flagged as a serverRPC on clients
So I am considering a change in strategy
how would one make it so that a phone app can trigger events in the game via LAN connection?
The RPC has to be on a Network Object too otherwise it gets called just like a regular function
does it need to be parented?
Network object can only be parented after they've been spawned
The easy way is to make the phone app a game client that connects to the game server on the PC
Thats what I've BEEN DOING
But the problem is I have no viable means to connect the two things
If you don't want to enter the IP then you'll either need to use the Relay service or use NetworkDiscovery
one sec
okay relay doesnt seem that hard
I cannot use this principle with Unreal, can I?
the weird thing to me is that i have a very similar explosion effect for the bullets after hitting something and it works fine
I don't see why not. Epic Online Services has a relay service too
As long as its only spawned by the server, then it should be fine
alright
So I need to actually make the base game, the product, a thing on the relay cloud before I even have a dream of- okay
... I think i have adumber idea, but thanks for putting me in the right direction
this is the explosion part of the script
public void ExplodeClient()
{//yoinked most of this from the bullet explosion script
print("exploding on client");
Debounce = true;
GameObject ExplosionClone = Instantiate(ExplosionEffect, transform.position, transform.rotation);
ExplosionClone.GetComponent<NetworkObject>().Spawn(true);
ParticleSystem ExplosionCloneParticle = ExplosionClone.GetComponent<ParticleSystem>();
//AudioSource ExplosionSound = ExplosionClone.GetComponent<AudioSource>();
ExplosionCloneParticle.Emit(1);
//ExplosionSound.Play();
rb.isKinematic = true;
rb.velocity = Vector2.zero;
gameObject.GetComponent<SpriteRenderer>().enabled = false;
AllowedToPlay = false;
Respawn();
}
this is the serverRpc version
[ServerRpc]
public void ExplosionServerRpc()
{
ExplodeClient();
}
and this is when it gets called
void Keys()
{
if (Input.GetKey(KeyCode.LeftShift))
{
shipspeed = afterburnerspeed;
}
else
{
shipspeed = defaultshipspeed;
}
if (Input.GetKeyDown(KeyCode.K))
{
if (Debounce == false)
{
Explode();
}
}
}
public void Explode()
{
if (OwnerClientId != 0)
{
print("client");
ExplosionServerRpc();
}
else
{
print("server");
ExplodeClient();
}
}
you need a clientrpc involved in this
[ServerRpc]
public void ExplosionServerRpc()
{
ExplodeClient();
}
this will just call the client that's the server
where as a ClientRpc would be sent to each client
so i need a explodeclientrpc
Yeah usually NGO related code will involve a kinda "paired" client and server rpc
do i need a seperate explode and explodeclientrpc for the serverrpc or can i just call it as a server rpc
like [ServerRpc}
public void ExplosionServerRpc()
{
ExplosionClientRpc();
}
iirc server has to call clientrpcs for them to work so yeah. It depends on what your doing but in general there's two kinda ways you can compose your code when doing these "paired" rpcs
option 1
[ServerRpc]
MyFunctionServerRpc()
MyFunctionClientRpc()
[ClientRpc]
MyFunctionClientRpc()
//Logic for both host/server and non-host/server clients is handled all here in the same function
option 2
option 1
[ServerRpc]
MyFunctionServerRpc()
//host/server specific client logic is handled in this function specifically. seperates your logic abit but can be prefered/required in situations where you need to do server/host specific stuff maybe (eg. maybe validating if you should even pass on this request)
MyFunctionClientRpc()
[ClientRpc]
MyFunctionClientRpc()
//Logic for only the non-host/server clients because the host/server client has already been handled
It would be a lot easier to use [RPC(SendTo.Everone)] instead of multiple RPCs
is that in unity 2022
alternative you could have the server .Spawn() the network object explosion
so use .Spawn instead of instantiate?
You need to Instantiate and Spawn on the server
i already do that
GameObject ExplosionClone = Instantiate(ExplosionEffect, transform.position, transform.rotation);
ExplosionClone.GetComponent<NetworkObject>().Spawn(true);
Yes. but you are only enabling the particle system on the server.
either an RPC or use OnNetworkSpawn() on the object
can't i just change the function to a clientRPC and everything will instantiate
Yea. you can use [RPC(SendTo.Everone)] but you'll need to remove the Spawn() since that only works on the server
Mirror vs photon vs netcode for a game like ark or rust?
All of them would work fine
or would photon fusion be better considering thousands of entities & large scale map
coding wise they are all very similar. I'm not sure if Photon still requires you to use Photon Cloud or not.
i half fixed it
clients can explode but if the host explodes the client wont see it
ah ok but performance wise are they all very similar or is netcode for gameobjects or netcode for game entities best etc
Entities will get you better performance by default but you have to make the rest of your game with DOTS which might or might not be worth it.
i was planning on making multiple systems like the Animals, structure etc systems with dots but does it require me to only use dots for my entire game?
Not the entire game. DOTS animations doesn't exist yet. Audio and UI as well. But if you are already using ECS then stick with Netcode for Entities. Its a huge learning curve though
ohh
so i have core monobehaviour things
like initializing the server
handling player connections etc
then i use NCE for handling huge amounts of structures
huge amounts of entities
calculating everything etc?
No, you can't mix the 2 Netcodes. You can use NGO and have DOTs run the server simulation but you'll have convert your data back to monobehaviors to have it sync with the clients.
kk
Does anyone know where I can find which package versions of the Lobby, Matchmaker, Relay, QOS, and Multiplay were used to combine into the single SDK called Multiplayer services.
Looking for the package versions at the time of when Unity combined them so I can see if there is any API I need to update that replaces former functions.
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/migration-path There are only a couple functions to worry about
Only Relay changed(reverted basically). I don't think any of the other services updated since the merge
Thank you these document sub sections are exactly what I was looking for.
I saw the change where instead of the constructor for RelayServerData to AllocationUtils.ToRelayServerData.
And the Relay.Instance to RelayService.Instance, but not sure yet about and of the other reverted changes.
Thank you for mentioning some things being reverted will look into it
So I have the relay thing all good to go
I just have ONE problem
two actually
How do I make it so that the second player that joins the game is not... A player prefab
why wouldn't they be a player prefab?
Spawn the player objects manually, you can pass in whatever object you want
Although it’s rare you’d need to do this/would want to do this
Generally better to use the same prefab with the same scripts on it and just make visual changes if needed
I'm making a companion app dependent game
So I'm logging in through one device, but the main game is on something else
And then I want player 2 to control the environment and player 1's game (like swapping between first and third person)
That's why they wouldn't be a player prefab
You would need to remove the player prefab from the network manager so it doesn't spawn a prefab at all for either player
Hello someone can say me what i'm suposed do in boostrap to setup the multiservice session ?
I can create a session, but i can't join it, i don't know how i can set up the ConnectPort so per default is 0
If a god soul can help me
ok so is there a way for me to change the collision group of the player ONLY on the client?
basically whenever i spawn bullets it kills the player
so im tryna find a way to make the bullets hit other players but pass thru the player who shot it
Do you mean Netcode for Entities bootstrapper?
I don't think you can do this outside of Distributed Authority.
The general solutions would be spawn the bullets farther away, make the player/bullet colliders into Triggers, or have the local players instantiate fake bullets with no colliders while the server handles all the bullet physics
fake bullets might work
im worried about desync tho
like if one bullet spawns on a different frame
screwing with trajectories
Yeah
i have this bootstrap
i take it from documentation unity
Yea. Once the worlds are created then you need to send the GoInGame request
https://docs.unity3d.com/Packages/com.unity.netcode@1.5/manual/networked-cube.html#communicate-with-the-server
The server would still spawn the real bullet. You could use it to sync up the fake bullet
how would i spawn the fake bullet only on the client
and then a real bullet only on the server
just instantiate is as a normal game object
and send a ShootRPC to the server to spawn the networked bullet
the problem is when I create a session by connecting directly (by setting up AutoConnectPort and DefaultConnectAddress) when I create a session and join it my rpc from the server are sent to all clients even those not in the session, is this normal?
You shouldn't be sending the RPC from the server. Only the clients
Are you using the Session SDK? Its a bit different with that
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/create-session#advanced-usage:-specifying-a-custom-network-handler
Yes i use that
You'll want to make sure that the GoInGameClientSystem has only WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation) so the server world doesn't send it
Yeah i do
why (i don't talk about goInGame rpc) ?
Please help, i cannot figure out why its not working
[Command]
private void CmdSplatter(Vector3 point, Vector3 normal)
{
GameObject splatted = Instantiate(splatter, point+(normal*0.01f), Quaternion.Euler(normal));
NetworkServer.Spawn(splatted);
NetworkServer.Destroy(gameObject);
}
I guess I'm not sure which RPC you are talking about here. All RPCs from the server will get broadcast to all connected clients.
Session are not supposed "create" a server world for all players of session ? or i'm wrong ?
Precisely to limit the number of rpc in the same session, and to be able to have several games on the same server easily.
No, only the Host/Dedicated Server will have a server world
whats thaT
I'm a bit stuck. I'm trying to set up a server that contains several additive scenes. The players should be able to switch back and forth between the scenes like in an mmo. I am currently trying it with Unity netcode for gameobjects. It works partially. The client should only see the scene it is in. I have the feeling that NGO is not the right thing for this. Am I wrong?
Yea. That's not how NGO works. Or MMOS for that matter. NGO is not built for MMOS and will require a ton of custom server code for it work.
How can I get the public IP of the player's computer? (I need to bind it to a server name so the client can connect with mirror across networks)
Is there any way to attach a debugger to additional editor instance when working on multiplayer game using Multiplayer Play Mode?
Is Mirror the better solution ?
it's been a while since i tried but iirc yeah it's possible, i think you can find the C# project somewhere in the library folder and open it or get the MPPM second window to open it somehow (double clicking a log in the console to browse to the source file like the normal window might work?)
i think you can probably attach to the second instance from your regular project too but i think that's what i did when i wanted to debug both at once 🤔
Mirror's uMMORPG asset is currently on sale on the asset store. I've never used it though
This is what a relay service is for. I thought mirror had their own but you can use Unity Relay as well
https://docs.unity.com/ugs/manual/relay/manual/mirror
Why doesn't the Unity Transport option come up when I try to add it as a component to a game object? I have Multiplayer Services and Unity Transport packages installed.
I don't use Mirror, but you would need to grab the UTP Transport from the repo on the docs page
Unity Mirror Sample project! This project demonstrates how to use Unity Transport Package (UTP) and Relay service with the Mirror Networking API. - Unity-Technologies/unity-relay-mirror-sample
Is this the wrong way to spawn players in a procedurally generated world? So once the algorithm finishes generating a level I assign a spawn position and spawn players after it finishes because the main spawn room changes locations due to the algorithm. However, its very inconsistent, sometimes clients spawn at 0, 0, 0 and out of the map. I wonder if I'm been doing it wrong this whole time and I should have a designated spawn room/location that I can spawn players right away in and then procedurally generate around that spawn location.
If its generating locally on each client then you'll want to send an RPC to the server when the client has finished loading the level. Then the server can assign and spawn the client's player object.
When I've been trying to work on making a multiplayer game before, every tutorial I've looked at used the netcode for gameobjects RPC system, which is fine, but they've always had the client and server in the same scripts/project. I'm trying to have the client and server applications be entirely separate from each other, as far as being in different projects, so they only have the code relevent to that side of the project. I haven't had any luck with getting the RPC system to work with this setup, as it's only worked when I make the server integrated into the client (sharing the same namespace/script). Is it possible to have the rpc system work in this manner, or do I have to have a integrated server to get RPC to work? Is there a better library or tool to use to be able to split the environments like this, or is it not even worth trying to split the environments?
A split project is possible but not worth the effort. You still have to duplicate all Network Objects and network behaviours on both. Unity themselves separates things with asm def files and compiler defines. You can use the dedicated server package to strip code and assets from the client and server builds if security is a concern.
https://docs-multiplayer.unity3d.com/tools/current/porting-to-dgs/optimizing-server-builds/
You can also forgo RPCs and Network Variables and just use custom messages if you really want to.
This is part four of the Porting from client-hosted to dedicated server-hosted series.
hello guys, how are you doing, I hope you are doing fine. So I wanted to ask about something, I want to make a multiplayer peer2peer mobile game however I've used photon before but it didn't suite me well even after being so close to finish the game on photon networking solution, I want to go for mirror or fishnet however those 2 networking solutions hasn't got any tutorials about matchmaking or lobby systems, and if they do then it turns out their tutorials are outdated anyways. Same goes for tools like master server toolkit which is outdated for fishnet and hasn't got any tutorials about mirror as well. So do you guys have any advice or any tips to get me started? because i'm really lost and got no idea what to do.
If you're fine with using NGO, I really like their new multiplayer Session SDK. It makes lobbies and matchmaking super easy
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session
if it doesn't have any problems or like issues then sure why not :DD
I've tried architecting my game in a similar fashion based on boss room architecture a few years back by keeping server and client code in separate assemblies, but I quickly found out that its going to be a PITA to do so. My approach was to use "controller" interfaces which would implement local/networked logic. Then "client" and "server" assemblies would have their own implementations. It was manageable for a while, but the boilerplate grew really quickly and the interfaces were leaky (they exposed IsOwner, Request/Response and similar). I just decided to keep everything in the same script and my life is way easier. I was recently re-checking boss room project and it looks like Unity themsleves backpeddled on their idea to keep everything separate 😄 https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture/#clientserver-code-separation
IMO in Unity networking libs are not designed for such separation and kinda suck in this regard. I looked at Photon Fusion a bit and it looks like it might be more suited for such approach from the surface, tho haven't tried that yet and just looked at the docs/samples. So I think your idea of having separate projects would be a whole new level of pain if just using assemblies is painful. I think you'll have lots of issues just spawning prefabs and not only architecting the code
Second this, currently using NGO with Sessions API and Distributed Authority, its quite nice and easy to get started. Tho if you go this route make sure to use Network Scene Management from the get go. Also do not rely on Session callbacks as you'll get weird issues where it tells you that connection is established when its not - subscribe to Network Manager callbacks instead for connected/disconnected/error events and you should be good to go
Not sure hows the pricing yet in production, we'll see in a month if it doesn't drain our wallets after release >:D
Using DA will be a bit more expensive than Relay. I'm curious to see exactly how much more that ends up being in practice.
Thank you for the suggestions, I'll probably just make it a shared project then, though Edd by any chance do you have any resources on doing custom messages as you suggested at the end, I want to try looking into that as well. I also haven't messed with assemblies yet, so if trying to do separate projects is more painful than something I haven't used yet, probably not a good idea I guess.
Here are the docs on Custom Messages
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
Thank you
so this didnt seem to work in the end consistently. I think ive tried pretty much everything at this point, but I feel like my approach of generating a spawn position later like that is probably bad and inconsistent. I'm not sure how much you've worked with procedural generation in multiplayer but would you say its better/a more common practice to have a known/fixed spawnposition on scene load?
I suppose it depends on the type of game, but the server should assign spawn points, which I assume would also be generated with the map. You wouldn't be spawning the players immediately on scene load so the spawn point wouldn't necessarily need to be fixed
I'm trying to get my Host to initiate loading a new scene. The host loads the scene fine, but my clients don't do anything. Are there any symptoms to point where the issue may be? I'm using NetworkManager.Singleton.SceneManager.LoadScene.
If the client is already connected to the host then the scene should change. When the client does connect, it will sync to the new scene
In the picture, data is sent using Lobby and Relay. When stepping into that new scene, would I need to reconfigure Relay to adjust for no Lobby service for data?
Usually the lobby is only used for sending the Relay Join code. Or if you are on Unity 6 You can use the Sessions SDK to streamline it
Well, it's used to facilitate a full lobby system using a low amount of data
I must have it misconfigured slightly somewhere, as everything in the lobby is synchronised perfectly
No idea how I just fixed it, but I reinstalled the Multiplayer tools package and it now works properly. Thanks anyway @sharp axle
Edit: Either that or the restart of both editors solved it
Hello everyone,
I'm looking to better understand how Distributed Authority works from a topology perspective.
For example, in a P2P Authoritative Host setup, clients send their inputs to the host (which also acts as a client). The host then simulates the entire game world and sends state snapshots and relevant events back to the clients. In this model, communication mainly consists of client-to-host input messages and host-to-client snapshots/events.
However, I'm having trouble finding clear documentation or examples regarding Distributed Authority. How does message flow typically work in that model? Could anyone help clarify or point me to resources that explain this topology in more detail?
Thank you in advance!
The distributed authority service itself manages the session state. Each client will send updates to the service for the objects they have authority over.
https://docs-multiplayer.unity3d.com/netcode/current/basics/ownership/
By default, Netcode for GameObjects assumes a client-server topology, in which the server owns all NetworkObjects (with some exceptions) and has ultimate authority over spawning and despawning.
@sharp axle by The distributed authority service you mean a machine hosted by unity? Is that optional? Or can I use one of client players to be the 'Session Authority'? So correct me if I'm wrong, the Distrubuted Authprity Topology, uses a Unity Dedicated server, which does not run simulation, but receives state from objects distributed on clients, and then relays the information to the other clients?
The DA is similar to the Relay Service. It's hosted and run by Unity.
One of the clients will be the Session Owner but it still goes through the DA Service.
It's hosted and run by Unity Is that optional?
No it's not optional. You can't use DA without it. Just like the other Unity Game Services.
Got it, thanks @sharp axle
hey, i have a unity netcode third person shooter game and when i want to restart the game i load the scene again and call this code on OnLoadComplete. The problem is that the client player spawns at the correct position but when it actually loads the screen of the player2 it jumps right back at 0,0,0.
no matter what position i set it to, it always only is on the correct position visible for the server and at a moment after the player2 actually loads the scene it jumps back to 0,0,0
what could be resetting the position even after setting is in instantiate?
If the player object has a owner network transform then it's overriding the position when it spawns in.
and how can i stop that? i just want the server to set the inital spawn position
You would need to send the position in an RPC. Or if you are Unity 6 you can swap the authority mode temporarily
well actually i have the networktransform set up like this and the authority mode is the server. I dont particulary know how it changes the game but this would probably mean that the server can just set the position
You're still using the old Client Network Transform script. If you want to make use of the Authority Mode field, just use the regular NetworkTransform script.
if that script is overriding OnIsServerAuthoritative it will ignore authority mode
so i changed it to network transform and changed the code to this, but it still does the same thing. the setpositionrpc just sets the transform.position
and also sometimes, it actually doesnt go back to the 0,0,0 position and it actually works which is very weird
so if i actually delay the setpositionrpc at like 1 second, it changes it to the right position, but then why does it not work in the script i showed you and how do i fix it? And btw, the script i showed you is called when all clients triggered the SceneManager.OnLoadComplete event on the server.
I would guess that the RPC is received before the NetworkTransform is initialized, sets the position to 0, 0, 0 and syncs the result
yeah thats probably, and how do i make it work then?
Make it server authority by default so you can set the spawn point from the server, then change back the authority to the owner after
okay that should work, thanks. But this is actually a pretty common and normal feature in a game to just restart it, is this how all games made in unity netcode have to do it?
It’s one of many ways to do it.
You’re mixing server and client authority on an object which can lead to the issues like the one you’re having. It’s usually best to have one or the other call all the shots.
well but if i want to spawn the players, i cant do it on the client right? So i have to mix the authorities
I’m referring to the setting of the spawn position
You’re using client authority to sync position and then wanting to set the position from the server for the spawn point. There’s not anything wrong with that at all, I’m just explaining why there’s a couple extra steps involved in that process.
okay, so i just found out that it still doesnt work, even when i set it to owner later it still treats it like its server, its weird, but maybe i could just make it so the client when it loads the scene tells the server that it has loaded the scene, the gamemanager will spawn it and the client will set the position by itself
i dont know if this is a better approach but the approach im doing now doesnt seem to really work correctly
Also a valid solution. Just something you need to be aware of when doing this - you may want to disable the visuals of the player object until the client is able to set the spawn point position
As there will be a small delay between the server spawning in the player object and the client being able to sync the spawn position change - so you may see the player spawn in and teleport to the spawn position after a small delay on other clients
okay thanks
I'm using NGO to connect to a dedicated server in Unity, but when the client tries to connect, I get the following error:
All socket receive requests were marked as failed, likely because socket itself has failed.
🫤
anyone here knows what I would need to do to setup a 100 player map? no need to talk about verts or server lag, just wanna know what i would have to do to get a prototype up and running
Use this guide to learn how to create your first client-server Netcode for GameObjects project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects.
this will just allow me to run 100 players by default
if you can get 100 players, sure.
i think im completely in over my head here but
I have a networking setup with client-server
first editor instance hosts and everythings great
Second editor instance joins as client and client cannot move or look around, but does have input animations
im assuming im not applying ownership but cant figure out how?
more context, in my player prefabs network transofrm i have authority mode set to server
when setting it to Owner, everyhthing works fine, my issue is, for a competetive FPS, wouldnt i want to verify position data with the server?
i tried this
public void OnMove(InputValue value)
{
if (!IsOwner || !_consumeMoveInput) return;
_inputDirection = value.Get<Vector2>();
_networkInputDirection.Value = _inputDirection; // Sync input to server
}```
but no luck
I found the problem.
When I install the Dedicated Server package from the Package Manager, the client throws the following error when trying to connect to the server:
All socket receive requests were marked as failed, likely because socket itself has failed.
But when I remove this package, everything works correctly and clients can successfully connect to the server.
It doesn’t matter whether I check or uncheck the "Enable Multiplayer Roles" option in the Dedicated Server package settings under Multiplayer Roles — the error still occurs in both cases. It only works properly when I uninstall the package.
The settings I’ve configured in the Multiplayer Roles section are shown in the attached image.
But why though?
I actually need this package.
now this is weird. So i implemented it where the client sets the position himself and it still doesnt work. I even made a coroutine of 1 second delay and it still does nothing.
the weird thing is that sometimes the transform position set does absolutely nothing, sometimes it actually sets it correctly after the 1 second and sometimes it even already spawns on the correct position from the beginning, because the server instantiates it at the correct position. This is extremely weird
Does the same thing happen when you keep the network transform on server authority?
when i let it on server authority, it spawns initially on the correct position and stays there, but then obviously the whole game breaks and i cant move etc...
What version of NGO are you on? Also try turning off Interpolation
Im on version 3.1 and i will try the interpolation, but i dont know how that would fix it
The thing thats weird is that im literally setting the position as the owner and it doesnt work, but i can normally move by wasd
i think im completely in over my head
also try updating to 2.3.2. There were some fixes to Network Transform
okay, so i updated it and it didnt change anything and also turning off interpolation also did nothing
also a very weird thing, i tried this and it did absolutely nothing on the host and on the client.
You have another problem going on there. maybe something else is moving the player
yeah but then why does it always work on the host but not on the client? If it was something else than it wouldnt even work on the host
It would be something on the clients overriding the position
okay i fixed it. the problem was the character controller overriding the position.
thanks for the help tho
how can i properly use authority mode: server for client position without making that clients movement feel like absolute shit
I am using Netcode for GameObjects,
Anyone know if its possible to show session in lobby list later after the game has been hosted?
I am thinking to skip lobby entirely (As if a singleplayer session), and later they can open it to public. (Listed in lobby list and put password)
How easy is it? I am still in the process of choosing the technologies I'll use.
If you're using NGO: Client Anticipation
Client anticipation is only relevant for games using a client-server topology.
hey so i think i made a dumb mistake that may be the cause of all my random desync/player spawn issues with procedural generation, but wanted ur opinion if you think this is an issue. So I usually additively load levels, and without thinking about it i did the same for this project where I additively loaded/unloaded my map generator upon new levels. I realize now that additively loading levels is really just for levels already created in those scenes and that I really could have just called a function instead of loading a whole scene.
I have UI elements that are supposed to cover the screen while loading the level, basically "Waiting for opponent", from the Main Menu scene with a DoNotDestroy, however the half-loaded level gets shown for a few seconds and then the game proceeds like normal. Any help?
Code:
Server/Host:
NetworkManager.SceneManager.LoadScene(levelPrefabs[UnityEngine.Random.Range(0, levelPrefabs.Count)], LoadSceneMode.Single);
Client/Host:
NetworkManager.SceneManager.OnLoadComplete += OnLoadComplete;
You can query sessions at any time. You would have the host make a private session with only itself in it. Then later they can make it public so others can join
It would definitely be easier to just call the generator function again if that's all you need to happen.
Are you not seeing the loading screen at all? You should be subscribing to OnSceneEvent and you can use the Load event's AsyncOperation for a progress bar
I have a loading screen before loading the scene and then when the other player joins they subscribe and start the loading.
However when the scene loads the DoNotDestroy elements aren't visible
Even though the loading screen isn't disabled
I will check out the AsyncOperation
thanks a lot, ill dive into this
Is this the same service as the lobby service?
The Sessions API is built on top of Relay and Lobbies
Ok thanks!
I dont get it why this error happen, how to fix this? NetworkVariable is running well, but NetworkList is exist error
whats condition and teamtype?
Depends on the game but I'll usually start with the standard Unity First or Third Person Controllers
kk
Hello, in the host side the client animation doesn't update, any help on what could be happening, pls?
Are you using NetworkAnimator?
Yes
Make sure it's in owner authoritative mode if you are controlling it from the client
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
yes I think it is in authoritative mode, In was verifying the host side in the inspector the client prefab the animator variables don't update, but in the client side both client and host update normally
if(!IsOwner) return;
_moveDir.x = playerButtons.Horizontal();
animator.SetFloat("Speed", _moveDir.x);
Is it possible to load a scene from an asset bundle when Scene Management is enabled?
Not with Network Manager Scene Manager.
Can anyone help me come up with a base network design for server authoritative player items, where the item stats are rolled during runtime when a player opens a container. Im not sure really how to start. I created a ScriptableObject class called itemdata with some basic items, but im just trying to figure out where to store player inventory items, how to roll stats and instantiate new items, and how to add them to the player inventory.
Im reading that theres a NetworkList type that you can use, I might use that for the player inventories. But then, im just curious how I will initialize the data of the player inventory as theyre loading into the game. Like where to store the information. Would I use some sortof database? most likely. How do I connect a database to unity haha.
https://docs.unity.com/ugs/en-us/manual/cloud-save/manual
Cloud Save is Unity's solution for storing player and game data.
huh?
really 🤔
oh right i forgot i do weird shit
apologies
With some IL stuff you can actually make it work, Not sure if I can provide an example link/elaboration since I only know about it via modding
Is there a way to fix this? It shows up when i install netcode for entities, and i already have netcode for gameobjects. uninstalling netcode for entities fixes it. Can you not have both in the same project?
I've edited scene loading code a bit already to work using paths (sadly my proposal was declined to implement this to upstream, IMO way more robust than build indexes). If you have any modding links, I'd take a look 😅
🤔 what
!ban 754540163970891887 spreading scam
skeephalo4343 was banned.
You can not have both installed at the same time
Hi, do network variables get reset when the NetworkManager is shut down and the host is started again?
When the Network Manager Shutsdown, all network objects get destroyed which takes the network variables with them
What about those in-scene placed network objects? Their network variables don’t get reset when I shut down the host and start the host again using NetworkManager.StartHost
I have many persistent network objects, typically managers with DontDestroyOnLoad on them
If they are persisient then they will not reset. You will have to deal with them manually
Why does my code not spawn the items for all players?
using Unity.Netcode;
using UnityEngine;
public class ItemSpawner : NetworkBehaviour
{
public Item[] itemPool;
public int spawnCount = 10;
public Vector2 spawnAreaMin = new Vector2(-10, -10);
public Vector2 spawnAreaMax = new Vector2(10, 10);
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (IsServer)
{
for (int i = 0; i < spawnCount; i++)
{
SpawnRandomItem();
}
}
}
void SpawnRandomItem()
{
Item selectedItem = itemPool[Random.Range(0, itemPool.Length)];
int value = Random.Range(selectedItem.minValue, selectedItem.maxValue + 1);
Vector3 spawnPos = new Vector3(
Random.Range(spawnAreaMin.x, spawnAreaMax.x),
Random.Range(spawnAreaMin.y, spawnAreaMax.y)
);
GameObject obj = Instantiate(selectedItem.worldPrefab, spawnPos, Quaternion.identity);
var networkObject = obj.GetComponent<NetworkObject>();
networkObject.Spawn();
ItemWorld iw = obj.GetComponent<ItemWorld>();
iw.SetItem(selectedItem, value);
}
}
That should work. Are you seeing any errors in the console?
The ItemSpawner object in the inspector didn't have the network object component. Which I didn't know it needed.
Any NetworkBehaviour needs one
Yea. It's supposed to add a network object automatically if it doesn't.
Unless you manually turned that off
What’s the best way to sync player movement? I’m guessing transforms, not velocity for a character controller?
I’m just trying to figure out how to make the movement look smooth with transforms
Somehow interpolate it?
I’m also curious how it would work for the local player, do they just move normally, and then send out updated transforms every frame? And if the new transform is invalid, the server resets the players local position to last known position?
Network Transform will handle syncing and interpolation for you. It will only send data when the transform changes. It has Server or Owner Authority modes. If you use Server Authority then you will have to deal with input lag somehow. There is an Anticipation System to help with that though
Client anticipation is only relevant for games using a client-server topology.
im using server authority
man network programming for games is very complicated haha
I had another question, for server authoritative, should the server keep track of all player movements aswell? Im just worried about overwhelming the server
using UnityEngine;
public class PlayerMovement : NetworkBehaviour {
private float gravity = 18.0f;
private float playerMass = 2.0f;
private float jumpForce = 10.0f;
private float moveSpeed = 3.0f;
private Vector3 velocity;
private bool jumping;
[SerializeField] private CharacterController characterController;
public override void OnNetworkSpawn(){
jumping = false;
}
void Update() {
if (IsOwner){
RequestGravityServerRpc();
jumping = false;
}
}
// player wasd movement
[ServerRpc]
public void RequestMovementServerRpc(Vector3 movement){
// perform checks for valid movement
PlayerMovementClientRpc(movement);
}
[ClientRpc]
public void PlayerMovementClientRpc(Vector3 movement){
characterController.Move((movement.normalized * moveSpeed + velocity) * Time.deltaTime); // maybe add some sortof call that gets the player stats to change movement speed
}
// player jumping
[ServerRpc]
public void RequestJumpServerRpc(){
PlayerJumpClientRpc();
}
[ClientRpc]
public void PlayerJumpClientRpc(){
if (characterController.isGrounded){
velocity.y = jumpForce;
jumping = true;
}
}
// applying gravity to players
[ServerRpc]
public void RequestGravityServerRpc(){
PlayerGravityClientRpc();
}
[ClientRpc]
public void PlayerGravityClientRpc(){
// gravity
if (!characterController.isGrounded){
velocity.y -= (playerMass * gravity) * Time.deltaTime;
} else {
velocity.y = -2f; // Small downward velocity keeps player grounded.
}
}
}
``` this is my current player movement script that responds to player input, jumping doesnt currently work, but can anyone let me know if im on the right track haha.
im just not sure if I should apply the player movement locally, and then just send transform updates to the server, or if theres a different way I should be doing it
I just need the players transforms to be pretty accurate to avoid desync, as there will be accurate physics collisions for damage etc
chatgpt told me I should be applying the movement in the serverrpc lol
chatGPT don't know jack about squat. Its like 3 years out of date.
lol
You need to disable the character controller on all non authoritative clients if you are going to go full server auth
okay
also you are using the old RPC system. [RPC] instead
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...
I understand it now
oh thanks haha
chatgpt helped me understand it
the player requests to move the player serverside, to move it in the simulation, then you use network transform, or a different custom interpolation to sync the transforms
I feel like theres probably a better method out there, but this one works for now
man this legacy lerp sucks
regular lerp is a lot better, nice
Man testing clients does take a little while
You should use Multiplayer Play Mode for testing
thanks
Im curious how to make rotation local, but also set it on the network, it seems difficult to configure
wait I think ive got it figure out\
I got it setup, its decent
I cant believe I thought multiplayer would be easy
If you can accept giving clients way more authority you can get away with a lot more (depends on the game ofc). Also once you do networking abit you start to get into the common patterns and maybe start building little helper classes and utils to make it easier
nicee
Im trying to make my game very server authoritative because im going to have quite a few items that get random stat rolls on them, as well as a lot of pvp, hard mobs to kill for good drops. So I want to eliminate absolutely any ability of the client to take advantage of client authority. Im not even telling the client any values of any other player inventory or attribute. all of those things will be gathered by the owner, or server during an item hover, or attack
That’s a big task 😅
oh my lord I finally got player rotation and position to sync
Yeah, well this is all I do in my spare time when im not hanging out with my girlfriend, so I have a lot of time haha. Im also waiting to hear back on some interviews from some jobs, so I've got time. I want to make a good game
I already have a lot of the item logic laid out, I just needed to get actual player movement working first lol
Only thing im having troubles with in terms of the items is sending Guid over the network
using UnityEngine;
public class PlayerNetworkSync : NetworkBehaviour {
[SerializeField] private GameObject player;
[SerializeField] private CharacterController cc;
private NetworkVariable<float> rotationY = new NetworkVariable<float>(writePerm: NetworkVariableWritePermission.Owner);
private NetworkVariable<Vector3> playerPosition = new NetworkVariable<Vector3>(writePerm: NetworkVariableWritePermission.Owner);
void Update() {
// set network variables if the owner, because the owner is the one moving the object in their instance
if (IsOwner){
rotationY.Value = player.transform.rotation.eulerAngles.y;
playerPosition.Value = player.transform.position;
}
// read the network variables and sync the player's position to this session.
if (!IsOwner){
player.transform.rotation = Quaternion.Euler(0f, rotationY.Value, 0f);
player.transform.position = playerPosition.Value;
}
}
}
``` I seperated the logic for movement and syncing positions, and its so much cleaner
ignore my comments, sometimes they make no sense because I write them extremely fast so I have context if I have to do something else suddenly xD
they make sense, just poor grammar
Just keep in mind that is client authoritative
yeah I know the client is moving then telling the server its transform, Im going to have to implement some sortof validation checks serverside that will prevent the player from moving if they have some sortof invalid movement.
there was just way too much input lag when the client was basically remote controlling their character
im not sure what kindof validation ill come up with, but ill figure something out, just need it functioning for the moment
Man theres a lot to consider when writing anything for multiplayer hahahaha
You'll want to check out the Client Anticipation I linked up above. It's fully client server authoritative. But still allows the client to move with no latency
server authoritative?
if so ill check that out after I get all the player input working here
alright, now im having an issue where I cant change the transform of a bone on a playermodel, clientside or serverside, not sure why
i think rotations are the most annoying things in unity
I figured it out, an animator was enabled and I didnt realize hahaha
im having a problem, i wanted to up the network manager tickrate from 30 to 60
when i do this, and connect a client, they are immediately dropped, it works fine on 30
Hey hey! I am using the Network Scene Manager to load a scene for the host, then automatically distribute the scene to a late joining client. However, the second player's objects in the scene (monobehaviours, not networkobjects) seem to not be running their start and awake methods, even though they should be local to the joining player
If Start() and Awake() are not running then you have some bigger issues going on.
Hello. I was facing a problem when trying to handle user disconnection/leaving the game.
What happens is. I have this function subscribed to NetworkManager.Singleton.OnConnectionEvent
This is the function:
private void Singleton_OnConnectionEvent(NetworkManager arg1, ConnectionEventData arg2)
{
if (arg2.EventType != ConnectionEvent.ClientDisconnected) return;
print("Disconnecting " + arg2.ClientId);
if (arg2.ClientId != NetworkManager.Singleton.LocalClientId)
{
NetworkManager.Singleton.Shutdown();
}
else
{
NetworkManager.Singleton.OnConnectionEvent -= Singleton_OnConnectionEvent;
Destroy(NetworkManager.Singleton.gameObject);
SceneManager.LoadScene(0);
}
}
What happens here is when someone disconnect. If it wasn't you. disconnect yourself (to return to main menu)
If it was you. Destroy the network manager singleton. And load the scene (to prevent multiple network managers in the same scene)
The problem is when I tried to host a game after leaving a game. The
NetworkManager.Singleton.StartHost();
Doesn't work even though the network manager exists in the hierarchy
This is the entire Host Lobby function:
public async void HostLobby()
{
MainMenuManager.Instance.ShowHideLoadingScreen(true);
try
{
const int maxPlayers = 2;
Allocation alo = await RelayService.Instance.CreateAllocationAsync(maxPlayers - 1);
// Host doesn't count
string joinCode = await RelayService.Instance.GetJoinCodeAsync(alo.AllocationId);
CreateLobbyOptions options = new CreateLobbyOptions
{
IsPrivate = isPrivate,
Player = getPlayer(),
Data = new Dictionary<string, DataObject> {
{JoinCodeKey, new DataObject(DataObject.VisibilityOptions.Member, joinCode)},
{KEY_timer, new DataObject(DataObject.VisibilityOptions.Public, timer)}
}
};
Lobby lobby = await LobbyService.Instance.CreateLobbyAsync("Lobby Name", maxPlayers, options);
connectedLobby = lobby;
StartCoroutine(HeartbeatLobbyCoroutine(lobby.Id, 15));
transport.SetHostRelayData(
alo.RelayServer.IpV4,
(ushort)alo.RelayServer.Port,
alo.AllocationIdBytes,
alo.Key,
alo.ConnectionData);
print("Created a lobby");
NetworkManager.Singleton.StartHost();
PlayerUI.instance.ShowLobbyCode(connectedLobby.LobbyCode);
if (connectedLobby != null)
{
MainMenuManager.Instance.ShowHideLoadingScreen(false);
_buttons.SetActive(false);
}
}
catch
{
MainMenuManager.Instance.ShowHideLoadingScreen(false);
_buttons.transform.GetChild(4).gameObject.SetActive(false); // Hosting a game menu
MainMenuManager.Instance.ErrorMessage("Failed creating a lobby.");
}
}
I would suggest a bootstrap scene that loads the network manager before the main menu. That way you don't have to worry about destroying the network manager
How can I implement it?
just an empty scene with the network manager and a script that loads the main menu scene in Start()
Great. This and the removal of the destroy function should fix everything right?
SceneManager.LoadScene(SceneManager.GetActiveScene().ToString());
I should use this instead of 0 right ?
maybe. keep in mind that you will only get ClientDisconnected event if you or the server are already disconnected. If another client disconnects then your will get a PeerDisconnected event
It is subscribed to:
NetworkManager.Singleton.OnConnectionEvent
I already tested it in a different scene to know which one gets notified and when does it get called
If you want to just reload the current scene, yea.
I noticed that if a client left. it would call for both host and client. If the host disconnect. It would call for both that the client disconnected First. Then for the host that the host disconnected
since it would get called twice when the host leave. I put the if statement to check if it was you who disconnected or not
Anyways. Thank you for the help. It took me a whole week trying different approaches 
Bumping this
There is not really a reason increasing the tick rate would drop a connection. Unless something is flooding the network and timing out. But you would see errors in the console if that were the case
Console shows the following
Host is client 0 in this case
-Client 1 connecting…
-Client 0 disconnected
This is all thats shown at 60 tick rate
At 30 its
-Client 1 connecting
-Client 1 connected
How do people usually setup animations over the network? what does the architecture usually look like
right now mines just PlayerInputHandler.cs -> handles player input, handles animation network variables, handles local animations
I think im just going to make a PlayerAnimation.cs to seperate the logic
If you are using NGO then NetworkAnimator will handle the syncing for you
The NetworkAnimator component provides a fundamental example of how to synchronize animations during a network session. You can also use RPCs, NetworkVariables, and custom messages to create a custom animation synchronization system, if it suits the needs of your project better.
UnityEngine.Debug:LogWarning (object)
Unity.Netcode.NetworkLog:LogWarning (string) (at ./Library/PackageCache/com.unity.netcode.gameobjects@91cf39ffcce4/Runtime/Logging/NetworkLog.cs:28)
Unity.Netcode.NetworkManager:CanStart (Unity.Netcode.NetworkManager/StartType) (at ./Library/PackageCache/com.unity.netcode.gameobjects@91cf39ffcce4/Runtime/Core/NetworkManager.cs:1258)
Unity.Netcode.NetworkManager:StartServer () (at ./Library/PackageCache/com.unity.netcode.gameobjects@91cf39ffcce4/Runtime/Core/NetworkManager.cs:1288)
Unity.Netcode.Editor.NetworkManagerEditor:DisplayCallToActionButtons () (at ./Library/PackageCache/com.unity.netcode.gameobjects@91cf39ffcce4/Editor/NetworkManagerEditor.cs:336)
Unity.Netcode.Editor.NetworkManagerEditor:OnInspectorGUI () (at ./Library/PackageCache/com.unity.netcode.gameobjects@91cf39ffcce4/Editor/NetworkManagerEditor.cs:395)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
what does this mean
using UnityEngine;
public class ConnectionApproval : NetworkBehaviour {
[SerializeField] private PlayerSpawnSystem playerSpawnSystem;
private void OnNetworkInstantiate(){
if (!NetworkManager.Singleton.IsServer) return;
Setup();
}
private void Setup() {
NetworkManager.Singleton.ConnectionApprovalCallback = ApprovalCheck;
NetworkManager.Singleton.StartHost();
}
private void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response) {
// The client identifier to be authenticated
var clientId = request.ClientNetworkId;
// Additional connection data defined by user code
var connectionData = request.Payload;
// Your approval logic determines the following values
response.Approved = true;
response.CreatePlayerObject = true;
// The Prefab hash value of the NetworkPrefab, if null the default NetworkManager player Prefab is used
response.PlayerPrefabHash = null;
// Position to spawn the player object (if null it uses default of Vector3.zero)
response.Position = playerSpawnSystem.PlayerSpawnPosition();
// Rotation to spawn the player object (if null it uses the default of Quaternion.identity)
response.Rotation = Quaternion.identity;
// If response.Approved is false, you can provide a message that explains the reason why via ConnectionApprovalResponse.Reason
// On the client-side, NetworkManager.DisconnectReason will be populated with this message via DisconnectReasonMessage
response.Reason = "Some reason for not approving the client";
// If additional approval steps are needed, set this to true until the additional steps are complete
// once it transitions from true to false the connection approval response will be processed.
response.Pending = false;
}
}
This is my script
I followed the documentation, I thought this defines the callback
some weird errors, all I did was enable connection approval, and used the unity docs code
wait I sortof figure it out
heres my network script, maybe ive done something wrong?
one thing is that if you add prefabs to the prefab list at runtime then you need to be sure that its added on both server and all clients
okay ill check that, but how does that relate to client 1 getting immediately dropped on 60 tick rate and not 30?
You might get a Network Config mismatch error. But like I said before there is no reason for tick rate to drop a connection so something else must be happening
yeah that makes the most sense, the tick rate shouldnt matter at all, so i assumed i have to be doing something wrong on my side
interesting, it ONLY works on 30, im going to dig in and get back to you to see what i can find
Huh, so 29 and 31 also fails?
And you are changing it in both the client and the server/host?
Are you changing it in the MPPM clones too?
how would i do that? and wouldnt the clones be, for lack of better term, cloning the scene data from the main editor?
oh wow i tihnk i fixed it
Do you know what the problem actually was?
yeah im an idiot and didnt save the scene after changing the inspector value, so the MPPM clone was expecting 30
you were so right
thansk for your help
Hey guys - At the end of a game, I'm trying to load the main menu scene and disconnect all players from a lobby (using FacePunch). It's giving me this error:
Anyone know why?
Code:
// Load new scene (networked)
NetworkManager.Singleton.SceneManager.LoadScene(scene.name, LoadSceneMode.Single);
// Shut down lobby
GameNetworkManager.Instance.LeaveLobby();
Leave lobby code:
public void LeaveLobby()
{
currentLobby?.Leave();
}
Its trying to initialize steam again when you load that Menu scene.
Easiest workaround would be to have a bootstrap scene that loads the network manager before the menu scene. Then you can go back to the menu without duplicate managers
Wouldn't that still cause it to do that, but within the bootstrap scene?
The problem happens on awake within the FacepunchTransport script, but I'm not sure why it doesn't happen when I load the main game scene from the menu scene since it would trigger that same logic..
The bootstrap scene would only load once when the game is first opened.
Your main game scene wouldn't have another network manager in it.
The network manager gets moved to Do Not Destroy On Load to persist between scene changes
Ahhh yes I see. Actually, that's basically how I have it now.
-The main menu scene has the Network Manager in it.
-When we load the main game scene, it's dragged along in Do No Destroy On Load, and that works just fine.
-Then when the game is complete, I try to load the main menu scene again, but then I get the errors.
Are you saying I should load a bootstrap and then load the main menu additively?
He's saying to make the boostrap scene the scene that opens when the application is first opened and have the NetworkManager in it. From there load the main menu scene and then never worry about the bootstrap scene again and just load in between your main menu and game.
You'll load in one NetworkManager one time, and don't have to worry about duplicate initialization attempts from those scripts.
Ohhhhhhhhh I gotcha I gotcha. Ok good suggestions guys, thank you 🙂
Yeah. The menu or game scene doesn't have to be additive
when storing a game object as a variable, how do i sync this variable across clients, as i cant store it as a network variable, and without it being a network variable, when the game object is instantiated, it is only being assigned to the variable on the host and not any of the clients
You can not serialize a gameobject. But if its a spawned network object then you can use a NetworkObjectReference
Brief explanation on using NetworkObject and NetworkBehaviour in Network for GameObjects
thanks 👍
i have a save file, its several hundred kilobytes rn and i need to sync (parts) of it to clients. sending the parts i need synced at the start with an rpc doesnt really work because its so big, is there a good way to do this or do i have to cut it into pieces and send it in parts with rpcs
public static List<byte[]> SplitBytes(byte[] source, int chunkSize)
{
var result = new List<byte[]>();
for (int i = 0; i < source.Length; i += chunkSize)
{
int length = Math.Min(chunkSize, source.Length - i);
byte[] chunk = new byte[length];
Array.Copy(source, i, chunk, 0, length);
result.Add(chunk);
}
return result;
}
var chunks = SplitBytes(data, 1024);
for (int i = 0; i < chunks.Count; i++)
{
//send each chunks[i] here to clients
}
@flint shadow
you can also send length of array to clients, so client can add data to a new byte[] or List<byte> and when lengths are same, do whatever you want with it
thanks, i think i'll also look into optimising the save process as well (one specific category is making up like 400kb of the save file ffs) but i think splitting is the most scaleable lol
Out of curiousity what is it that's being saved?
yes exactly, otherwise you can not send large data with rpcs
basically theres like a city with a bunch of houses, semi randomly generated (different variants of houses and furniture etc) and the furniture is taking up like 400kb even though i only save their prefab id and location to 2dp and their health value
the split sending works better than i thought it would tbh thanks gracz!!!
maybe, you can just create a new struct/class to store variables and send it
i think i already have it the most optimised i can have cuz i have a custom parser that saves on characters (it justs uses a godawful amount of delimiters) and turn it into ascii byte[] and send it compressed using gzip
Obviously you know your project far better than me but a big way this kinda thing could be "solved" potentially is by not having to send that specific data as a save to each player in the first place. instead sending perhaps a rng seed and/or just the host loading the save and initializing the game stuff from that save via messages that get sent to each client
Just ideas rather than specific suggestions
i do just use RNG seeds for nondestructible stuff but since these furniture things can be destroyed i had to save them somehow, and also they cant be networkobjects that are just loaded by the host cuz networkobjects are really laggy in large amounts lol
i guess i could just manually spawn them on all clients with an rpc for each object but i think i have a better way to save them, each house could save all of their furniture objects since it has all the spawnpoints it doesnt need to keep positions and rotations
Yeah every aspect of this might not need to be a networkobject but depending of the scale of your game a higher scope piece of content could be a networkobject that manages the stuff inside it (eg. maybe the building managing the furniture?)
yeah i already do something like that to sync their health i could probably do that pretty easily actually
Anyone here familiar with Quantum?
If I click an object in Unity, is there a way to send a reference to that object as an input to quantum?
For example: I have an item on the floor, I want my player to be able to click the item and then place it somewhere else
Has anyone gone through and attempted the ecs/dots character controller tutorial (third person) found here: https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Tutorial/tutorial-netcodecharacters-gamesetup-thirdperson.md
Despite some descrepencies, I was able to get it mostly working. However, it's unclear to me why it seems that the third person orbit camera is being set as a ghost component and simulated by the server.
I could be interpreting this wrong or maybe I missed a step, but what ends up happening is if you simulate a high latency (ie: 400ms) the camera becomes impossibly difficult to control.
I find it hard to believe that the orbit camera is meant to be configured in this way and assumed it would be client side for responsiveness.
Has anyone gone through this tutorial or know where I might want to start looking / changing things?
It's due to how the prediction system works. The orbit camera has to be an owner predicted ghost. If everything is working properly you shouldn't be feeling any latency with your inputs. It's all client predicted.
Here's a very short demo of what I'm seeing in this test project. It consists of just a custom server and client, handshake/ingame authentication and some rpc's to establish a player in game, and from there it's largely an implementation of the previous tutorial w/ netcode for entities.
If I change the client/server latency to say 400ms, the camera lags behind my mouse movements substantially, and jitters excessively.
This seems fundamentally incorrect to me but it's unclear what I have setup or configured wrong.
like yes, I get that I'm simulating a poor connection, but people are going to have ~200ms connections. What's throwing me for a loop is how/why this is tied to direct player camera input and controls.. something isn't working as I would otherwise expect.
At this point I'm just pouring through the docs because I clearly must have missed something (everything is configured as owner predicted, HasOwner is checked, the network id's are grouplinked with the spawned entities etc). Next step is probably to see if there's a demo of the full setup available somewhere and if the source (the tutorial) also has this issue.
400ms ping is going to be nearly unplayable no matter what. But if you've updated to NFE 1.5 then you can change the Lag Compensation Physics World Collision buffer to 32 ticks and that should help a bit
So I've actually figured it out after going back through the guide step by step.
TLDR; I overwrote the vital changes here: https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Tutorial/tutorial-netcodecharacters-prediction-thirdperson.md which substantially change how the camera and input is handled and when / where it's simulated.
I was moving project files around for organizational purposes and essentially "undid" this step of changes. Now, as I would expect, the latency between the client and server has no noticible impact on the player's ability to move around the game world in open uncontested space with smooth camera movement.
Does anyone have a known/ideal solution to this github issue someone posted: https://github.com/Unity-Technologies/CharacterControllerSamples/issues/6
I have the same issue now, and it's pretty obvious that it's an oversight. I can think of some ways to address it potentially but curious to know if there's already something identified or updated
If you follow the directions in https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Tutorial/tutorial-netcodecharacters.md Everything works in the editor fin...
You really shouldn't have multiple cameras unless you are doing split screen
Yeah it seems to be that the tutorial isn't very well designed.. I was able to "resolve" it in the short term and posted a reply to that github issue.
but yeah fundamentally I don't see why the server needs to know about the orbit camera of the clients.
If I had to guess it would be so the player character model could look/aim at whatever the camera is looking at.
for sure.. but I would have imagined all of that really only needs to exist in the client simulation world.. why the server needs to know the players camera settings is beyond me.. I guess you MIGHT want it for cheating etc.
If the other clients need to display it for whatever reason then it has to be a ghost. I would think the sample would still work fine with the orbit camera being completely local.
It might, it'll just take some deviating from the example. It's something ill pursue over the next few days to figure out why it needs (or doesn't need) to be a part of the server simulation. Ideally the tutorial wouldn't do it in this way (unless there's a very good reason I'm unclear on)
Hey there! I am using the SceneLoader of the NetworkManager, however, it seems that the MonoBehaviours aren't running their Start or Awake methods for the (late) connecting clients, which leads to them not being initialized and working on the second player. How would I go about solving this?
The only reason Start() or Awake() won't run is if the object or component is inactive
Funny thing is, thats the case for some reason. Might it be because it is a Monobehaviour script and the NetworkManager.SceneManager cant sync it properly? Does it need a NetworkBehaviour?
To clarify: It is active for the first player, but when the late joining player loads the scene, it is inactive for the second player
no, ultimately the network scene manager is just calling SceneManager.LoadScene as normal at some point, there's nothing special that should stop components activating normally
how can you tell their Awake methods aren't running?
The game object is inactive?
I have Log calls in them to test them out, as well as all references breaking when they rely on the start being run
actually just the script component of the Monobehaviour
If its not disabled in the scene then you have something else disabling that component
well, in the first player's scene that component is (and stays) enabled, its just when loading the second player's scene it gets disabled for him
would just use OnDisable to see the stack trace of where it's getting disabled
Any tips to be able to make players hold items and interact with them in NGO?
I saw you cant have networked objects parent other networked objects (player parent item to bone).
Updating the item position on Update worked but I feel this isn't the best solution.
Another way I read was using a local non-networked object for each player enabled by an rpc (leaning towards this one, will figure out animation sync)
Solutions are very dependent on the number of different grabbable items and also the level dynamics needed for the items.
I tend to like the local non-networked object route if the main goal is just pick-up + drop interactions
What's the difference between PredictedSimulationSystemGroup and PredictedFixedStepSimulationSystemGroup?
To me it seems like they are very much the same besides the fixed update group can have a higher update frequency
My only 'fear' is a possible desync between making the networked version despawn/hide and show in the player hand locally.
But I dont see a better way 😅 maybe read a bit more
There will be latency just as any other solution. Making sure there's no blatant desync should be easy as you're just doing those two main actions; showing + hiding.
Is there a way I can make two players interact like normal.When I use netcode for gameobjects they cant push each other.I have soft body characters so only thing happens is when a moving player crash to a stable player the moving one bounces back but the one that got crashed dont get effected.I added client network transform to all bones of soft body character and the parent.
I'm not sure there is a difference
https://docs.unity3d.com/Packages/com.unity.netcode@1.5/manual/physics.html#predicted-ghosts-and-physics-simulation
Syncing physics is a hard problem. You might also want to look into Client anticipation
Client anticipation is only relevant for games using a client-server topology.
i think theres a difference, yet subtle. I will continue looking into it
Maybe. But Physics updates on FixedUpdate. I don't think there is any faster update loop for it.
ah i see now, that must be the difference between the two
is it worth it to just use unity physics to save the headache of prediction? especially if i might use ecs for some systems
GameObjects and DOTS Physics do not interact. If you are using Netcode for Entities then you are likely already using Unity Physics
i understand gameobjects dont interact because they use physx, but can i feasibly create my own rigidbody component which internally references an entity and just updates the gameobjects transform
Yea, that's doable. You would set the rigidbody to Kinematic and use rb.Move() with the matching entity's LocalTransform
alright thanks. i feel like unity should give you an option to use dots physics for gameobjects just for its determinism
That's coming with their ECS for All merge initiative
How do you guys normally handle returning to a menu and keeping players all connected, but despawning the actually players?
A bootstrap scene before you main menu will allow you to return to it without having to worry about duplicate network managers. You can keep players connected to a session or lobby
That's what I'm doing based off your last recommendation, but I think my player character is being deleted from the scene transition and that results in me having no player. Have any advice for that? I don't want the whole player to be in the menu scene.
The player object should persist through the scene changes. You might want to disable the renderer of the players while in the menu scene
Ah, good idea. I'll give that a go! Thanks 🙂
Ok, one more thing. I'm putting DontDestroyOnLoad on my NetworkObject gameobject, but it's still getting destroyed on load. I also have tried an assortment of options on the NetworkObject, to no avail. Have any idea what I may be overlooking?
If the object is still getting removed from the Do Not Destroy On Load scene, then something must be destroying it manually.
But what could it be?! 😄
If you're still interested in helping, this is my NetworkObject on my player when in Play Mode
These are when not in play
The player object might work a bit differently. Are you trying to keep it around after the client disconnects?
I'm trying to have the host load a scene (the lobby) and keep everyone connected. I don't NEED the player object, but I thought that was the only way to keep the game alive and persistent