#archived-networking
1 messages Ā· Page 31 of 1
An update.... I re-installed 2021LTS via the hub.. I made a dedicated server build, and was able to connect to it via the client. š
For who exactly is IsLocalPlayer true? Is it true for children of the PlayerObject? Can I manually set it true for objects spawned by my local player object? I have a local player object that works more as a manager, and it instantiates the actual object that the player controls, including its camera, which I of course want to disable if its not my own. How can I do that properly?
You would use IsOwner instead for that case. I believe IsLocalPlayer would only be true for the root player object if it had children. You can not spawn child network objects but you can reprarent them after spawning.
IsOwner is true for all spawned objects on the Host tho since it is also server
You can use SpawnAsPlayerObject() if you only have one playerobject at a time. Otherwise you will need some other team identifier
I assume this is not networking related but Il drop it here incase I'm wrong. I'm trying to recolour player objects. The line playerMeshRenderer.material.color = IsLocalPlayer ? Color.magenta : Color.green; doesn't have any effect. I've tried SetColor, using sharedMaterial.color and copying the material, changing the colour then reassigning the material back. I'm on 2022.3.47f1. My current code:
public override void OnNetworkSpawn()
{
// We should create a unique Material for each Player GameObject
Material uniqueMat = new Material(playerMat);
uniqueMat.name = $"{this.gameObject.name} Material";
playerMeshRenderer.material = uniqueMat;
// Move the Player and Recolour its material
if (NetworkManager.Singleton.IsServer)
{
transform.position = IsLocalPlayer ? Vector3.left * 4F : Vector3.right * 4F;
SubmitPositionRequestServerRPC(transform.position);
playerMeshRenderer.material.color = IsLocalPlayer ? Color.magenta : Color.green;
NotifyOfRecolourRPC(playerMat.color.r, playerMat.color.g, playerMat.color.b);
}
}
Bizarely, this code works in Start() but not in OnNetworkSpawn():
Material uniqueMat = new Material(playerMat);
uniqueMat.name = $"{this.gameObject.name} Material";
uniqueMat.color = Color.red;
playerMeshRenderer.material = uniqueMat;
Hey y'all, I have been looking into the different networking options, and it seems like for large multiplayer games most people go with fishnet, my best guess is that fishnet can allow many dozens, maybe even hundreds of connections to play in real time? The classical advice seems to be to use PUN 2 for games with smaller rooms? I am planning a game sort of dauntless, a fast paced action rpg with lots of realtime combat, but I ideally would like up to 20 people in a room together to emulate large scale dungeon crawling, does anyone know if this would work with PUN 2? Would it be practical or cost effective? Is Fishnet the better option for pricing? I am inclined to use PUN 2 for its match making and room management, but it's hard to decipher what the real strengths and weaknesses of these different services are.
Any networking solution currently available can handle 20 or so players. PUN has been deprecated though so you would want to Fusion 2. But Unity Netcode or Mirror can handle it just fine as well. Things get tricky if you need fast-paced performance or more than about 100 players
Thank you so much, it's been hard to understand that much just searching online.
So apparently, if I make a serverrpc to spawn it, as opposed to just spawn it when the player object spawns on the server, and give it the client id, and then do SpawnWithOwner, then it only sets the client as owner and the server actually has IsOwner fasle... that feels like something unintended ngl
That's right. If you SpawnWithOwner(clientId) then the server will not be the owner
Well, guess thats how I wanna do it then to work properly lmao
Hi all, I'm doing a test update of my project from Unity 2022 with Lobbies and Relay, to Unity 6 with Sessions and Widgets. There seem to be a few duplicate Types within the two. Can both packages, Lobby and Sessions, work in the same project or do I need to remove all my old Lobby and Relay managers?
The loading screen shouldn't be its own scene. Just a full screen UI panel.
The old managers will still work but you have to uninstall the relay and lobby packages(matchmaker and multiplay as well). They are included with the Multiplayer Services SDK
Anyone in here familiar with WebRTC in unity? I got some issues setting up the videostream correctly, as my stream state is stuckin "checking", but both get the offer and answer from both sides.
Hey @sharp axle, that's what I was hoping but I've found that even after they are uninstalled i'm still getting errors. Specifically anything referencing Lobbies. I get this error -
error CS0433: The type 'Lobby' exists in both 'Unity.Services.Lobbies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Unity.Services.Multiplayer, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
You might need to restart Unity or delete the library folder and reimport
I've tried that but still getting issues Lobbies: Lobbies.Instance.CreateLobbyAsync - giving an error of - "error CS0234: The type or namespace name 'Instance' does not exist in the namespace 'Lobbies' (are you missing an assembly reference?)"
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
should be LobbyService.Instance
Thank you, missed that. Too many bits of old code mixed in with new.
You can turn off Scene Management
You can use Scene Validation to prevent clients from loading certain scenes
Network Scene Manager scene events load and unload have an AsyncOperation you can listen to for progress
do you have any tips, to not singleton the LobbyService?
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html just use the normal SceneManager's Async Loading
Per the docs: If you load a scene on the server-side using UnityEngine.SceneManagement.SceneManager then it will be synchronized with late joining clients unless you use server-side scene validation
Then they should be loaded using the NetworkSceneManager so you can make use of SceneEvents
That would be my guess - using the normal SceneManager probably doesn't trigger any SceneEvents even if the loaded scene is being synced for late joining clients
So get clients to load the inventory scene themselves.
Then use Scene Validation to prevent late joining clients from getting it automatically synced when they join.
Netcode for GameObjects Integrated Scene Management
Seems like it
This comes coming up on an object that I spawn as a child of another object which has a NetworkObject, it comes up on the NO-less prefab, is there a way I can mark it so this message stops coming up? I cant just give it a NetworkObject component, because then it says that nested NOs are not supported, this is really annoying to deal with :(
There is a setting in the project settings to disable that message
If you mean the initial load, I'm not sure there is. I would pop a loading UI between StartClient() and the LoadComplete event
^ lol
I'm using netcode for gameobjects
and there's 100 cards in the table, which I would like to somewhat synchronize their transform
and like 20 more objects which I would like to do the same
would that be super bad? 120 objects with client network transform?
I'm trying to achieve a game... somehwat like tabletop simulator, where it simulates a real life game
so people can try our game before buying it, and not needing to own tabletop simulator```
It probably wouldn't be great. I mean, I'm sure you could optimize the settings on the component and only move them in simple ways - but that is a lot of Network Transforms.
xD.... yeah...
If it were me I would definitely look at a different approach.
Like using RPCs or NetworkVariables to sync to each client that a preset/predictable animation or movement should play locally for the card.
You could even allow the owner client to move the cards around freely with the mouse, but only send this RPC or set this NetworkVariable when they're done and have placed the card so that other clients can play a preset animation/movement for the card.
that sounds good
I had something like that in mind but
not sure how I will achieve it XD
I haven't done much with the cards yet, I'm just planning so
I'm open to ideas
void OnMouseUp()
{
if (_dropLocation is CardPlaces.None)
{
transform.position = _lastPosition;
transform.rotation = _lastRotation;
if (_cardLocation is CardPlaces.Hand)
{
ResetCardPositionInHand();
}
}
else
{
_boxCollider.isTrigger = false;
_rb.isKinematic = false;
ChangeCardLocation(_dropLocation);
ChangeCardPositionRpc();
}
_dropLocation = CardPlaces.None;
_isBeingDragged = false;
_boxCollider.enabled = true;
_handler.TransparentCardObject.SetActive(false);
}
[Rpc(SendTo.Server)]
void ChangeCardPositionRpc()
{
transform.parent = this.transform.parent;
transform.position = this.transform.position;
}```
something like this?
I need to add network object here, right?
tag me for replies plz ā¤ļø
I would have a single Card Hand manager class that would control all the graphics on the cards. It would have the network object on it and any network variables/RPCs needed. That way each card would not need its own network object
For network varaibles, and a Distributed Authority system. How do I set them for all clients/host from either a client/host?
Can I just assign values to them like MyNV.Value = OtherValue; and then the local state will be sent on the next network tik, or will that only set the local state?
Or would I need a [Rpc(SendTo.Everyone)] that then sets the MyNV?
And if I set them dirrectly do I have to claim ownership before writing to them?
Likewise how do we make sure the NetworkVariable value is set before the network spawn?
OnNetworkSpawn() maybe?
Why you answering with a maybe. I can maybe all day XD
Sometimes
NetworkBehaviour is an abstract class that derives from MonoBehaviour and is primarily used to create unique netcode or game logic. To replicate any netcode-aware properties or send and receive RPCs, a GameObject must have a NetworkObject component and at least one NetworkBehaviour component.
I read that, but it was put in context of an authoratative system. Would the "Server" be whatever client spawned the object?
Plus that section is a bit, vague
It is missing the context of networkVariables and setting stuff on awake.
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
Is more relevant, but they set the initial state of the NetworkVariable in OnNetworkSpawn, where it was said earlier that the NV state should be synced already by then. Which was leading me to think you can set it on awake.
Though maybe I will need to do a isOwner check instead of isServer(as I have no clue how that behaves on a Distributed Authority network)
To my knowledge you will get warnings/errors when trying to set the value in awake. OnSynchronize is the earliest you can safely set it AFAIK.
I know you're using "server" as a way to compare between DA and Client-Server, but best to get away from that to prevent mixing up the two. There is no true server with DA. Ownership/Authority is given to the client who spawns an object unless changed afterwards.
This means NetworkVariable Write Permissions are given to the owner by default in DA. So you can check HasAuthority when setting a NetworkVariable. If true, you can set a value directly. If false, you can use [Rpc(SendTo.SendTo.Authority)] to request the owner to set a value.
That's fair enough... I have to think how I'll do it
This makes alot of sense. I am still not 100% on how to properly set the initial state of the network variable before spawning across clients
Can I simply Instantiate the GO and then in the Awake do a HasAuthority, and set initial values? Then that gets replicated across?
no Awake() is called before its on the network. You want to use OnSynchronize()
NetworkBehaviour is an abstract class that derives from MonoBehaviour and is primarily used to create unique netcode or game logic. To replicate any netcode-aware properties or send and receive RPCs, a GameObject must have a NetworkObject component and at least one NetworkBehaviour component.
Can you not set values before the object is sent across the network? That seem unperformant if we are already sending the data about the Behavior to spawn it?
setting the value right after spawning is viable too. On other clients the network variable should be already up to date when OnNetworkSpawn() is called
Okay, and for that Awake works with a HasAuthority?
Aka so that code doesn't get called on the other clients that are gettting sent spawn.
Awake will not work because its not on the network at that time.
Isn't that what we want though? Because the state will be set before it is on the network, so when it gets sent to the network the state is already set?
Oh the HasAuthority won't right
I remember reading that somewhere
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior/#spawning
don't expect netcode-distinguishing properties (like IsClient, IsServer, IsHost, for example) to be accurate within Awake and Start methods.
NetworkBehaviour is an abstract class that derives from MonoBehaviour and is primarily used to create unique netcode or game logic. To replicate any netcode-aware properties or send and receive RPCs, a GameObject must have a NetworkObject component and at least one NetworkBehaviour component.
why isnt this possible?
the type of OnRegistrationResponce (sic) isn't Action<RegistrationResponse>, C# has to convert it to a delegate of that type when you call it, but C# also won't infer type arguments from things which need that kind of conversion
if you cast it to Action<RegistrationResponse> it should work, but at that point you might as well specify the type on the call
If you want to add coop into your game, which solution is better: Unity Networking or Photon Fusion?
What kind of coop, any game example?
think of zelda 4 swords
nothing fancy. Just max 4 ppl on a 2D top down adventure game
Either are perfectly suitable for that. Just comes down to whatever solution you like more and are more comfortable working with
The current version is working with Photon Pun 2, but 20 CCUs is very limited. Thats why I want to change it to Fusion or Unity Network.
I assume Unity Network doesnt have a CCU-limitation because its player hosted
I'd assume Pun 2 to Fusion is probably a much easier port than switching to NGO
I have to rewrite anything no matter what. Thats why I m asking.
I just want to know which is easier to handle and future proof. I dont mind to rewrite everything from scratch as long it works well. I converted my game already from Pun to Mirror to Pun again. So, I would mind to switch to Unity Networking.
I'd probably recommend NGO in that case. A simpler 4 person co-op game wouldn't take full advantage of most of Fusion's features + I think you're still locked in to using Photon Relay/Hosting services and their pricing.
NGO is suited primarily for smaller scale co-op and I think would probably beat out Fusion in terms of ease-of-use in your case. Added bonus that you're familiar with Mirror because it's quite similar to NGO.
If you're really looking to future proof, I'd recommend starting off using Unity 6 and NGO 2.0.0. As well as making use of the Multiplayer Services package: https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual
Awesome, thank you very much
https://hatebin.com/hmtjbjfhqr
What would cause this simple code to not sync between two players, host and client. The host creates a server and the prelobby perfectly starts the countdown and displays one player connected. Now when as a client i type in the host's ip and conenct to the same prelobby, the host's game now displays that 2 players are connected and the countdown is still going smoothly but the client's player count is for some reason 0 and the countdown is completely unsynced meaning it starts again from 0.
I already tried asking chat gpt but he came up with nothing usefull, i also tried rewriting it completely but that also did nothing.
NetworkServer is a class in Mirror that is used for a server/host. It's inaccessible and/or all of it's properties are empty for a client as it's not used because a client only uses the class NetworkClient. When using Mirror you really shouldn't be using NetworkServer or NetworkClient anyway. Try seeing if NetworkManager has reference to the player/connection count instead.
You're not syncing the countdown at all. You're just running a countdown on each instance of this script separately. I would look at SyncVar to see how you can use it to make a synced timer.
Oh, alrighties that's why. Thanks ill definitely look into that!
I fixed on the script but now i got another issue, no UI is updating like everything is freezed in the prelobby and the error message says "NullReferenceExpection: Object reference not set to an instance of an object PreLobby.Update () (at Assets/PreLobbyStuff/Scripts/PreLobby.cs28)
Completely no idea what would be causing this error, All text labels and buttons are properly assigned in the inspector. The code seems normal too.
https://hatebin.com/fiolgmbqrw
i tried some debugging
void Update()
{
Debug.Log("0");
if (isServer)
{
Debug.Log("1");
}
}
Only 0 is going throught console.
the isServer is for some reason giving the same error
is this script running before you call StartHost?
Im not sure but i would say i doubt that. StartHost is called in the MainMenu when the player clicks create server, then the scene switches to the prelobby and this issue arises.
public void OnCreateServerButtonClicked()
{
NetworkManager.singleton.StartHost();
StartCoroutine(LoadSceneAfterDelay(0.5f));
}
This would be the part in the main menu that creates the server before prelobby
I have found an solution, my canvas was missing NetworkIdentity
When building a multiplayer game for webgl, with NGO, and the use of dedicated servers. Is it true i'll still need Lobby + Relay in order to easily connect people to the dedicated server?
Your first Fusion app comes with 100 CCU for free. Permanently and you can release with it.
Shared mode is using a similar approach as PUN but is more convenient with plenty of samples...
Only if you are using Unity Server Hosting or other hosting service with dynamic allocations
ahh yeah good point, since the Multiplay (Unity Dedicated servers) spins up and spins down servers when Matchmaker requests are processed.
This means that it's not a static IP/port. So it means we'll need Lobbies to well, let us find the game. And i use relay for the webgl part. Since well, i have no clue if Relay is needed but i think it works well when using Lobbies. Also to punch trhough it can be needed?
Thanks a lot, your answer opened my eyes.
Hi, when i try to change a network variable that is in a [System.Serializable] class I get a warning "NetworkVariable is written to, but doesn't know its NetworkBehaviour yet". Is this something I need to worry about?
assuming this is NGO, i'm pretty sure all NetworkVariables need to members of a NetworkBehaviour class
And that network behavior needs to be on a network object spawned in the scene
This is a snippet of the code, if I take the NetVar out of the MissionScene class then its fine but within it gives me that warning. either way it does actually change.
public class MissionManager : NetworkBehaviour
{
[System.Serializable]
public class MissionScene
{
public string sceneName;
public NetworkVariable<int> scenesAllowed = new NetworkVariable<int>();
}
public static MissionManager Instance;
public MissionScene[] missionScenes;
}
Just want to make sure i'm not doing something wrong. It is working and its only a warnign not an error so...
Is that network variable actually syncing?
I wouldn't think so. But if it works, it works. I guess the network manager goes through all the subclasses as well
Would there be another way to do this that is safer? It is working but still giving me warning which i'm not very happy on leaving.
I see that nested network variables arent supported from an old post 2021 but cant find anything recent
I would make MissionScene a struct and implement INetworkSerializable. that way you can just have a NetworkList<MissionScene>
and not bother with nested network variables
Thanks, i'll take a look!
Hey guys,
What would be the best alternative for "Multiplayer Play Mode"?
I'm working on a project, "Unity Dedicated Server + PlayFab + Mirror". There is an open-source tool, ParrelSync but it seems like the author dropped it, and I'm looking for something similar.
Thanks
If you are not on Unity 6 then ParrelSync is the alternative.
so, it still works with the Unity 2022.3.x ?
it was working up still 2023.3 at least
Thank you!
It is always a pity when such rare and fantastic tools are dropped.
Hi, I'm using unity 6 22f1 presently to develop a prototype for a coop game, i wanted to test and use the new features etc.
I want each player play in first person
I got two players to succesfully conenct to one session (one virtual) off of the same player prefab. however for whatever reason the camera that is assigned to the prefab only works for the host player and doesnt seem to exist at all for the second player regardless of what i try to do. i thought to go around this by making a template camera in the hierarchy and assign it to players after the prefab has been used but the result is the same, first play recieves camera, second player does not
am i just being stupid and missing something obvious?
How are you assigning the camera?
I gave the template camera a specific tag that only it has, i search it via FindWithTag, then instatiate it and then set it as the child of the player
it does work succesfully for the first player, and each player that joins has a script that should run this upon joining the session
Hi, I'm using unity 6 22f1 presently to
If you haven't already, post this in #1062393052863414313
i use netcode 1.0.0pre-9, and E-net transport 2.0 to develop a moba mobile game. After a lot of networkobject Destory , I find system use more memory on Memery ProfilerćBecause it like Array,List,Dictionry did not clear and give null. Who know which version netcode solve this question?
i can use object-pool solve this question=.=.eeeee!!!!!
Hello! Im using mirror for making a multiplayer game and i have a issue
This method is supposed to turn off the PreLobbyCanvas once the round start, and it does that just perfectly. However the problem is it only does that on the Host, so the person who starts the server. All the clients ( The people who join the server) still see their canvases enabled. What could be causing this issue?
after taking my time, the client asked me to have all objects be network client transform
they want the project to feel as scuffed as possible, like if it was playing in real life... xDDDDDDDD
for every card to sync their position in real time, making them a client network transform
having NetworkBehaviour inside of them, how does that sound?
if not, make a script in a handler that will tick 1 card every x frames, to sync their position to the other player
Thatās going to be a bandwidth and performance nightmare Iād say.
how bad are we talking?
doesn't tabletop simulator do it that way?
It depends on how you optimize the movement and the NetworkTransform
But if they want it to be āreal-timeā youāre not going to be able to do much if that.
I donāt really play any, but Iād doubt it.
it's a bunch of gameobjects that syncronize their transforms
scale, rotation and position
Most of them probably send that state of the board to clients and have the clients play animations and move things locally based on the state.
As opposed to syncing every single transform value in real-time.
welp
š¦
I could prepare some questions on how you would do things, with images and you can help me know what would be a better way to approach what I'm trying to do
you're right, they only sync the position in real time
or have a distance threshold, if that distance is passed they do a movement transition from point A to B
Thats how network transforms already work.
The problem you'll run into is the sheer amount of network objects
100 - 120?
Pretty sure card games sync the general board state, or single actions (while ensuring the same state) happening with cards, and replay those actions locally. So rather than networktransforms, sync the initial board state and broadcast any action to the client, eg. drawing a card, just as an event with some cardID and maybe playerID to make it clear who did that. You send a few dozen bytes tops only when needed rather than just a horrendous amount for each card in real time
same with an attack, attackerCardID, victimCardID when a card attacks another (I'm thinking in hearthstone terms but you get the idea)
have ya'll played Tabletop Simulator?
Is it where you have "hands" and can manipulate each object as if it were a physical one?
lmao yeah, so they by nature do server-auth networktransforms, in real-time. That's kind of needed for them, from the screenshot I see a vast majority of cards wont be moved at once in your game though. Can/Should they interact with eachother physically while moved?
If not, you can only sync positions per-frame when selected
that sounds like a banger optimization
altough, that is kind of solved already by threshholds
Its been a while since i've played it multiplayer, but i'm not entirely convinced TTS uses server auth physics.
Yeah, just assumed but if it's not competitive at all then client-auth is fully possible for better responsiveness.
Damn, I say try doing it the simple and blunt way, see how it behaves under bad network conditions, and just how much bandwidth it draws when you try to absolutely do as much destruction as possible, and go from there. You can do custom messaging as you described, or if you just need the position to be accurate for another player eventually just send a pulse with all cards positions each half a second? and interpolate between the difference. Going further you can only send data of cards whose position moved over some threshold, so the bandwidth increases only as chaos increases, use half-precision floats , ensure only X and Z is synced (if you don't move them vertically) etc.
Is unity netcode for game objects good enough to handle 25-30 player dedicated servers? I am working on a multiplayer game currently using mirror, but there are so little actual tutorials for mirror that i have trouble coding the round itself. While i wanted to check out netcode today and after just 1 actual tutorial i can tell it is way easier than mirror and im maybe planning to switch to unity's netcode istead. However the simplicty of it also made me think if it's strong enough to support that kind of sized servers since from what i know but im not sure it is made for smaller co-op games rather than bigger multiplayers.
That will ultimately come down to your server hardware. But you should be able to handle a couple dozen players depending on your game type
So it depends more on the quality of the dedicated servers themself rather than the networking which i am using?
For the most part, yea. Different solution have more built in features than others. But I haven't seen much that you couldn't implement yourself with any given network library
Alright, thank you very much.
Mirror and NGO are about as similar as can be, tbh. You shouldnāt find that much difference between them honestly
That being said if you feel more comfortable with NGO, go for it. NGO has a guide on porting Mirror/UNet code to NGO which would make the transition pretty simple.
Also thank you, the thing is im a beginner to networking and i found mirror a pain in the ass, and like said after one tutorial of NGO i can tell it's way simpler. However when i asked GPT about if it's efficient enough for 20-30 player servers he answered that NGO is made for 4-5 player co-op games rather than bigger one's, so i was a bit worried i may do all the coding for the game and when im finally done and buy the dedicated server it turns out to be extremely laggy et cetera.
It really depends on what your game entails and how you implement your networking code.
I used an early access version of NGO and Relay 5 years ago and had no problem having games with 15 players connected.
You should also always be testing and profiling your game during development.
Yeah. Definitely donāt wait until the end to see if things are working as you want them to
nothing should be a surprise when you go live.
Alright, thank you guys very much, definitely switching to NGO then. I did manage to achieve some stuff with mirror, but i wasn't able to find any good tutorials for it other than some nonsense talk about things nobody will even ever use so the most of my mirror usage was scripting, getting errors then asking on the mirror server how to resolve those errors and so on for 3 days straight.
Also be careful using ChatGPT for NGO going forward.. Iāve found itās knowledge about it is quite outdated.
I try to limit my ChatGPT usage when programming because sometimes he make stuff more complicated than it actually is so i only ask him questions when i actually cant find a real answer.
Yea, You'll want to shell out for Unity Muse if you want up to date AI
Thanks guys for all the usefull stuff!
There is also a Netcode Discord where the Unity devs post occasionally
Thank you, just joined it.
How do u make like a game manager for networking ive indtantiated it on my master client so theres only one of it but then i cant get refrence to it on the other clients im using photon btw but yeah how do i refrence it
Anyone know why NetworkTransform doesn't work? I have 2 players in scene whenever when moves around errors get thrown and the movement doesn't get synced.
The error:
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.NetworkTransformMessage.Deserialize
(Unity.Netcode.FastBufferReader reader, Unity.Netcode.NetworkContext& context, System.Int32 receivedMessageVersion) (at NetworkTransformMessage.cs:64)
(Unity.Netcode.FastBufferReader reader, Unity.Netcode.NetworkContext& context, Unity.Netcode.NetworkMessageManager manager) (at
NetworkMessageManager.cs:575)
Nvm, it looks like there was a weird bug on my own side of the code
TH.photonView.RPC("PlayerSatDown", RpcTarget.AllBuffered, i);
public void PlayerSatDown(int i)
{
players[i] = PM.gameObject;
playerSat[i] = true;
}```
im using this to update these variables to players and i use RpcTarget.AllBuffered to make it so late joining playersget updated but their not and i dont get why
hey guys, im trying to make a fps game and its my first time using netcode for game objects.
is this how i should handle bullet trails? :
what im saying is that the client that shoots the bullet will tell the server, then the server will tell any connected clients to just spawn a bullet and lerp them from position x to position y, because we dont need the bullet trail on the server.
is this the correct way to do it?
Hello. I am developing multiplayer card game using Unity and Colyseus framework. I've completed basic game logic but after I've integrated multiplayer function, there happens serious errors. when we establish connection, main UI was loaded but I cant see them. I hope the professionals are help it. Looking forward to hearing from you.
I wouldn't use lerp for bullet travel. But you can disable the trail renderer on the server if that's an issue.
well
it does have physics š¤
that sounds good, the ticking every x frames or half second
I figured
I'm trying to finish all mechanics, as if it was a single player thing
and then build them in multiplayer, might be double the work, but knowing exactly what I need will help a lot
and there's not a lot anyways
and also maybe, send this project here, or record stuff if I ever need to
Yea. I believe all the physics is done locally on each client.
huh, interesting
the bullet trail is only visual, thats why im thinking things related to bullet trails can be handled on the client, through a clientRPC
that seems like a lot of extra work. And you have to deal with the delay the RPC will have.
alright then, so how should i synchronize weapon effects like the muzzle flash vfx(srp) point light flash, and the vfx(srp) for the bullet trails?
Those don't have to be synchronized since they are local only. You can use an RPC to trigger your shooting animations and effects. or you can use Animation Events and let the Network Animator synchronize things
[Netcode for GameObjects]
I'm trying to serialize an array that contains instances of a particular class with the interface INetworkSerializable. I'm serializing it using the method NetworkSerialize, but the compiler won't let me do that. Here is the NetworkSerialize code:
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref directions);
}
What puzzles me: I've already done a similar thing (serializing array of INetworkSerializable) multiple times in the past, but it's the first time the compiler has prevented me from doing so. Any idea why it happened?
Does distributed authority only work for NGO?
I didn't think you could serialize arrays that way since they are reference types. NativeArray should work though.
At the moment, yes. NGO2.0 only. But since its a service like Unity Relay, I would think it would eventually be usable by anything.
Seems that NativeArray won't accept non-nullable values. I've checked how NativeArray works for a class that has no issues with being serialized in an array, and turns out NativeArray also won't work here. The conclusion is that sometimes .SerializeValue lets me serialize an array of nullable classes, but I've no idea why.
Are you using custom serialization for your class? I only ever use structs with INetworkSerializable
Netcode uses a default serialization pipeline when using RPCs, NetworkVariables, or any other Netcode-related tasks that require serialization. The serialization pipeline looks like this:
I'm using only INetworkSerializable so far. It worked for other classes. The not-working example looks more or less like this:
[Serializable]
public class Direction : INetworkSerializable
{
public GridMode gridMode; // enum
public int direction;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref gridMode);
serializer.SerializeValue(ref direction);
}
}
@sharp axle
Oh, I've just figured it out. My Direction class had a constructor that has some parameters, which implied that this class had no parameterless constructors. After adding a parameterless constructor everything works fine again. š
I was about to say there is no reason that code wouldn't work
Does any one have experience using netcode connected over the local host to do stuff in multiple unity windows for some sort of weird functionality? I'm surious as to how y'all handled it and what the use case was
You're gonna have to be more specific.
Oh, I'm trying to do a hacky sorta work around to run two unity windows by having one be the client and one be the host. I'm doing it so that one window can be streamed live and the other window can have behind the scenes stuff going on that doesn't get streamed and I figured that'd be the easy-ish way to do it with out having to resort to 3rd party solutions or breaking my brain, lol
I've worked with photon, but I don't want to have to pay to liscense it and deal with setting up the systems for actually connecting through a network, y'know?
I want to be able to control what the viewer sees in window one while I work in window 2 with the actual UI. I want to hide what I'm doing
make sense?
The window that is streamed isn't supposed to be interactive in any way
Is https://docs.unity3d.com/Manual/MultiDisplay.html an option?
Other than that, some IPC solution or any UDP transport should do the trick.
Why not stream the window in discord?
Oh, I thought that only worked for one window accross multpple monitors? I'll try it!
Because I don't want to see secret information as we interact accross discord. I'm making a virtual table top
I'm personally not very familiar with its capabilities, but it's worth checking out
I did very briefly, but I might have misunderstood
Right now, I was thinking to just run server, host, and client on the sae machine, lol
If this is all on the same machine then yes, Multi display is what you should use
Just for reference, I only have one monitor. Just want to make sure you understand the question
If you are streaming to a different PC then I would use WebRTC
https://docs.unity3d.com/Packages/com.unity.webrtc@3.0/manual/index.html
I mean, it's not that deep. I just want to be able to manipulate UI elements in one window, that I stream over discord, while I click on stuff on my window. The important part is just them being able to see text and pictures I pull up with out seeing the menu that I use to pull them up. I don't need a super robust solution. Just an easy one
God.... the documentation for this suuuuucks
Interesting! I'll look into that. I don't think using Display is going to work, because the constructor isn't public and the array of displays is automatically populated by Unity
You technically could hack the individual windows to do what you want by getting the window handle and doing what you want through OS API.
But please just anything other than IPC over Windows Registry š
Haha! I have no idea how to do that. Is there a particular reason I wouldn't want to use the netcode package? Also, I'm not the smartest, but what does the windows registry have to do with ICP?
PlayerPrefs on WIndows are stored in Windows Registry
Netcode is fine, especially if you do want to sync scene and objects instead of just plain data
Yeah, I just want to be able to visualize die rolls on both screens while hiding the interface on the one that actually selects from the random tables for the players, so I can GM on discord
I want a bespoke solution for a TTRPG thing I'm doing
If you don't actually need any of the "gameplay networking" features and just want to send plain network messages between clients, transport like Unity Transport used by Netcode is a bit cleaner solution.
Yeah? I'm not entirely sure what all of my features would be, so there is a chance that I might be syncing some game objects, like map markers and stuff, but I wouldn't really need to. I've only really used photon for one project at that, and am just sorta getting into netcode
Netcode is probably the safe and easiest option then.
Valid
Help needed
I am building a dedicated server
Problem: How can I remove unnecessary scripts, components and game objects from the scene in the build (the server does not need visual effects, decorations, cameras, etc.)
Or should I just create another scene for the server and sync it somehow
The dedicated server package can help you strip out unneeded assets
https://docs.unity3d.com/Packages/com.unity.dedicated-server@1.3/manual/index.html
Isn't this for the new version of unity? I'm using Unity 2022
These are also steps you can take on older versions
https://docs-multiplayer.unity3d.com/tools/current/porting-to-dgs/optimizing-server-builds/
This is part four of the Porting from client-hosted to dedicated server-hosted series.
Thanks, that will help me a lot
This repository does not contain a valid Unity project. Unity projects must contain a valid Unity version file in the path "ProjectSettings/ProjectVersion.txt".
To include it in your local workspace, follow the next steps.
Can someone help me with this?
so I am pretty much done with the basic mechanics of the game
sitll need to do the camera but, that can be done later
now, how is it that I would store the cards position and state (if activated, and flipped)
š for multiplayer, like you guys said
when suggesting not to use ClientNetworkTransform on all of my cards xD
NetworkVariable probably is sufficient for all three of those things
on each card?
I have 100 cards that are instantiated when the game starts
... I really don't have an idea of how I would do this... :/ I kinda need examples and such, if possible
I remember someone else saying that may be too many NetworkObjects, but you'd have to test.
Your other better option would probably be a NetworkList that keeps track of all the cards data.
oh, network list
Do you really have to instantiate all 100 cards? But you only need one network behavior on your card prefab
oh, I can have a network behaviour on each card
just not client network transform š ?
call my own OnCardMove(){Move for the other player too}
It's not the best way to do it. But it should work
Yeah, I would avoid instantiating if possible. My most recent project with Mirror had 75 NetworkObjects each with a NetworkBehaviour that had a NetworkVariable to keep track of its state. But they were based off of a prefab and placed in-scene.
I'm looking for a way that's not too bad, but that doesn't take time to make either
this is how I have it
the ownerID is not actually set yet xd
I guess I could put 100 cards in the scene, so I don't have to instantiate them
so make each card a network behaviour
to set the parent of a network object, does the parent also have to be a network behaviour?
From DeckHandler.cs, which is not a NetworkBehaviour
I assume also I should use, "Distributed Authority"
I see
kinda frustrating but... I guess I will have to break each thing down little by little until I get it
Network Object parenting has rules and can get rather complicated
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
Distributed authority is a whole other thing. I don't think you'll need it unless you are planning a full tabletop simulator type physics playground
Distributed authority is one possible network topology you can use for your multiplayer game.
oof
well
I would prepare a word document of how I would like everything to work and send it here
so people can visualize better how to assist me
but idk XD I feel like it's too much
well
I wouldn't know why I would need it, or why I wouldn't use it
Very basically, it shares the server processing load between all the clients. But since there is no central server authority, cheating can become an issue
oh I don't mind cheating really but
el bien hablas espaƱol?
just so I don't have to do things twice I'll keep it like that
only with female
im female
then, si
no
vrga
oh
well spit it out, make sure in the correct channel xd
i can pay u like 5 or 10 bucks for paypal
on which channel then? haha
sure
fair enough
well, let's start with
what things I should have checked here
(I want to change my card's parent every so often)
!collab - stop spamming this across different channels
: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
anyone know why collider callbacks wouldn't work on an object with a ClientDrivenNetworkTransform, CharacterController, and a CapsuleCollider? (this is on the server)
I put a Rigidbody on the object is should fire collision events for but it only fires the events when IsKinematic is false yet NetworkRigidbody forces it to be kinematic
That is correct. Collisions will only fire for the server
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/
There are many different ways to manage physics simulation in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.
guys for the life of me I cannot figure out why my player cannot move in the server, I am using unity multiplay hosting and matchmaker, and when I join, I just cannot move at all, here is my code https://paste.ofcode.org/35igiV98aV6KihbAQhnVnBm
You need to disable the character control the remote players. A network transform can handle syncing the positions. Check out this sample for working with Cinemachine and the 3rd person character controller
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/main/Basic/ClientDriven
Hey guys, anyone had trouble with Netowrk lightning?
I have a map wiht realtime lightning that works nice! the problem is when i use my networked player (Wich has a flashlight that you can activate via script), realized when i use any kind of script to activate or deactivate lights will make the other realtime lights, go crazy, they dissapear at certain angles (Its not forward lightning problem, i use deferred 100%)
I use FIshnet 3.11.18
your question/issue has nothing to do with networking
So where should it go on the discord?
or the server for the framework you are using
This is only for networking via Unity?
no, but mostly yes, there is a whole server for the framework you are using, so why not use that
Got no answers there, already asked
hello Im making a party game and I wanted to use unity netcode but I have an issue right now. I made a basic server sided movement however I think latency is so high for client. How can I fix that? Theres massive difference between playing from host and client right now and it makes it kinda unfair. My example game is 4 player pong
You can either use Client anticipation or the new Distributed authority if you are using Unity 6
Client anticipation is only relevant for games using a client-server topology.
Distributed authority is one possible network topology you can use for your multiplayer game.
Hello,
I am using Lobby and Relay.
I have built a chat when all the players of the lobby have loaded a new multiplayer scene and are connected with Relay.
But before that, I don't find how to build a chat for the lobby room (where the players wait before to load the game scene). Any concept to share? š
I would say Lobby isnāt perfectly built for a chat system to be implemented but itās definitely possible
At a pretty basic level you could just make some custom player data called āchatMessageā and instantiate some text that equals what chatMessage was set to
Using Lobby Events to ensure this happens every time a player updates their chatMessage Data
Oh, I see. Thanks.
If you are using Unity 6, vivox is super simple to set up with the Multiplayer Services SDK and Widgets package.
My player is keep getting out of sync š¦
I have a pretty involved question about server rewind in regards to melee combat. I really don't even know how to format the question in a way I would get an answer.
TLDR: What would be the proper method to check for hits when the mesh is being interpolated but the actual server side hit boxes aren't?
The reason this is confusing to me is because the visual mesh that the client hits is in the past. Then add on top that its being interpolated from an even older position to its current one. Meaning when I request a hit validation from the server and I pass the frame the hit occurred on, there's a high chance I wouldn't get a hit confirmation. As I type this I realize I would need to calculate the offset caused by the interpolation as well as use the server's current frame instead of the clients frame. Even then this is all a jumbled mess in my mind lol.
No, I am not using Unity 6, my project being several years old already.
This seems to work fine, not tested in multi yet though.
Well there is a little more than one second delay to display the message, but I think that it remains okay.
Thanks.
Be careful with this. Lobby has bandwidth limits with regards to how much data you can send
Even on older versions I still say that Vivox is the way to go.
The server should not be rewinding. It is the source of Truth for the simulation. The client should not be rolling back in the middle of attack animations, your client prediction should be locked in unless you have some kind of animation canceling happening
Yes, the idea is to recreate the exact view that the client had at the time of doing the hit, in the server, and taking into account things like interpolation.
Usually this is done by appending each input from the client with the two ticks (snapshots) used for interpolation and the alpha between them.
It's pretty simple to implement if you have a proper tick-based networking solution, with a clear replication strategy where you can be sure that by simply using a single number (tick), you can know exactly in the server what the client had.
However, the real problem is performance. As resetting individual transforms is very slow. However, for games with small scales and low player counts (less than 16), it's fine.
Lobbyās free tier covers up to 10 GiB. Sending chat messages this way youād be looking at barely a KiB per message. Youād have to route millions of chat messages through Lobby to even get close to going above the Free Tier.
As long as he has a cooldown for sending messages to avoid Rate Limits, this method is more than sufficient for a pregame chat system.
i can't write to a network variable in distributed authority?
They have to be set to Owner Write Permissions
What's the best way to host a P2P multiplayer solution yourself?
Are Unity mutiplayer services advantageous in the long run ? Or i need to use an another alternative ?
I'm planning to create a multiplayer game. The games will be hosted on the host PC, with 6 to 12 players per game.
Any relay service will work for that. Unity Relay, Steam P2P, or even Epic Online Services can work
But what about pricing ? What is best solution for an indie game developer ?
Only you can make that call. Unity Relay has a free tier that you will be unlikely to go beyond as an indie. Steam and EOS are both free but tie you to their services. Photon Cloud is also an option with a similar free tier to Unity.
Thanks for your answers! I'll take a closer look š
Hey ya'll! I am having an issue in Unity 6 LTS (6000.0.23) that happens with all to me available netcode for gameobjects versions (1.10-2.0).
I have set up a minimal example already in a new project with only the essentials and only three scripts.
The first script is unimportant as it just calls the StartServer/StartClient methods on the NetworkManager, as well as using it's SceneManager to change scenes
The second script just contains a NetworkObject prefab, that it spawns for every connected and connecting client, to which it also gives ownership to. This logic runs inside the OnNetworkSpawn method, meaning that netcode should have run everything it needs beforehand.
The third one is also tested to be unimportant to the case, as it just changes the color of the SpriteRenderer depending on it's owner id.
I have created and registered two prefabs for both the player and player spawner scripts, and I have no trouble connecting via the MPPM package. Only when I change scenes to another one that also has the player spawner script, it throws "Invalid Destroy"-errors for the client on every network object. The weird part is that the scene with it's objects is visible for a single frame. I """fixed""" this issue by delaying the spawning of connected players by one frame, but this just doesn't seem right. Can someone please help me figure out if this is an issue with my setup or a bug in netcode?
TL;DR: I'm encountering an issue where when spawning objects directly after a scene change, the clients get "Invalid Destroy" errors, which does not happen for the host.
The first video (green editor) shows me not delaying one frame and the second one (gray editor) does
This is the script responsible for spawning, if you want to take a look at it
I've done some more experimenting with a heavier second scene and it seems to always work when I put off spawning by one frame using Invoke with a delay of 0 or waiting for the OnLoad(Event)Completed events
even with more clients
Hey,
I tried the VR Multiplayer Template, and it worked for me on Editor+Desktop.
Then I tried to change Transport and Relay settings to websockets. (secure=true in Relay) and use websockets both on Relay and Transport.
But once I set secure to true on Relay(needs that later for SSL connection), and/or switch to use websockets, it fails to connect.
In some cases I get an error that "player is already a member of the lobby", on others I get "join code not found".
Any idea or tips on how to make the VR Multiplayer Template to support websockets? Maybe I'm missing some settings? Couldn't figure it out from the docs.
(I want to run it on web. There are other changes I need to make, but no issues with them)
I'm using Unity 6000.0.23 and downloaded the template for it.
Thanks
You need to also make sure you set the Relay server data to use wss
https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo#Note_about_WebGL_support
Yes, done that as part of the iswebsocket in the RelayServerData. The API is a bit different than the docs.
public RelayServerData(string host, ushort port, byte[] allocationId, byte[] connectionData, byte[] hostConnectionData, byte[] key, bool isSecure, bool isWebSocket)
I set both isSecure and isWebSocket to true.
But if even one of them is true, it seems like the Relay/Lobby/Transport fail.
Can't figure what fails.
Does anyone know where I can find up-to-date documentation for using Unity's authentication service to authenticate with Oculus? I've done a lot of googling but the only resources I can find uses the deprecated Oculus Integration package. I'd also still like to be able to authenticate with an Oculus account when running the project in the editor (and I have no headset connected).
Does this no longer work?
https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-signin-oculus
This is the documentation I was taking a look at that uses the deprecated Oculus Integration package
Have you tried it with the latest Meta XR Core plugin? The namespaces might change but I would assume it's still a similar process.
hi, Im triying to make a game as a host but im having a problem
my host does not start(in editor at least)
this is the code, I am following this tutorial from codemonkey
š¬ Here is the Multiplayer Course! I really hope both of these FREE courses help you in your game dev journey! Hit the Like button!
š Course Website with Downloadable Project Files, FAQ https://cmonkey.co/freemultiplayercourse
š® Play the game on Steam! https://cmonkey.co/kitchenchaosmultiplayer
⤠IF you can afford it you can get the paid ad-free ...
Are you seeing any errors in the console? Make sure your AllocateRelay() is calling RelayService.Instance.CreateAllocationAsync(maxConnections)
and yes, i am doing this
now i am getting another error before that one
before initializing host
Hmm I tried adjusting my code and stuff and its still not really working, can you maybe help me out some more
CreateAllocationAsync() needs to be in a try catch block too in order to see any exceptions that might get thrown
You'll need to simplify things in order to see where it's breaking. First try moving a simple cube then move up from there
ill try more
yes
it is
I tried and the movement is being detected but its just not moving
Hello, can anyone tell me the correct way to handle this. I have used NetworkList before but its first time i am using it like this.
This giving me Null RReference error
I add value to this list in OnNetworkSpawn and in Server
[SerializeField] private Team[] teams;
[Serializable]
public class Team
{
public string teamName;
public Color teamColor;
public SpawnRange teamSpawnRange;
public NetworkList<ulong> teamMembersList;
}
private void Awake()
{
for (int i = 0; i < teams.Length; i++)
{
teams[i].teamMembersList = new NetworkList<ulong>();
}
}
I initialized it in Awake also
I also tried to do it in Constructor but same error
I would probably avoid putting a NetworkList inside of a class like that
I'm not sure that's supported
I guess you are right
Server Player movement
Actually I think as long as the parent class is a network behavior, it should still work. You just need to initialize the teams array.
I still wouldn't do it that way. Make Team a struct that implements inetworkserializable. And member list a Native Array/List
hey people
I need some help here š¦
right now, I am passing in the player name and leaderID
in the information that I need for the actual game
which is nicely working
now, I have a List<int> of each player's deck, which contains the ID for 50 cards
should I make it a network variable so I can pass it in from the LobbyRoom scene to my Game scene?
I want to create a small game that handle 8 - 12 players, anyone can tell me what the best multiplayer solution between Client Hosted and Distributed Authority ?
Hey, the same kind of game like Lethal Company and Lockdown protocol
But cheating is always possible even Distrtibuted Authority right ?
In both cases, I understand that both options are chargeable on the Unity side ?
If i use the multiplayer Relay or Distributed Authority
And i think its the same if i use Steam P2P with a bandwidth usage ?
let's wait for someone more savvy to come and answer that, don't wanna give u wrong information
Network variable should be a better use case for syncing your deck cards i think, but i dont know if you can share a networked variable value between multiples scenes š¤·
I think PlayerPrefs class is to share values between scene if i remember correctly
oof, I could make this object a Don'tDestroyOnLoad type thing
which will be fine
I will probably make a script just for that, to act as a bridge for the players information
and destroy it when it does it's job
You can do it like this too yeah š
there's so much Idk how to do tho š xD
@viral ether Don't post ChatGPT answers here and there's no off-topic either.
I dont understand this š¤
0.16$ for each player playing multiplayer on my game / month ?
Or 0.16$ for each player playing ~43000 minutes in multiplayer / month ?
average CCU. Not just each player that plays the game ever.
Meaning you remain within the free tier if your game averages 50 or less players connected concurrently throughout the month.
If you start averaging 51 concurrent players, that's 16 cents and so on for each additional average CCU.
Did you know what is the best solution about pricing between using Unity services or Steam P2P ? (Im using a game hosted solution)
No idea, really. Although, I've never really heard anyone say one is drastically a better deal than another. But I'm sure the pricing for each solution is public, so should be easy to compare.
What I can say is that Unity's free tiers are pretty generous, I don't know many people that go beyond them.
Distributed Authority free tier is a bit lower than Relay
Distributed is like each client own its game objects or something like that ?
Distributed authority is one possible network topology you can use for your multiplayer game.
Yeah that can be the reason
I will try the solution
On NGO i have a Network object, With a net transform & net RB using interpolate, the movement of this object is all controlled by the server. I need the client to be able to follow these objects without jitter. I'm currently using a simple cube for testing with the most simple transform matching script below however its clearly stuttering while following the physical objects controlled by the server Why is this? (The video is from a clients perspective, the cube is being controlled solely by the client, with only the position script below and a mesh renderer)
void Update()
{
transform.position = SteeringWheel.transform.position
}
Im soo confused surely the cube should move more smoothly than the Network Transforms? As this is the clients perspective and the cube is controlled by the client, yet somehow the boat objects are moving more smooth
That stuttering is fighting between the physics and the local transform. I believe physics update in FixedUpdate() then you are resetting the position in Update()
This doesnt make sense, the wooden boat is more smooth in fixed update, when compared to the transform position setting of the cube in the Update()
This issue does not occur in local play
Player and example cube are controlled clientside?
Yes they are controlled clientside, It seems that the transform position of the Network Transform objects is jittery, despite the movement of the objects being smooth due to interpolation, it doesnt make any sense, as surely what im seeing is smooth objects, so in theory i should be able to smoothly follow these objects
If you have a client-side object trying to follow a server-side controlled object, you have two sources of interpolation from different places. Naturally, they'll struggle to sync up and fight with each other.
That would be my guess.
Also as said above, FixedUpdate with an RB for the boat and just Update for the player introduces another potential layer of fighting.
You can fire up the debugger and step through that code one frame at a time to see exactly where the transform is stuttering
No interpolation for the cube, the cube is below, nothing to interfere with the movement
Notice the Green WireSphere is at the correct position, yet the cube isnt
How can this be possible if both functions use the exact same position?
I'm encountering a substantial delay when using the Unity 6 (6000.0.23f1) Distributed Authority sample (setup via the the Multiplayer Center). Between clicking "connect" on the sample UI and actually getting the default cube player prefab spawned it's over 10 seconds with a lot of time seemingly on QOS checks as shown here.
Is this expected when using Unity Services or is there a way to eliminate all the wasted time?
You can check the profiler to see what taking up the time but it's not the Qos calls. Those took less than half a second
hey, i've got the NGO stuff working but all of a sudden the network managers started shutting down when a remote client connects and the console doesn't say what's caused it, is there anything I can enable or add somewhere to find out what's causing it?
Hello! I'm new to networking, and I have this homework where i have to find a pre-made prefab game and attach multiplayer to it. I chose this Advanced FPS Horror Kit prefab, and I chose Mirror as the networking plugin. However I started watching the tutorials for it and immediately became confused. This is the player prefab from the Horror kit, it's got plenty of nested gameObjects. The parent in the prefab does have the network identity component, but its children dont see it for some reason. And as far as I understand, all of the scripts need to inherit from NetworkBehavior, because they do stuff like shooting guns and picking up objects. What am I doing wrong here?
looks like it was approval request taking forever, rebooting editor fixed
Who in their right mind would give out homework like that? You can't just attach multiplayer to an asset like that.
things are never as simple as "just add multiplayer", you need to build in tandem
I dunno, my mobile gamedev teacher
It's a semester project, we need to find a prefab game, choose a networking plugin and make multiplayer with the prefab, then attach a bunch of statistics services and show that it all works
ok so this issue is back again, seems like rebooting editor is just temp fix, anyone come across this before? i'm on MacOS so not sure if this is Mac specific thing
does it still happen when you turn off connection approval?
Heey, iam trying to switch a scene through NetworkSceneManager.Loadscene.
But the scene only switches for the host, not for the client. I tried it in all sorts of ways(ServerRpc, clienRpc) but the documentation states that the NetworkScenemanager automaticly syncs scenes if you change the scene after a client is connected. Anyone any idea?
Make sure you have scene Management enabled in the network manager
Yes done!:)
Still only loads the scene for the host
Are you seeing any errors on the clients? Also make sure the scene is in the build list
No errors seem to be happening, and the scene is setup in the build profile
In one way there was an error that SceneLoad should not be called from the client, but i fixed that with the server Rpc
And IsHost
Yea, only the host can call SceneLoad(). But it should definitely sync to all connected clients.
I hate my life, thanks anyway! Ill keep on digging:)
Can someone please review my websocket connection wrappers? Are there possibilities for race conditions/concurrency issues? Currently there are no issues found
https://gitlab.com/qiwik0805/clicker-game/-/blob/dev/MI-4/Assets/Scripts/Runtime/Services/WS/WebSocketConnectionService.cs?ref_type=heads
https://gitlab.com/qiwik0805/clicker-game/-/blob/dev/MI-4/Assets/Scripts/Runtime/Services/WS/WebSocketConnectionManager.cs?ref_type=heads
hi, sorry for late reply, yes this happens with it disabled, it was disabled by default on my project too
this is all i see in the logs
i've got my logs set to developer, tried both disabled/enabled client approval and it still happens, sometimes it works fine for a few tests and then all of a sudden stops, and sometimes just doesn't work off the bat
Are you using a VPN?
nope, if it helps in any way I'm using the multiplayer client feature in Unity 6
Do you mean Multiplayer Play Mode?
that's the one š
Try making a build and see if the same thing happens. The only issue with mppm that I'm aware of is when the clone windows don't open if the os language is not in English.
will give that a go shortly
Is there a free simple proximity chat asset or tutorial
So i have a problem with my project: Basically when i spawn ONLY the host no warnings appears in the console, but when i try to spawn another player, it gives me continues warning about the rigidbody being kinematic (which it isn't in both rigidbodys), here my script for movement, for reference: https://paste.ofcode.org/pM6H2nvu8P9gzTxERxPhy5
Vivox is free up to 5000 monthly users
how can i implement spatial sound
The docs are a bit of a mess but you can call JoinPositionalChannelAync()
https://docs.unity.com/ugs/en-us/manual/vivox-unity/manual/Unity/developer-guide/channels/positional-channels
thanks will look into it
Hey I donāt know where I should ask this: I having problem with vivox when mute then unmute later, my app will be crashed due to resource usage (iOS)
Immediately when unmute
Hey everyone! I'm starting a multiplayer project and everything seems to working except when I spawn in a client, they aren't able to move. It just jitters. Any ideas?
EDIT: I'm using Unity 6 and Netcode for GameObjects
hey y'all, quickj question. Is the recommended pattern to write your own sessionmanager logic or to use the baked in unity multiplayer widgets? I found the multiplayer widgets to be pretty inflexible, so I figured they were just there as informational, but i'm not seeing a massive amount of documentation around writing your own solution, anyone ahve thoughts?
edit: unity 6 and netcode for gameobjects
Yea the widgets are locked in at the moment. I talked with some of the devs over on the Netcode server and they said that they are looking into making them more extensible.
But no need to write your own session manager. You can hook into most of the events that widgets themselves do.
oh thanks for the response, yeah i've been banging my head against the wall cause i thought they were all packaged up together, but you're totally right
ah darn i remember why i didn't do it this way, all of the unity session stuff is stuck behind internal classes ><
Oh yea, you are not going to be able to make your own widgets at the moment. But there are public Session manager events you can hook into
oh, there are two classes literally called sessionmanager, one in the multiplayerwidgets and one in the multiplayerservices, and one is hyper internal and inaccessible and the other is totally public
thanks for the help @sharp axle
with unity netcode, and animations, would it be better to :
#1 Just fire the animation on the host system that moves a gameobject, and then have the animator component disabled on the other systems, and have them follow the host movement via network transforms?
or #2 run the animation on all systems at the exact same time with rpc methods?
The network animator handles syncing for you
https://docs-multiplayer.unity3d.com/netcode/current/components/networkanimator/
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.
oh, COOL! thanks, not sure why I didn't come across that.
Who knows what engine to use if I want to develop a game with rooms (in each 10 people) and there can be more than 100+ such rooms. That's very similar to Dead By Daylight, Amoung Us etc
For instance as I know photon PUN 2 isn't for MMO games but my game isn't so I wonder if it can provide what I want
Does PUN 2 has client auth not server?
Oh
Maybe netcode will be a better choice for that
Will you target mobile or WebGL?
For the games you describe, most solution will do fine, even PUN.
I'd recommend Fusion Shared Mode. It distributes the authority on all clients but is easy to work with and still gets great results.
Netcode's distributed authority is not yet final and relies on UGS services.
3D PC online game
I'm looking for a solution which provide:
- Server auth or shared mode (good sync and prevent hacking);
- Opportunity to host rooms (100+) with 10 players in each of them;
- Voice chat
Server auth or shared mode are quite different from one another so it makes sense to figure this out early on.
Shared mode is typically easier to do but not as precise as everyone runs a part of the simulation.
Fusion can do either. There will be Server Side plugins for Fusion Shared Mode at some point but that is not ready yet.
Running many of such sessions is not a problem with any solution and Voice can also be added to existing networking solutions in many ways.
This might be a starting point:
https://doc.photonengine.com/fusion/current/game-samples/fusion-impostor
It is in Host Mode however (so: Server Authority, Input sent to Host and State back, less prone to cheating).
This covers your target genre perfectly.
The Fusion Impostor demonstrates an approach on how to develop the coreloop of a social deduction game for up to 8 players, as well as how to integrat
I am using Relay + Lobby for my multiplayer and connecting for the first time works no problem. I queue up, get into a game and can play. Then when I attempt to search a second time, it just says, connected to client and it's just me in the game. I assume I'm not disposing of something - I already checked GetJoinedLobbies and nothing is pulling up there. What am I missing?
I call this upon clicking the button to leave the game
public async void LeaveLobbies()
{
try
{
NetworkManager.Singleton.Shutdown();
Debug.Log("Leaving lobbies");
var lobbyIds = await LobbyService.Instance.GetJoinedLobbiesAsync();
foreach(var lobbyId in lobbyIds)
{
string playerId = AuthenticationService.Instance.PlayerId;
Debug.Log($"Removing player {playerId} from lobby {lobbyId}");
await LobbyService.Instance.RemovePlayerAsync("lobbyId", playerId);
}
}
catch (LobbyServiceException e)
{
Debug.Log(e);
}
}
Is there a tutorial or documentation for a NGO inventory system
That would definitely remove you from all lobbies
When I click to start a new game, it puts me into a game with no one else. What would be causing me to still be connected to something?
There are loads of different ways of doing inventory. Most are not NGO specific. You can use a cloud service like Unity Economy or Cloud Save. LootLocker is another service.
depends on how your new game is setup to start
Too much for the text limit - but it's calling this and opening an empty room on the second attempt.
Is it because the Lobby has a non-unique name? "Useless Lobby Name"?
You would get an error message if the lobby still existed. That code will create a new empty lobby
Right, and it does, but for this one, it doesn't wait for a second player, it just creates it and goes.
that is what its supposed to
But on the first one, it doesn't go until a second player has joined.
And I can close the app and every single time I try to do it the first time it works perfectly, but if I try to start a second game ever, this happens.
weird. none of the code you posted waits for a second player. No idea why it would.
That's a good point. I must be handling that elsewhere. I'll check real quick.
Oh yeah, towards the bottom:
NetworkManager.Singleton.StartHost();
NetworkManager.Singleton.OnClientConnectedCallback += ClientConnected;
Then when the second player connects:
private void ClientConnected(ulong clientId)
{
Debug.Log("Client connected!");
NetworkManager.Singleton.SceneManager.LoadScene("GameScene", LoadSceneMode.Single);
}
make sure you are unsubscribing from OnClientConnectedCallback that would be causing your issue
Should I unsubscribe as soon as I hit ClientConnected? Like do this after the debug statement?
NetworkManager.Singleton.OnClientConnectedCallback -= ClientConnected;
How exactly does it cause the issue? Not arguing, just curious.
I have a question on what's best for me and for my project:
I want to create a casual and social single player and multiplayer, where people just login to chill, talk and interact with the environment. I'm developing a world for the fans (likely no more than like 5 people lol) of a cartoon I'm working on where the world is like a gallery/mock gift shop (no real life purchase) of the cartoon where fans could get on, either offline or online to hangout with other fans.
I'm using the Multiplayer Center in Unity 6 to see the recommended specs. Is "Async, Idle, Hyper Casual, Puzzle" best for me? Also what is the recommended Hosting Model? I'm sort of new to multiplayer for the exception of trying Photon Fusion but all of it was confusing for me and never got to finish due to my lack of understanding.
Please and thank you
If you are still subbed to it then the host client connection will trigger it
It more depends on your budget really. Having a dedicated server running 24/7 can get expensive. Player hosted lobbies with a Relay service would be cheaper but limits your player counts per game session.
Thank you, I appreciate it. Will I be able to change it from p2p to lobby and vice versa once I already start?
The hosting model has Cloud Code recommended but I don't know if that aligns with what I'm trying to do.
Yea. its not too hard to port between relay hosted and dedicated servers.
Cloud Code would be more for asynchronous multiplayer. Think mobile games like clash of clans or words with friends
Thank you! This helped a lot!
Using Vivox on the Quest, whenever I try to record a video, I can't hear the other players in the recording, anyone know why this could be happening?
I'm not too familiar with Vivox but sounds like you need to use an Audio Tap to pipe it through the mixer
https://docs.unity.com/ugs/en-us/manual/vivox-unity/manual/Unity/developer-guide/audio-taps/use-audio-taps
Alright I'll try that out, thank you!
So my client server has been experiencing framerate freezes when certain server RPCs are being handled, and I was wondering how realistic/feasible it would be with the dedicated server package to have the game's host instead launch (from within the game) a dedicated server and connect as a client instead
for a bit more background info on one of the problematic RPCs: it requests from the server to decide what action each npc will take after the player has taken theirs, sending back to that client only the id of the action and an array of targets. the freezing is caused due to the complexity how the choice is made, and already includes coroutines to minimize the impact
You should probably fix the function instead. Something is really wrong if your coroutines are freezing up
the coroutines are not freezing, its justdifficult and messy figuring out everywhere i would need to yield and am looking for an alternative to making it burst compatible. not saying there arent ways to improve the process, but it is inherently a time consuming one
How do you network AI FSM soldiers to have accurate animations across all clients?
My AI's transform is perfectly correct using Netcode for Game Objects 1.9.1.
But the animations even using networkanimator are innaccurate so the AI on one screen shoots and kills the player before it even aims at them but on the server it was aiming at them seconds before.
I sent logic updates to clients from the FSM with no computations but it is still wonky - and when the AI dies and all rigidbodies become kinematic so it can have an accurate ragdoll, it bugs out on the clients
Your AI FSM should only be running on the server/host. The network Animator and Transform should be keeping everything else in sync.
any ideas for networked 3d dungeon generator
The basic idea would be that you send the generator seed to the other client in a RPC or NetworkVariable then have the client generate the scenes locally
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/using-networkscenemanager/#dynamically-generated-scenes
Netcode for GameObjects Integrated Scene Management
Hey folks, I'm creating my own NetworkVariable by creating a class extending INetworkSerializable, which contains a public int, bool and a vec3 and quaternion. I've implemented the NetworkSerialize() method, and in another script I'm declaring it as such NetworkVariable<MyCustomClass>; however, Unity is complaining that "MyCustomClass: Managed type in NetworkVariable must implement IEquatable<MyCustomClass>". How do I proceed, just by making MyCustomClass extend 'INetworkSerializable, IEquatable<MyCustomClass>' or have I setup the NetworkVariable wrong?
Canāt say whatās wrong for sure but just generally speaking, if your class doesnāt have any methods make it a struct. Also if your quaternion is for rotation just use a Vector3.
IEquatable I believe is used in NetworkLists.
Hey everyone š I've followed this simple video (3m) to get started into Networking code
I have then installed Multiplayer Play Mode package to check if it was working
However I manage to spawn the Host thanks to NetworkManager but then I cannot seem to create new clients, anyone has an idea?
Unity Multiplayer, using Netcode For GameObjects quickly explained to show how easy it is to get started with.
If you want to see the inspector in MPPM you can click Layouts in the top right corner after you click Play. You could also add buttons in the scene to start client/host
If you want to see the inspector in MPPM you can click Layouts in the top right corner after you click Play
Thanks! That's what I was looking for (it did work š )
Meaning I was starting to create the buttons to the Scene but the button is not working (doesn't register clicks yet, Idk why)
Hello, I have a problem with Multiplayer. If start two projects on my pc, the multiplayer works, but if I send it to a friend in another Network, it doesnt work.
using UnityEngine;
using Unity.Netcode;
using UnityEngine.UI;
using Unity.Netcode.Transports.UTP;
using System.Net;
public class MainMenu : MonoBehaviour
{
public InputField ipAddressInput;
private void OnEnable()
{
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
}
private void OnDisable()
{
NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnected;
}
public void ConnectHost()
{
string ipAddress = ipAddressInput.text; // Get the IP address from the InputField
Debug.Log($"Attempting to connect to {ipAddress}...");
// Set the address for the Unity Transport to connect to the specified IP address
var transport = NetworkManager.Singleton.GetComponent<UnityTransport>();
transport.SetConnectionData(ipAddress, 7777); // Assuming you are using port 7777
// Start the client connection
NetworkManager.Singleton.StartClient();
gameObject.SetActive(false);
Debug.Log("Connected");
}
public void CreateHost()
{
var transport = NetworkManager.Singleton.GetComponent<UnityTransport>();
transport.SetConnectionData("0.0.0.0", 7777); // Host on all available IPs on port 7777
NetworkManager.Singleton.StartHost();
Debug.Log("Host started."); // Debug output
string hostIp = GetLocalIPAddress();
Debug.Log($"Host started on IP: {hostIp}"); // Ausgabe der Host-IP-Adresse
gameObject.SetActive(false);
}
private string GetLocalIPAddress()
{
// Ermittelt die lokale IP-Adresse
string localIP = "";
foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) // Nur IPv4
{
localIP = ip.ToString();
break;
}
}
return localIP;
}
public void QuitGame()
{
Application.Quit();
}
}```
You'll need to use the Relay Service if you are not on the same network
Then I will directly see other players?
Once you both connect to the same relay session , yes
Do you have an example or tutorial?
tank you very much
The Multiplayer Services and Widgets packages make it super easy as well
Hi, I was wondering if I could get a bit more clarification when it comes to netcode. I'm trying to make a simple hide n seek game and at the moment I've used [Rpc(SendTo.Everyone)] above the methods to interact with a hiding space and whenever I interact with a hiding spot the debug messages appear for both clients and I get an error message on client2 (The one that's not hiding or pressing the interact button) that makes it seem like they're trying to interact with something not there. Is it because [Rpc(SendTo.Everyone)] makes the method get called to everyone? Or is this just how it works?
Yes, this will make the function run on every client and the server.
Figured, so if I wanted to interact with a door/locker/chest/etc where a gameobject changes in some type of way be a sprite being changed or a door/chest being opened or used. Which would I send to? Server?
Depends on what you actually want to do. An animation trigger or spawning a new object can be sent just to the server.
I want a player to be able to hide in a locker and the sprite of the locker goes from open to close. Other players can't hide in it but the seeker can open to reveal them. I already have that set, its just making it so that the method isnt called to everyone.
Hi, i'm messing around with Distributed Authority, why i'm having this error even tho i'm checking if the user has authority and is owner before writing to this network variable?
using Unity.Netcode;
using UnityEngine;
public class EnemySpawner : NetworkBehaviour
{
[SerializeField] private GameObject _enemyPrefab;
[SerializeField] private float _defaultSpawnTime;
[SerializeField] private NetworkVariable<float> _curSpawnTime = new(readPerm: NetworkVariableReadPermission.Everyone, writePerm: NetworkVariableWritePermission.Owner);
private void Update()
{
if (!HasAuthority || !IsOwner)
return;
_curSpawnTime.Value -= Time.deltaTime;
if(_curSpawnTime.Value <= 0f)
{
SpawnEnemy();
_curSpawnTime.Value = _defaultSpawnTime;
}
}
private void SpawnEnemy()
{
var instance = Instantiate(_enemyPrefab, transform.position, Quaternion.identity);
var instanceNetworkObject = instance.GetComponent<NetworkObject>();
instanceNetworkObject.Spawn();
}
}
The error itself doesn't change anything in the gameplay, but it's annoying
This happens whenever i'm the session owner, leave (the session owner goes to someone else), and join again
From what i see it's giving me this error whenever i disconnect from the game
when trying to test my lobbies after making a build I keep getting this error when trying to join. Would anyone know the fix or a way to make your clones have unique ids?
Unity.Services.Lobbies.LobbyServiceException: player is already a member of the lobby
I think a good solution would be to generate a random profile ID whenever the user opens the game for the first time and then save it locally or on cloud (steam and so on)
Something like
var profileName = Guid.NewGuid().ToString();
// Save it to your cloud or locally, re-use
For testing on editor with multiplayer play mode you can just pass in a new one every time you connect
for unitys relay service would you know where i could find the place to set the profileName?
You call the async method MultiplayerService.Instance.CreateOrJoinSessionAsync(string sessionId, SessionOptions sessionOptions);, here is a example that i'm using (i basically implemented upon existing NGO samples):
public async Task CreateOrJoinSessionAsync(string sessionName, string profileName)
{
if (string.IsNullOrEmpty(profileName) || string.IsNullOrEmpty(sessionName))
{
Debug.LogError("Please provide a player and session name, to login.");
return;
}
_state = ConnectionState.Connecting;
ConnectionStateChanged?.Invoke(ConnectionState.Connecting);
try
{
if (!AuthenticationService.Instance.IsSignedIn)
{
AuthenticationService.Instance.SwitchProfile(profileName);
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
var options = new SessionOptions()
{
Name = sessionName,
MaxPlayers = _maxPlayers
}.WithDistributedAuthorityNetwork();
_session = await MultiplayerService.Instance.CreateOrJoinSessionAsync(sessionName, options);
_state = ConnectionState.Connected;
ConnectionStateChanged?.Invoke(ConnectionState.Connected);
}
catch (Exception e)
{
_state = ConnectionState.Disconnected;
ConnectionStateChanged?.Invoke(ConnectionState.Disconnected);
Debug.LogException(e);
}
}
Then i can connect by saying:
try
{
await CreateOrJoinSessionAsync("YOUR_SESSION_ID_HERE", "YOUR_PROFILE_NAME_HERE");
}
catch (Exception e)
{
Debug.LogException(e);
}
ok gotcha i will try to implement this into my code thanks for the help
You should probably use OnNetworkSpawn() to start a Spawn coroutine. HasAuthority is not getting updated until this object has spawned.
Hi, I'm trying to make a server-authoritative variable, a cooldown. Only the server is allowed to change cooldown. Is this the way to go about it?
This is using Mirror
The script aims to spawn an object and apply a force to it. Only the server should be able to run this.
Are commands run with respect to the client or the server?
There is not really a reason to make cool down a network variable. Unless you want to display it in some kind of UI
its more for anticheat
also other players should be able to see when this player's ability is on cooldown
I can't use a coroutine due to the way the spawner will work, instead i made a simple bool based on your comment, it worked like a charm, thank you!
Now i'm having a little trouble on the distributed authority of enemies, what i want is that the player who takes the ownership of the session also takes the authority of all enemies, however there is this situation:
- Player 1 is the session owner, while he is the session owner a enemy is spawned
- Player 1 quits, player 2 gets the session/enemies ownership, everything is working like it should
- Player 1 re-joins, it gets the ownership of the enemies it spawned in the past instead of keeping to the current session owner
Here is a example, you can see ownership of objects based on their color:
Think i managed to solve it, i just dont know if its the correct way
I believe setting the ownership permissions to Distributable and RequestRequired will prevent the automatic transfer back
I've set the ownership of the networkobject to "Transferable" instead of "Distributed", listened to OnSessionOwnerPromoted event, if i'm the new session owner i request the ownership of all the enemies
public override void OnNetworkSpawn()
{
_isSpawned = true;
NetworkManager.Singleton.OnSessionOwnerPromoted += OnSessionOwnerPromoted;
}
public override void OnNetworkDespawn()
{
_isSpawned = false;
NetworkManager.Singleton.OnSessionOwnerPromoted -= OnSessionOwnerPromoted;
}
private void OnSessionOwnerPromoted(ulong sessionOwnerPromoted)
{
if (sessionOwnerPromoted != NetworkManager.Singleton.LocalClientId)
return;
foreach (var spawnedEnemy in FindObjectsByType<EnemyFollow>(FindObjectsInactive.Exclude, FindObjectsSortMode.None))
{
spawnedEnemy.NetworkObject.RequestOwnership();
}
}
(the findobjectsbytype is temporary just for testing purposes)
It makes a lot of sense, but for some reason i have the same problem when doing this, idk if it's some other setting
I guess the automatic distribution overrides the request requirement. Could be a bug as well. It is kinda weird that they let you pick permissions that are not compatible with each other. The way you are doing it is probably the correct way for what you want
Thanks
Is there any place i can check for the definition of those icons and numbers? there isn't any kind of tooltip or anything like that
I can't find it on the docs

Those icons are added by components. I don't remember about the numbers offhand
So I was following a tutorial on Youtube and after finishing the MatchMaker Script I got over 40 errors for no reason and I can't really know how to solve the problem
Well at the start I got a problem with this line
public SyncListString matchIDs = new SyncListString();
but I managed to fix it by adding this
[System.Serializable]
public class SyncListString : SyncList<string> { }
after implementing that these whole errors popped up
I'm not too familiar with Mirror but it probably can not sync strings try one of the fixedstring types
if I do execute ClientRpc on serverside player object then this RPC will be sent only to that owner of this object?
or in old unet ways I need to specify clientid in clientrpcparams ( old TargetRpc )
I don't think you should be making a class that inherits from SyncList, it should just be declared as a variable inside of a NetworkBehaviour.
public class SyncListExample : NetworkBehaviour
{
public SyncList<string> namesList = new SyncList<string>();
}
I have already done that before and it worked! Thanks btw :)
When I host the game everything works fine but the canvas isn't getting enabled?
{
if(success)
{
lobbyCanvas.enabled = true;
}
else
{
joinMatchInput.interactable = true;
joinButton.interactable = true;
hostButton.interactable = true;
}
}```
``` [Command]
void CmdHostGame(string _matchID)
{
matchID = _matchID;
if(MatchMaker.instance.HostGame(_matchID, gameObject))
{
Debug.Log("Game hosted success");
networkMatchChecker.matchId = _matchID.ToGuid();
TargetHostGame(true, _matchID);
}
else
{
Debug.Log("Game host didnt success");
TargetHostGame(false, _matchID);
}
}
[TargetRpc]
void TargetHostGame(bool success, string _matchID)
{
UILobby.instance.HostSucces(success);
}
}```
even the game hosted success is popping up
in this case I should not use dispose?
iirc no, the reader is owned by the serializer being passed in, so you should expect it to be disposed elsewhere
I believe you would only need to dispose if you are using NativeArray/List
buffer readers/writers can allocate native memory on their own, but unless you allocate them youself NGO usually does it for you
Hi. I am using NFGO 1.11.0, since the new v2 is only compatible with unity 6, and i am still on the LTS. The problem i am encountering, is when i set the transfrom position of a player object (i am using the non-server authoritative networktransform), the position reverts to what it was before. This happens on the player object that is owned by the host, that i set the position of to some x spawn point, and it still reverts to what it was before i set it. I tried to wait 0.15 seconds to set the position, and it still reverts, but less frequently. The player objects are already placed in scene, and when a player joins, ownership of the object is transferred to the player, and the player itself sets its own spawn position, that gets reverted. I don't think this is caused by ownership issues, since even if the host sets its own spawn point in Start() or first Update() (or 0.15 seconds after Start), it still reverts. I can share any code if needed
hi chat
I have this struct for player data
void Start()
{
PlayerData = CurrentPlayerData;
CameraControl.Instance.SetCameraIndex(CurrentPlayerData.IsHost);
if (IsServer)
{
SetPlayerDataOnServer();
}
else
{
RequestSetOpponentDataServerRpc();
}
}
[ServerRpc(RequireOwnership = false)]
void RequestSetOpponentDataServerRpc(ServerRpcParams rpcParams = default)
{
SetOpponentDataClientRpc(CurrentPlayerData, rpcParams.Receive.SenderClientId);
}
[ClientRpc]
void SetOpponentDataClientRpc(PlayerData data, ulong clientId)
{
if (NetworkManager.Singleton.LocalClientId == clientId)
{
OpponentData = data;
}
}
void SetPlayerDataOnServer()
{
foreach (var client in NetworkManager.Singleton.ConnectedClientsList)
{
SetOpponentDataClientRpc(CurrentPlayerData, client.ClientId);
}
}```
I'm trying to pass it in on a serverrpc and clientrpc
however, I think it needs to be serialized, but "System.Serializable" did not do the trick...
the list there might make my life complicated... any tip?
ChatGPT gave me this solution to serialize it, but it's kinda messy I assume there are better ways [Thread to not flood the chat]
Hi everyone,
I'm developing a VR multiplayer application using Netcode for GameObjects with two Quest headsets, and I'm running into a weird synchronization issue.
Current behavior:
- Headset 1 can see its own position correctly
- Headset 2 can see Headset 1's position
- BUT: Headset 2 cannot see its own position
- AND: Headset 1 cannot see Headset 2's position
The strange part:
- Basic object synchronization works perfectly (when Headset 2 moves a cube, Headset 1 sees it and vice versa)
- Debug info always shows only 1 player (Player 1)
- Even on Headset 2, it shows "Total Players: 1" and "List of IDs: 0" (Player 1's ID)
My setup:
- NetworkObject component on XR Origin (XR Rig) with following settings:
- Synchronize Transform ā
- Active Scene Synchronization ā
- Scene Migration Synchronization ā
- Spawn With Observer ā
- Auto Object Parent Sync ā
- NetworkedHeadTracker script attached with NetworkVariable
I'm trying to display each player's position in a text UI element at the top of the screen. Despite the object synchronization working fine, it seems like there's an issue with player discovery or registration.
Has anyone encountered something similar? Any ideas what might be causing this or how to fix it?
Thanks in advance!
Here is how my code look like (2 files (100 lines of code in total))
Hi. I searched more online for my issue, and all solutions say to override NetworkTransform and set the spawn position with OnNetworkSpawned, but since all of my objects are already spawned when the scene is loaded, i can't do that. I will try writing my own position synchronization solution until i find a better solution for this.
After testing more, i found out that CharacterController was causing my issues, and this is not related to NetworkTransform at all. Other people have also been having issues with CharacterController resetting their transform, and that is where this issue comes from. If anybody else is having the same issue, i hope this helps.
Edit: the fix was to disable the CC temporarily, set the transform, then re-enable it
Hello. I am using a networkvariable to sync a shape. When i join directly after starting the server everythings fine. But when i change the shape/networkvarible on the host and then try to connect a client i am getting an InvalidOperationException: Nullable object must have a value Error on line 2040 on the NetworkObject. The IsSceneObject property seems to be null. Any ideas?
What type is the network variable? It shouldn't be able to be null. Or you would need custom Serialization to handle a null value.
Hello. The networkvariable is an integer that is initially 0.
Guys i got the multiplayer working with photon fusion. Everything is working well. But the car movement is not smooth. Its a bit jittery. Can anyone please tell me how to fix it. Thanks in advance
You've got something else going on there. Is this object a child of another Network Object?
No. The script with the network variable is on a player prefab (that has a network objectcomponent) that gets instantiated after connecting. The weird thing is it only happens when i change the network variable before i try to connect a client.
Question about Vivox
Does anyone have any issues when trying to create a Participant Tap when the Participant joins the channel? I'm trying to do exactly that (like this participant.CreateVivoxParticipantTap();), however it doesn't create the Participant Tap, and yes, I know that Taps can't be created on the local player
I'm trying to broadcast data between Android devices, so far I tried https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery, wrote my own UDP broadcast, and found some code on unity forums none worked, the sending part works I can receive data sent from android devices but not receiving the data on android, So far I tried adding MULTICAST permission andĀ acquiring multicastLock in Unity through Java calls and adding internet permission but nothing seems to work.
@tulip sky If you have a solution, post it here, don't spam cryptic messages to DM you
You can create a thread and post there.
Is there a good tutorial that goes over how I properly make movement in a server authoritative game with predicting it on the clientside and rubberbanding back if discrepancies are detected?
Still looking for a solution
There are some tools described here https://docs-multiplayer.unity3d.com/netcode/current/learn/dealing-with-latency/#client-side-prediction
Can also ask around on the dedicated Unity networking server, it's in the pins.
If you are using NGO, check out Client anticipation and its Sample
thank youu
Its abit hard to understand how NetworkVariable works.. but i think im getting it. Just to confirm whenever you wanted to change NetworkVariable's value you have to send a server rpc?
Only if the server has write permissions. You can set them to have owner write permissions so the owner of the object can set its own values.
But by default its write permission is set to server?
Neat thank you guys
Having an issue where I have a NetworkObject on the parent, and then ClientNetworkTransform on both the parent and a child object. On the host client, everything stays good. on the 2nd client, the child transform scale x/y/z changes as soon as the network connects!
It takes the scale of the parent object, and appends the last two digits of that to the child object's original scale, changing the size of the child object!!? so wierd...
original: parent- 1.17 child - 0.01
after network connect: parent - 1.17 child - 0.0117
What version of NGO are you using?
Hi I'm getting the error
Unity.Netcode.Editor.CodeGen.NetworkBehaviourILPP: Assets\PlayerController.cs(96,13): error - Rpc method must end with 'Rpc' suffix!
when the code clearly is named as such
[Rpc(SendTo.Server)] void CastSpellRpc(int spellNumber){ unitStats.Cast(spellNumber); }
I also get the same error (albiet for ServerRpc) when changing it to use [ServerRpc]
one oddity is also when i double click the error it opens an empty version of my script and when i close it it asks if i want to save, but when i remove the RPC line and force a random error, cdouble clicking opens the file properly
in fact I've just saved the file it opens and its now creating and referencing / Assets (notice the space)
when i remove the RPC line from the original it goes back to working fine?
If you already tried restarting the editor, I would do a full reimport of the Library folder
Try updating to 1.11. There were some fixes to parented network transforms
package manager not showing any updates for it. is that a beta version or something?
Itās a normal release. Recent versions take a bit to be listed on the Registry. Just add by name and specify the version number.
If you go to version history, the new versions should show up
doesn't appear so...
I'm on unity 6. If you hit other versions there they show up. If not you can add the package by name by clicking on the + in the top left corner and specifying the version
Do you guys know why this isn't working when I grab an object and call these methods on it?
// Call this method to request ownership transfer
[Rpc(SendTo.Server)]
public void RequestOwnershipServerRpc(ulong clientId)
{
// Change ownership on the server
ChangeOwnershipClientRpc(clientId);
}
[Rpc(SendTo.ClientsAndHost)]
void ChangeOwnershipClientRpc(ulong clientId)
{
GetComponent<NetworkObject>().ChangeOwnership(clientId);
}
I'm using this line when calling it:
objectGrabbed.GetComponentInParent<Item>().RequestOwnershipServerRpc(OwnerClientId);
I get the "Only a server can change ownership" error message
How can I make the player able to host a game and when he host a text shows the code of the lobby, then the client be able to join with that code? (using mirror)
Exactly what the error message says - only the server can change ownership. Youāre making the ownership change call inside of a ClientRPC.
You can use Unity Lobby or other similar services
https://docs.unity.com/ugs/en-us/manual/lobby/manual/unity-lobby-service
that's actaully pretty good
Thanks man
Right, that makes sense. However, when I change it to be in the ServerRpc call, I get the same thing.
// Call this method to request ownership transfer
[Rpc(SendTo.Server)]
public void RequestOwnershipServerRpc(ulong clientId)
{
// Change ownership on the server
GetComponent<NetworkObject>().ChangeOwnership(clientId);
//ChangeOwnershipClientRpc(clientId);
}
Idk if it matters, but I have the network transform a uthority mode as "Owner"
Iāve been using mirror for multiplayer but Iāve seen some of the things Unity has been doing recently and have been wandering if I should change over to using Unity for it. Should I do this and if so how easy or hard would it be to switch everything over
They're quite similar in terms of general syntax, would be one of the easiest ports you could do most likely.
UNet is deprecated and no longer supported. Follow this guide to migrate from UNet to Netcode for GameObjects. If you need help, contact us in the Unity Multiplayer Networking Discord.
Should I do it though. I do know they are very similar in terms of syntax. What about the components. Are they also similar?
That's entirely up to you. What one you like working with, what one works better for your project, etc.
If you value ease of integration with other Unity Services like Auth, Lobby, Relay, etc. and like the new features NGO is coming out with, then yeah, I'd probably say it's worth the switch.
Yes the components are also very similar.
Ok. Thanks
You should not be getting the same error message with this code.
But I am š¢ lol
If the client is still running that server RPC then you have something else wrong. Make sure that script is a network behavior
Hi I'm using Unity's Multiplayer Playmode however I'm unable to resize player 2's window horizontally. How do I resize the window?
Oh, good call! It wasn't a NetworkBehavior script, so that's why it wasn't working. Thank you!!!!!!
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 0, but that trigger was not received within within 1 second(s).
Why do i receive this message on console whenever i try to interact with something on the client? It never gave me problems but now it is giving me problems out of nowhere
Usually I see that when you send an RPC before OnNetworkSpawn() or in ClientConnectionCallback
thanks for the help, i'll try search on the code something like that
Hey you guys, I got this error when sending an RPC in Netcode for Entities. How do I determine when the handshake approval is complete?
[ServerWorld] Cannot send non-approval RPC 'Unity.Collections.NativeText.ReadOnly' to Entity(786:3) as NetworkConnection[id1,v1] is in state Handshake! Wait for handshake and approval to complete!
Depends on if you are using Connection Approval for not. But there are Connection Events
https://docs.unity3d.com/Packages/com.unity.netcode@1.3/manual/network-connection.html#netcodeconnectionevents-on-the-server
Thanks! very useful
Hi, anybody familiar with using NGO (with SSL websockets encryption enabled) and any tips for reducing ping? I can't seem to get anything under 200ms RTT and that's using my own servers in my region?
Is it just downside of using TCP websockets to have such high ping in NGO rather than UDP?
The transport type has little to do with the ping times. TCP does have more overhead and resending packets can increase latency.
Hmm might just be the servers Iām using. Would you recommend a certain cloud provider other than UGS? Amazon Gamelift looks reasonable?
Do you guys have any recommendations or tutorials for how to get my multiplayer game set up to build and play with friends without using stuff such as Relay? I'm using Netcode for GameObjects, but I don't want to be chained to Unity's paid stuff if I don't have to.
Edit: All the functionality is working and set up. I'm just looking to build it now and get friends and other players to be able to play it
Use tunneling service
Such as ngrok (tcp only)
playit.gg
Or hamachi (not recommended)
And relay is free at certain limit
Yeah I'd rather do something on my own though. So you're saying there is no other way than a 3rd party app for people to play my game?
You can either have your players set up port forwarding or roll your own relay server
its the way traditional games works too
like terraria/minecraft, people were using 3rd party service to play with their friends
Relayās free tier limits are very generous. Itās impossible to go over the limit if youāre just testing with friends. You wouldnāt even come close to it.
And it would be built in to your game with a relative amount of ease. So it would take you little time to set up and means nobody has to download anything extra when wanting to play your game.
Fishnet
huh
FishNet is a networking solution to code multiplayer games. He's looking for a connectivity solution/service that allows him to play his already coded game (with NGO) over the internet with others.
NGO is far better than fishnet, especially now that NGO has host migration š„
Hi, I'm currently having an issue with netcode for gameobjects where If i destroy the player objects spawned automatically that client will stop syncing all other gameobjects. Everything functions normally for any other client connected.
void Kill()
{
GameObject camera = GameObject.FindGameObjectWithTag("MainCamera");
Vector3 cameraPosition = camera.transform.position;
Quaternion cameraRotation = camera.transform.rotation;
SpawnSpectatorClientRpc(cameraPosition, cameraRotation);
NetworkObject networkObject = gameObject.GetComponent<NetworkObject>();
networkObject.Despawn();
}
[ClientRpc]
void SpawnSpectatorClientRpc(Vector3 position, Quaternion rotation)
{
if (!IsOwner) return;
Instantiate(spectatorPref, position, rotation);
}
If I don't destroy the player object, everything stays synced.
The Player object shouldn't have any effect on the other network objects. Do you have anything else happening in OnDestroy() on the player object?
no, I have nothing
Im losing my mind trying to figure this out
Everything on the player
the changes in SpawnSpectator are just me trying a bunch of things dont worry about the mismatch
Only the host/server can despawn network objects. That could be throwing an exception
thats what i was saying here
I was just covering my bases
despawning on the server removes the player object on all clients
throws no errors
and just stops syncing on the client that had their player removed
with this code
void Kill()
{
GameObject camera = GameObject.FindGameObjectWithTag("MainCamera");
Vector3 cameraPosition = camera.transform.position;
Quaternion cameraRotation = camera.transform.rotation;
SpawnSpectatorClientRpc(cameraPosition, cameraRotation);
// SceneManager.LoadScene("StartMenu", LoadSceneMode.Additive);
NetworkObject networkObject = gameObject.GetComponent<NetworkObject>();
networkObject.Despawn();
}
[ClientRpc]
void SpawnSpectatorClientRpc(Vector3 position, Quaternion rotation)
{
if (!IsOwner) return;
Instantiate(spectatorPref, position, rotation);
}
Yeah I've used FishNet before and loved it. Try NGO this time and I guess we'll see how things go. Similar to me so far.
Helloo everyone, I don't know why car network object just spawned on host and on client it not spawned,
It's strange, because follow loop it should spawn more than 1 car when load scene done, but runner.spawn just spawn one car with input authority of player 1 (host) and the second car not spawned with input authority of player 2 (client)
here is my script
this seems almost like photon fusion if it is then thats prob a bug with your spawning script as someone said "if your spawning script doesnt spawn it for the client but the player spawns that means your code must be broken"
AnticipatedNetworkTransform.AnticipateMove() Does this line alone handle client and server or do I still need to send a ServerRPC for the server to check that the new position is correct?
That is only for the client side. You still need to send the inputs to the server in a Move RPC
Check out the Anticipation Sample
Thank you for replying to me, yes it's photon fusion, I think I can know the problem come from my game object had attached rigidbody, but I just used network transform not network rigidbody. I'm going to test it again to see it right or not
ah
Has anyone ever tried using the Multiplayer play mode ? It crashes when I try activating a second player. Its a fresh URP project
Image
What version of the Editor and MPPM are you using?
I tried with botg 6000.0.16f1 and the last stable release, tried both 1.2.2 and I think 1.3.1? can't recall
Whats the build platform? I haven't had any issues with the latest versions
Windows 11 Education 23H2
make sure to submit that bug report
Hello, I'm making a game where each player has a 'Character' object that has about 300 states. Their usage is rare. Can someone tell me please which approach is more efficient and why? Approach 1: Each client has a local 'Character' object, and the server has all the players' characters stored locally. Decisions are made on the server based on the data from the local characters on the server. Updates are sent to the players via ClientRPC to refresh the data. Approach 2: Each state/variable in the character is a NetworkVariable. (Decisions are still made by the server, etc., but the server no longer holds a local copy of all the characters).
Anyone know what's going on with NetworkManager.OnReanticipate? The documentation claims that the delegate should accept three parameters. However the delegate type provided only provides the round trip time (third parameter from the comment). Is this a bug / oversight?
(this is from Netcode for GameObjects 2.0.0)
The comment there (and API docs) are wrong/outdated.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/client-anticipation/#global-onreanticipate
Client anticipation is only relevant for games using a client-server topology.
Thank you.
hi all, im new to networking, and im getting a warning that slightly confusing.
this is the error i recieve
[Netcode] [Deferred OnSpawn] Messages were received for a trigger of type NetworkTransformMessage associated with id (77), but the NetworkObject was not received within the timeout period 10 second(s)
i am spawning a projectile and giving it ownership using this code.
[ServerRpc]
private void OnFireShellServerRPC()
{
OnFireShell();
}
void OnFireShell()
{
NetworkObject newProjectile = Instantiate(projectile, firePoint.position, firePoint.rotation).GetComponent<NetworkObject>();
newProjectile.GetComponent<NetworkObject>().SpawnWithOwnership(OwnerClientId);
}
void Fire()
{
if(!IsOwner)
{
return;
}
if(IsServer)
{
OnFireShell();
}
else
{
OnFireShellServerRPC();
}
}
i am despawning it with this code.
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
rb.AddForce(transform.forward * projectileSpeed, ForceMode.Impulse);
StartCoroutine(DespawnAfterTime());
}
IEnumerator DespawnAfterTime()
{
yield return new WaitForSeconds(timeBeforeDespawn);
DespawnProjectile();
}
protected virtual void DespawnProjectile()
{
if(!IsOwner)
{
return;
}
if(IsServer)
{
OnDespawnObject();
}
else
{
OnDespawnObjectServerRPC();
}
}
[ServerRpc]//called on the server, not on client
void OnDespawnObjectServerRPC()
{
OnDespawnObject();
}
void OnDespawnObject()
{
NetworkObject.Despawn();
Destroy(gameObject);
}
any help would be greatly appreaciated
Don't destroy the game object. It needs to still exist to receive the Despawn message. Despawning will take care of the game object as well. Disable the renderer if you need it to disappear locally.
are there ways to reduce the latency with unity relay because everything is very async und buggy and i cant display the ping it always says 0ms
There is not much you can do about the actual network latency. But check out the Ping Tool to see the ping to the relay service.
Client Anticipation can help you deal with the latency
Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer. - Unity-T...
Client anticipation is only relevant for games using a client-server topology.
Alright so I've been working on a single player game for a while now, but recently I decided that I would like for it to have multiplayer functionality. I guess I am a little confused on where to even start converting my game to multiplayer and I was wondering if anyone had some resources/advice on where to start. I'm not looking for a dedicated server for hosting, I would want it so that the host player's computer would act as the server.
Really depends on how far along you are. Adding multiplayer after the fact is going to be a bad time. A lot of things will have to be rewritten. But in general, pick a networking library first. That will steer you towards what Relay services you can use.
hiya! i don't really have much experience with websockets but my friend has made the backend for my game. most of the functionality is up and running but i'm struggling to figure out why i'm not receiving packets of chunk data, so i've been going back and forth with chatgpt and gemini to no avail.
it's a mess at the moment but what i'm hoping is that my RecieveChunkData() method receives those packets of chunk data sent from the server. right now it only receives the information given by the server on connection to the websocket.
any help is greatly appreciated as i've been struggling with this for days. thanks in advance, and so sorry for the newbie question.
What behaviour are you seeing?
it's currently receiving the first message sent from the server containing some other info, but then i'm also receiving that whenever it sends me a chunk packet? at least that's how i'm understanding it.
alright, one more thing, this time im looking for critique, improvbments, anything to help me grow here. how bad is this code, which keeps track of clients with their usernames?
public class LobbyPlayerHandler : NetworkBehaviour
{
// Store the incoming connections
public static NetworkVariable<Dictionary<ulong, FixedString32Bytes>> PlayerData = new NetworkVariable<Dictionary<ulong, FixedString32Bytes>>(new Dictionary<ulong, FixedString32Bytes>());
public string PlayerName;
private static bool eventsRegistered = false;
public override void OnNetworkSpawn()
{
//allows registration of events only once while confirming registrar
if (IsServer && !eventsRegistered)
{
NetworkManager.Singleton.OnConnectionEvent += OnClientConnected;
NetworkManager.Singleton.OnConnectionEvent += OnClientDisconnected;
eventsRegistered = true;
}
}
private void OnClientConnected(NetworkManager manager, ConnectionEventData connectionData)
{
//dont know if this is needed
if (!IsServer)
{
return;
}
// Add the client to the PlayerData dictionary
if (connectionData.EventType == ConnectionEvent.ClientConnected)
{
AddClientUserName(PlayerName, connectionData.ClientId);
}
}
private void OnClientDisconnected(NetworkManager manager, ConnectionEventData connectionData)
{
//dont know if this is needed
if (!IsServer)
{
return;
}
if (connectionData.EventType == ConnectionEvent.ClientDisconnected)
{
// Remove the client from the PlayerData dictionary
RemoveClientUserName(connectionData.ClientId);
}
}
private void AddClientUserName(string userName, ulong clientId)
{
//dont know if this is needed
if (!IsServer)
{
return;
}
//debug to see what client is joining
Debug.Log($"{OwnerClientId} called this method!");
//convert a string that we get from other code into a fixed string to pass later
FixedString32Bytes convertedString = new FixedString32Bytes(userName);
//check if the client number doesnt already exist
if (!PlayerData.Value.ContainsKey(clientId))
{
PlayerData.Value.Add(clientId, convertedString);
//collection requires me to do this after modification
PlayerData.CheckDirtyState();
}
else
{
Debug.LogWarning("Client with ID " + clientId + " already exists.");
}
//this is another debug to ensure i am getting the string into the dictionary and getting it appropriately
PlayerData.Value.TryGetValue(clientId, out convertedString);
Debug.Log(convertedString.ToString());
}
private void RemoveClientUserName(ulong clientId)
{
//just remove the thing :)
PlayerData.Value.Remove(clientId);
}
}
You can't have static network variables but otherwise it's seems fine.
how would I get logging from the Network Manager to show in game? such as an in-game console or something like that
you could use Application.logMessageReceived? if you're using NGO the messages should usually start with [Netcode] so you can identify them
bumping this, would very much appreciate any help!!
Hello, maybe this has been answered a lot, but I tried lot of things and no one worked. I have this error when a client wants to join an ongoing lobby:
[Netcode] A ConnectionRequestMessage was received from a client when the connection has already been established.
When the client joining the server starts well, he connects to the lobby (even the server has all the callbacks)
Im using Unity Netcode 2.0.0, Lobby 1.2.2, Relay 1.1.1 & Unity 6000.0.21
Im also using Unity Transport with Relay Unity Transport
SceneManagement isOn, Connection approval is on bu approves everyone for the moment (Approved = true)
I just started trying to do netcode stuff, and sometimes I get this problem where if I try to start a client, this happens
how would I debug an issue like this?
it just immediately fails
this time I knew why it was happening i think, it was because I had a regular rigidbody on my player prefab
something like that.... and after I removed it, the client could connect again
but in the future it won't be so obvious what's wrong.. so how does everyone do troubleshooting
Sounds like the client is trying to connect twice
So I was just getting into networking and learning about it. I just learned about networking variables and how you can restrict certain client for writing certain data. The first thought that comes to mind is that the purpose of this is for data security so that clients can't manipulate particular vital game data. But I was wondering, if I am planning on making a casual game where I don't necessarily mind I guess player cheating (as it would only hurt their own experience) what form of data communications would I want?
Would I still want the client to handle most of the data changing and having the clients just read the data? Additionally, I wouldn't want players to be able to change the data of other players, only their own if they really want to.
General rule of thumb is that network variables are for persistent state data and RPCs are for one off events.
And network object can only have one owner that has wrote permission so no need to worry about changing other players data.
I have a question regarding networking. So I am in the middle of converting my single player game to multiplayer, and I have an object pooling system. I am getting an error at the start of the scene that pretty much says that I shouldn't reparent an object before starting a server or host. I understand what is going on, as I am just instantiating and trying to reparent the a particular object at the start of the scene without a host running...
All I really have to do is start a server or a host at the start of the scene before the object pooling system starts up. BUT...
For games such as lethal company, where you start the game solo and have friends join you at the start of the game, how does this work? Does this mean that when you start the game you are still technically a host/server, just without any clients?
I'm wondering if I should be starting a host as soon as the user presses play or if I would want to do that at a different time
Yea, for solo mode you would start a host and connect to itself. Not too familiar with Lethal Company, but if you are sharing lobby codes to join matches, that is easy to set up too
Could anybody here help me out?
I'm trying to get my app released on the google play store
I need 20 closed access testers to get it published
I don't know if this is the right place to ask, but I have a multiplayer unity project. In my project, on a single client, I have a texture that I draw to at about 60fps. I need to take that texture data and somehow provide that data to every other client. I'm using Unity's netcode for gameobjects at the moment but I'm open to other tools.
Unfortunately, the code I'm running to calculate the data for the texture cannot be simulated on other clients.
I know Unity isn't really optimized for streaming textures across the network (let alone multiple textures which I'll eventually need to be able to scale to), but are you aware of any tools / packages that might offer some help with this.
I know Unity isn't really optimized for streaming textures across the network
No, it has nothing to do with Unity.
This is bad for any game, or real-time app with many connected clients, and should be avoided completely unless it's really really needed.
Unfortunately, the code I'm running to calculate the data for the texture cannot be simulated on other clients.
Why?
Yeah, I'm aware that not being able to simulate the code on other clients isn't ideal. If I could then that would make things a lot simpler. It's a bit too complex to go into, but I am actively trying to figure out a work around as video streaming is a last result. But basically I'm using a dll which contains many static methods, and has no concept of instances, and is expecting to operate on a singleton basically. I didn't write this dll so I can't modify the source code etc. unfortunately. Each client will be able to run their own singleton process (that's the best way I can describe it), and then data about what other client's are doing (in this case the texture data) is shared across the network. I'm working on creating a wrapper that will hopefully containerize this dll so I can have multiple instances running on a single client which will mean I won't have to go the route of streaming the textures.
Sounds like you want to stream video. You'll want to look into WebRTC
Thanks, I'll take a look. Hopefully I can get this wrapper working and I won't have to stream video. Out of curiosity though do you know how well WebRTC scales with multiple streams? Each of these textures are about 250 pixels in width and height, being updated at about 60fps
If i remember right, it has multicast support
https://docs.unity3d.com/Packages/com.unity.webrtc@3.0/manual/index.html
Alright so I am running into an issue with my networking system. So what I want is to make it so that when the player presses the play button, he is spawned in in the home base. I want to make it so that the player has an option to invite or join a friends world/game. In order to achieve this would I need to start a host/server as soon as the player joins the game? If so, how would I test this, as I would need to check if a hosting on the local IP is available, as I would be testing between a build and a playtest on the same machine.
Using Netcode
Really depends on how your game is set up. Normally for single player you would start a host session and connect to localhost. If you want to start a multiplayer session then you would end that host and start a Relay connection for others to join.
Has anyone seen this before? I am trying to change the way a script acts based on whether IsServer is true, so I am checking during OnNetworkSpawn, but OnNetworkSpawn is never being called. I am instantiating the object after the relay session has already started
I saw something in a forum about having a duplicate network manager object but I donāt have that
Do you have logs you can share?
Is it getting into ProcessReceivedData?
Does this ever receive data?
result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
Do you get any errors?
If you are switching scenes then make sure you are using Network Manager Scene Manager. Otherwise as long as the network object is active, OnNetworkSpawn will always get called
Are you calling Spawn on the object? If your instantiating it, the server must spawn it
This is probably the issue. Thanks a lot
One thing I noticed is that after setting up a network system using Netcode, players spawned as a host or client function normally, but players just spawned using regular instantiate ignore collision and can walk through walls. Not a problem but, I was just wondering what the reason for this was.
if something is nullable example abstract class there is no easier way to make this than this?
You can create a custom serializer for the owner hub class
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/custom-serialization/
Netcode uses a default serialization pipeline when using RPCs, NetworkVariables, or any other Netcode-related tasks that require serialization. The serialization pipeline looks like this:
im following the codemonkey tutorial and all of a sudden some things stopped working like the spawn plate every 5 seconds (as you can see the server has plates and the client doesn't). The one above is the client and the one below is the server. It is giving me this warning:
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 4, but that trigger was not received within within 1 second(s).
im stuck like this for days, idk what to do to continue
i tried searching online but nothing
Code you're using to spawn the plates? Or any code related to the plates?
imma send it rn
Piece of code related to the plate
private void Update()
{
if (!IsServer) return;
spawnPlateTimer += Time.deltaTime;
if (spawnPlateTimer > spawnPlateTimerMax)
{
spawnPlateTimer = 0f;
if (KitchenGameManager.Instance.IsGamePlaying() && platesSpawnedAmount < platesSpawnedAmountMax)
{
SpawnPlateServerRpc();
}
}
}
[ServerRpc]
private void SpawnPlateServerRpc()
{
SpawnPlateClientRpc();
}
[ClientRpc]
private void SpawnPlateClientRpc()
{
platesSpawnedAmount++;
OnPlateSpawned?.Invoke(this, EventArgs.Empty);
}
Another piece of code related to the plate that is connected to the first one some way:
private void Start()
{
platesCounter.OnPlateSpawned += PlatesCounter_OnPlateSpawned;
platesCounter.OnPlateRemoved += PlatesCounter_OnPlateRemoved;
}
private void PlatesCounter_OnPlateRemoved(object sender, EventArgs e)
{
GameObject plateGameObject = plateVisualGameObjectList[plateVisualGameObjectList.Count - 1];
plateVisualGameObjectList.Remove(plateGameObject);
Destroy(plateGameObject);
}
private void PlatesCounter_OnPlateSpawned(object sender, EventArgs e)
{
Transform plateVisualTransform = Instantiate(plateVisualPrefab,counterTopPoint);
float plateOffsetY = 0.1f;
plateVisualTransform.localPosition = new Vector3(0,plateOffsetY*plateVisualGameObjectList.Count,0);
plateVisualGameObjectList.Add(plateVisualTransform.gameObject);
}
the first one makes sure the server every spawnPlateTimerMax spawns a plate for all the clients
and the second one is executed by the client to instantiate the plate or remove it
@tame slate yo please help me on this
im following the codemonkey tutorial and
hi so i'm currently converting my single player game to multiplayer using Unity's NetCode. pretty much I have a scene transition between the player's home base and the actual in level/dungeon scene. i want all the multiplayer connections to be handled in the home scene and the players all enter the dungeons together and maintain control over their characters. i was wondering, currently when i change scene the player is just re instantiated and the previous data values such as health or equip weapons are reset with the newly spawned player. would this method still be recommended for networking? i feel like it would be easier to have the players do not destroy on load so that they can just be toggled on and off and reset when the scene is loaded. if it is not easier, where would i start with to i guess re establish all the connections of the players after the scene has changed with all the current equip weapons and stats?
you should be able to turn on "active scene synchronization" for the players which moves them to the next active scene automatically when you switch scene
how do i make it to where the player spawns when your onnected
and it doesn't make other people control your player
nvm
someone made any roslyn analyzers for networking? like example some field is using NetworkVariable soo analyzer will add .Value if its missing when something else wants to get value from this field
pain while trying to create own analyzer + codefix
.Value is added but yes it will add .Value even when its here
seems like its working, only if someone made this for most stuff in netcode heh
FastBufferReader.Length == Remaing data?
You are too bored of doing variable.Value = something instead of variable = something?
I mean when project is massive then lol, already converted all
Yea, I totally agree, it looks ugly.
Hello, I'm using Multiplayer widgets, its auto spawning my player prefab when I start the scene but I could'nt figured out how to change spawn position, even I change host's spawn position, guest clients still spawning in 0,0,0, anyone knows how to fix that?
Hello everyone.
I'm using NGO with steamworks and the SteamNetworkSockets Transport and want to create a couch coop (client authority is fine).
I can create a lobby and other clients can join the lobby. (Updating the lobby name works for both host and clients)
The problem: On the host machine, only the host player is visible. On the client machine, no player is visible. As far as i understand, networkobjects should be synchronised automatically, and also StartClient() should automatically spawn the playuer prefab. is that correct?
I'm using the Singleton methods for StartHost and StartClient.
In the NetworkManager, the Network Topology is set to Client Server.
The Ownership of the NetworkObject of the PlayerPrefab is set to Transferrable. The Authority on the Client Network Transform is set to Owner.
Is there anything i have to do besides StartClient() on the client to be able to see the host player? And why does the client prefab not spawn?
What am i doing wrong? Thanks for helping me
Hey everyone! Maybe this is a noob problem, but how do you guys handling passing any sort of object that isn't simple into a parameter to pass along the network?
For example:
[ServerRpc]
private void SetTriggerServerRpc(Animator anim, string triggerSetting)
{
SetTriggerClientRpc(anim, triggerSetting);
}
I get the error that states: "Don't know how to deserialize UnitEngine.Animator"
Usually use simple types to represent a value that can be used to look up a specific object in a collection that each client has -> Enum representing the type of the object in the collection, int representing the index of the object in the collection, etc.
In your case, why do you need to send an animator?
I'm trying to update a variable on the Animator so I can change an animator for all clients. However, I'm finding that maybe I should have a script attached to the object I'm trying to animate, call that, and use a networked variable to sync the status
I should have a script attached to the object I'm trying to animate
Definitely the way to go.
There's also NetworkAnimator
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.
if you do want to do it the original way, there's NetworkObjectReference, which you can serialize in an RPC and presumably call GetComponent on at the other end
Would you use this like any other component? Getting the component in start and setting a trigger via networkAnimator.SetTrigger("On")?
NetworkAnimator netAnimator;
private void Start()
{
netAnimator = GetComponent<NetworkAnimator>();
}
// Call this function when you want to update the animator parameters
[ServerRpc(RequireOwnership = false)]
public void SetAnimatorTriggerStatusServerRpc()
{
SetAnimatorStatusClientRpc();
}
[ClientRpc]
public void SetAnimatorStatusClientRpc()
{
netAnimator.SetTrigger("On");
}
You wouldn't use it in a ClientRpc generally
Works similar to NetworkTransform, the Server or Owner makes changes and the component auto syncs the changes to other clients
oHHHHHHHHHHHH
Also for any other Animator parameter, you can just update the normal Animator component directly and NetworkAnimator will sync it
Triggers are the only one you need to do it on the NetworkAnimator
Yeah it looks like triggers are a special breed of difficult
Thank you for this š
For anyone wondering in the future, here is the solution for setting a trigger over the network:
public class AnimatorSync : NetworkBehaviour
{
NetworkAnimator netAnimator;
private void Start()
{
netAnimator = GetComponent<NetworkAnimator>();
}
// Call this function when you want to update the animator parameters
[ServerRpc(RequireOwnership = false)]
public void SetAnimatorTriggerStatusServerRpc()
{
netAnimator.SetTrigger("On");
}
}
Hi guys, i'm doing an inventory system on my game and i want to put an object in the hand of the player. How to do that (cause i can't parent network objects to non-network objects) ? Do i have to put joints?
How does one usually go about handling starting a hosted/online game up after spawning? Do you spawn a empty game object and then add things a player would usually contain? or spawn everything hidden and then unhide it?
Depends on the type of game. In a round based game like a FPS, you spawn the players then wait for everyone to join then start a countdown to start the match. You might have a separate scene that you load in.
You'll need a custom serializer for Tile base
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/custom-serialization/
Netcode uses a default serialization pipeline when using RPCs, NetworkVariables, or any other Netcode-related tasks that require serialization. The serialization pipeline looks like this:
Hello! I've a simple question I can't find a specific clear answer. I'm building a multiplayer game using netcode for gameobjects (Unity 6). I've been reading about lag compensation and server reconciliation. But using the basics of my first level along with Multiplayer Play Mode, I don't see any lag happening (client side). Am I missing something?
What have you networked so far?
4 car controllers, traps with animations and 1 spawned object.
What components are you using to sync those things?
Network object + Client Network Transform + Network Rigidbody as basics, then a couple NetworkBehaviour holding some variables for health, name.
Using up to 4 instances using the Play Mode does not throw any noticiable lag moving all cars at the same time
Using a Client Network Transform basically means the client can move freely on their own without having to send information to the server in order to move
Which means locally your movement is not subject to lag
Also you will overall generally just have a smoother experience with Multiplayer Play Mode as all of your clients exist locally on your machine and it does not simulate a real networking environment
try out network simulator, test real network conditions and see if you have any big lag, like dylan said thought locally you probably wont see much
Thanks @tame slate @fringe imp . So before I move on with more development this is something I would need to take care right? That's why I'm asking. There's no "magic" behind netcode for gameobjects to deal with this.
to deal with what?
Find a solution for lag and/or server reconciliation.
Why does your game need these? Not saying they don't - just wondering.
I understand, Dylan. I'm speaking from a place of uncertainty because right now, using what's in the documentation, it works well (I don't see any lag). But I'm not sure if I'll need to apply some of these techniques later on when I have a level with many objects, data, and so on.
Lag Compensation and Server Reconciliation are advanced techniques that help minimize the effects of latency that the player feels. They don't just magically remove latency or reduce it.
Server Reconciliation isn't typically used with client authoritative setups to my knowledge, so I wouldn't worry about that.
If your game has very quick interactions between players, you may find implementing some form of lag compensation is helpful. But you'd have to implement that on your own, and I wouldn't do it prematurely, only if you notice quick interactions between players don't look right or aren't working as intended.
That's very clear. Thank you @tame slate š
later on when I have a level with many objects, data, and so on.
The techniques you described wouldn't help with this. The best thing you can do to prevent the scale of your game from slowing down networking is mainly two things:
- Use simple data to network things and try to use small amounts to accomplish what you want to
- Only sync things over the network when needed
But generally, if things are working well just keep on keeping on. Premature optimizing can get you in trouble
Get the basics down first. But you'll want to look into Client anticipation and Distributed authority
Client anticipation is only relevant for games using a client-server topology.
Distributed authority is one possible network topology you can use for your multiplayer game.
Hi! So I had a question I feel like this should be an easy fix but I'm not finding the answer online, pretty much I have the player movement and transitioning between scene A and scene B working. Since my players are persistant I need to move the players back to 0, 0 when moving to scene B, I have a script on an object in scene B that does that and replicates it using RPCs across all clients. However, when I try to run this I get the error above. I believe the reason for this is because the network object that is in charge of moving the player is a network object and is not being spawned in. From what I've seen online, the network manager STARTING in scene A should not be a problem as long as I enable scene management, but the script only works if I manually spawn in the object moving the player, which isn't a problem, but I feel like this could get cumbersome down the line. Is there not a way to make it so that objects already in scene for all scenes are automatically managed?
does lowering public float MaximumInterpolationTime = 0.1f; hurt performance?
after lowering to .1f there is way less smoothing going on of course (which is great), but not sure whats happening bts and if its going to cause trouble.
and i guess just to add on, is there a better way to lighten up the interp amount? I dont want it to be nothing, but the default is too extreme.
Hey. I am getting an error when trying to add Network transform to my co op game
Using Host / client, so no server here. Only happens when I add the Network Transform, otherwise everything works fine (Hosting and joining)
Found the issue! It did not like me deleting scripts based on IsOwner
Destroying scripts**
Always disable instead of destroy components/scripts when working with NGO.
Aha, thanks for the heads up
I am trying to test this through the internet (not locally), opened port 7777 on my network, but it doesnt seem to work. Put my public IP address in the Unity transport, but I cant join locally or through the internet when doing it like that. Any thougts?
not in the picture, but I toggled Allow Remote Connections
Helloo
Anyone here used MultiplayerPlaymode? I can't get it to work.
Here's error log :
[MultiplayerPlaymode]: The project directory for [mppmf329d855] could not be found.
- Unity ver : 6000.0.23f
- MPM ver : 1.3.0 & 1.3.1
Scratch that, changed to port 5555 and it worked. Unsure why, not running anything else on 7777
I am using it now and it worked out of the box for me
Mine stuck like this for ages.
What's your unity ver and MPM ver? May I know?
Nvm, Assets -> Reimport. All fixed the prob so far.
any insight on this dylan if u get time?
What component is this in?
this is in the bufferedlinearinterpolater script which sits in the network transform script
basically just want to decrease interpolation amount.
Should be fine. You can subclass network transform if you want to override the interpolator
You'd have to test thoroughly under a wide variety of network conditions. My suspicion is that if it's not exposed to the inspector through NetworkTransform by default, that's for a reason. I would guess that lowering it would make clients with higher latency or packet loss more susceptible to jittering/jumping.
gotcha guys, thanks. i think id prefer occasional jump/jitter then the extreme lerping. Ill test under some simulations.
private void ExtrapolateMovementFromPrevData()
{
estimatedPos = networkPos + networkVel * (NetworkTime() - lastUpdateTime);
// correct pos if error exceeds threshold
Vector3 posError = estimatedPos - rb.position;
if (posError.magnitude > posErrorThreshold)
rb.position = Vector3.Lerp(rb.position, estimatedPos, Time.fixedDeltaTime * 10);
rb.linearVelocity = networkVel;
}```
been working on my own but lost for the most part. Have no idea if im close or not, i send rpc of position and compare with network pos.
Network Transform uses custom messages so that's not far off.
i have a good rotation one figured out, but dont want to drop a wall of text. Position seems harder as ou want to include velocity
syncing physics is going to be hard
is c# decimal a good idea for network game logic that must be deterministic cross platform? I know float has issues with determinism
As far as I know floats are fine for most use cases. Physics being the exception.
Really? It seems like I am getting different results of computations on different platforms, at least when it comes to rounding to the nearest int. Itās possible itās another bug, but it doesnāt seem like it
If you're rounding to the nearest integer and getting different results on different platforms I highly doubt that has anything to do with the precision of float
I have heard in many places though to avoid the use of floating point math due to non determinismā¦
I'm not saying that's incorrect. But, if you're strictly talking about rounding a float to the nearest integer and getting different results, the chances of that happening due to the precision of float are astronomically low
I noticed that my stuff syncs but sorta laggy and it looks like the positions are being interpolated, is this some sort of setting somewhere
Using NGO?
yea
It's recommended and I believe enabled by default to reduce the impact of latency and jitter.
It can be toggled on/off on the NetworkTransform component.
As outlined in Understanding latency, latency and jitter can negatively affect gameplay experience for users. In addition to managing tick and update rates, you can also use client-side interpolation to improve perceived latency for users.
Are you using PhotonNetwork.Instantiate to create the networked object?
If it is part of the scene, make sure the object in the scene has a PhotonView ViewId (it's set when >= 1).
it would help to paste the whole stack trace not just the top line, but one thing that immediately looks sus is you're calling Spawn in Awake which will run on the client as well as the server
Awake runs before OnNetworkSpawn which generally is the first event it's safe to assume all the network stuff is initialized properly
how are you instantiating TerrainManager on the server? it's probably better to have it call Spawn there
well the server has to create an instance of it before spawning it right? or Awake would never be called
if you're using NGO's auto scene sync, you don't need to spawn it at all, it'll be spawned automatically if it's part of the scene
otherwise you need to make sure it's only instantiated on the server and is set up as a network prefab
can you see if it's spawned on each side in the inspector? it looks like it's trying to send a RPC before the system is initialized
if it's not spawned, you either need to enable this setting in your network manager config, or you need to delete it from the scene, make it a prefab, and spawn it yourself
Make sure that TerrainManager is on a Network Object and is active when the scene loads
I've been looking around Netcode for GameObjects and i had a question about authority. When you have a dedicated / listen server everything becomes server-authorative.
For example; if you have an inventory system, the server would have to know all of the player inventories to do the actions.
However my question is, can't you "move the ownership" to the client? I mean, each player has ownership of their inventory and they broadcast the changes to all other clients.
You can give Network Variables owner write permissions. But it all still goes through the server/host.
Hm. I had webfishing particularly in my mind, where each player has some sort of inventory then they can place their props around.
I guess the clients can call a "SpawnPropServerRpc" with the id of the prop, and the Server spawns the actual transform...
Can you make network spawns predictive somehow ? So a client can instantly spawn it visually, then when later the network object arrives it overwrites it
You can use Distributed Authority for client side spawning
Distributed authority is one possible network topology you can use for your multiplayer game.
That is for the topology without a host, right?
Right. There is still a Session Owner for things like scene management though
I do think that this will make things more complicated than a plain old host session
Depends on how far along you are in your game. It should be easier to spawn things and also has built in host migration
Not even started a project š just researching before a decision
can you screenshot what it shows in the NetworkObject inspector?
at runtime i mean
after the error has happened
both i guess if it's happening on both
that doesn't look spawned!
if it was spawned, there wouldn't be a "spawn" button š
If its a scene object then make double sure that you are using the Network Manager Scene Manager to load the scene
if it's not a spawnable prefab, that won't work
is it in the network prefabs list?
err, you're telling it to spawn in its OnNetworkSpawn method, that will never be called unless it's already spawned
you need to spawn it at some point after the NetworkManager is ready and before the client connects
networkManager.StartHost();
terrainManager.NetworkObject.Spawn();
something like that?
just don't do that on the client
Not much different than offline development. An object can't Instantiate itself. Same principle basically applies here.
Some other object/script should be responsible for spawning this. Or, if it's needed so early in the lifecycle of the network, it should just be placed in-scene.
Do you have other objects placed in scene that spawn correctly?
this is still the error you're getting?
Where is PlaceTilesServerRpc() called?
Did anyone get the invite to the Distributed Authroity webinar?