#archived-networking
1 messages · Page 33 of 1
I will take your word for NGO, I haven't used it much compared to the older third party options
I will also mention that they are all kind of buggy in their own ways, or have their own poor workflows. Might as well experiment
That is not true at all, Photon Fusion is not buggy, never had an issue with that
i said redistribute
(and modify...) I can see that you have strong opinions. Anyways, I gave my 2 cents.
i am not sure what is your point?
you usually want to modify so you can redistribute, they are very attached to each other, but technically yea they don't mean the same thing
many people have strong opinions on fishnet and its creator who's banned here
i am currently working on it
it is a painful process for a beginner
i've never worked with netcode before
and i regret doing it...
but its promising and rewarding if you success
hi, i'm having some weird issues with lobby. i've got this start method
and these methods to create and list lobbies. these two work fine when i test in the editor, but when i try to run them from a build i get an error
InvalidOperationException: Unable to get ILobbyServiceSdk because Lobby API is not initialized. Make sure you call UnityServices.InitializeAsync().
it seems very strange to me that i only get an error on builds, not from the editor. can anyone help? as far as i understand the unity services are initialised in the start method, and my debug.log there says it's initialised
The main reason why I wanted to swap was that I heard fishnet has built in client side prediction and I heard that for a networking beginner that can be really tricky to implement that was the main reason
But yes if anyone else has experience with Fishnet negative or positive please feel free to say!
Are you calling CreateLobby() from Start() as well? Could be a race condition. Also be sure to switch authentication profiles of you are logging in anonymously on the same PC
createlobby's being called from an update function when a key is pressed. what do you mean by switch authentication profiles?
Anonymous sign in is tied to the device. So 2 instances on the same PC will get logged in as the same player.
https://docs.unity.com/ugs/en-us/manual/authentication/manual/profile-management
ah ok thanks
But that won't stop the Unity services from initializing
that does not make using client side prediction any easier
client side prediction is an advanced technique, not sutiable for people with no multiplayer experience
what makes it worse is that a solution like fishnet has a very poor attempt at implementing it
Is this a good place to ask questionsn related to netcode for gameobjects?
Yes. There's also a Discord server for NGO and other Unity Multiplayer solutions
Oh nice! Im spawning vehicles for the players and am trying to find a way to assign the owner using a <NetworkVariable> playername that is already synchronized. I don't want the other players to be able to enter each other's vehicles
I spawn, then assign a local variable to the vehicle which updates the synchronized variable when Onnetwork spawn is called on the vehicle
i see so would you recommend that i stay on ngo? are there better options availabe? i know photon fusion has a good system but i want to know all my options before commiting to a change
what game are you developing?
genre, type etc
the answer will depend on that
2D roguelike dungeon crawler, faster paced
nah casual, up to 4 players
dedicated server or player hosted
player hosted
Good, NGO is great for this
also a useful tip, don't ask the creator of a product for opinion about his product
no creator will down play their own creation
you don't have to
that's a feature useful for competitive games
mainly
I see, if my game is fast paced though and there is a moderate amount of latency wouldn't it feel pretty bad to play?
Any game would feel not great with a lot of latency
you can't beat the speed of light
True, but doesn't client side prediction help a lot with that? Especially for a high speed game?
if you thought client prediction fixes latency issues
then you are very wrong
that's not what it solves
I know it doesn't but it helps with stuff such as should this projectile hit this enemy accounting for latency no (im pretty new to networking so i could be wrong xD)?
no, with a client authoritative game, that does not matter
While my game is peer to peer, I still have most of my operations so far done by the host who is acting as the server. I did some research and I found that people recommended to still have the server handle the bulk of the logic to prevent desync, etc. at the cost of some latency. Would the client prediction apply in this case?
I think what you're wanting is some form of Lag Compensation, not client prediction
You would want to use .SpawnWithOwnership() then you can have the owner set its own name.
@ocean wadi https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking#Lag_compensation
discussed in detail here
I was thinking about the ownership trick, but it does not hold up in my build because the clients request ownership of the vehicles to drive them. So ownership is assumed false. Apparantly the issue was order of operations. I just put network spawn at the end of my method. So [get prefab instance from pool]=>[assign shipowner using string name]=>[Then spawn] seems to work. I just assumed getcomponent wouldn't work since the gameobjects were inactive, but its a little different over the net
I would look into both Distributed authority or Client anticipation
Distributed authority is one possible network topology you can use for your multiplayer game.
Client anticipation is only relevant for games using a client-server topology.
Hello there. I am having a really weird issue with NGO.
I have a NetworkManager on my scene. And I created a prefab that has a collider, a NetworkObject and PlayerController that inherits from NetworkTransform.
I assigned the prefab to the player field on the Network Manager and it is being spawned but OnNetworkSpawn never get called and I get this error:
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.Components.NetworkTransform.InternalOnNetworkObjectParentChanged (Unity.Netcode.NetworkObject parentNetworkObject) (at .
...
Any ideas please?
thank you ill be sure to check this out!
Is the network object on the root of the prefab?
Yeah, checked many times. Super weird.
Does it work with just a regular Network Transform?
sorry, got into a meeting.
Replacing with a Network Transform actually worked. But all my player controller logic in on the other component.
Can I have my PlayerCOntroller being just a monobehavior, that gets the NetworkComponent on Awake and does what it needs to do with it? Like move based on input and etc.
Or my playercontroller would need to the a NetworkBehavior?
Sure. It only needs to be a network behavior if its using network variables or RPCs. Just be sure to disable the player controller on remote players so they don't get the local inputs
Got it! Thanks a lot for the help though!!
I’m confused which networking package I should be using with a hybrid project
Are you able to use both N4GO and N4E??
Or are the packages just like
You implement it on an entity / go?
Not use x if you use x in the rest of your project
(I’m complete noob)
My guess is that you would want to use N4E and make a hybrid layer to forward messages to the game objects.
Based on what I know about N4GO, it would be tricky to tie them together
they are completely different animals
if you are a noob, stick to GameObjects
DOTS is not for noobs
i meani m a noob at networking
i want to add multiplayer to a hybrid ecs project
thanks
you will have to either use Netcode For GameObjects or Netcode For Entities
you can't use both
that will never work
i mean it could work but u will end up with a huge mess
this is like running a Windows VM inside a Linux VM that is running inside a Mac OS Machine, and u are trying to pass data from one layer to the other or some random shit like that
technically may work, but it's dumb
All DOTS projects are hybrid projects since there is no ecs animation or audio systems.
Adding multiplayer after the fact is going to be a bad time. Triplely so with DOTS. Most if not all of your systems are going to have to be rewritten.
There is a Unified Netcode coming in the next Gen version of Unity but that is many years down the road.
Hey there, what networking solution do you recommend? Mirror or netcode(NGO)? I have experience using the old UNet a couple years ago, but now I want to make a "fresh restart" and learn the newer networking frameworks. i am a solo dev and don't want to buy a dedicated server, instead the players host the game themself. thanks :)
Maybe you could hint at what you plan to do. The recommended solution depends on that to a large degree.
Which genre, platforms, etc.
I think either is a fine choice. I'm a fan of NGO. But there are other solutions as well. Mostly will come down to how much work you want to put into extra features like client predictions
well, I'm not quite sure, but i am thinking of making a 3D among us like game with different player roles yk. maybe i will add a simple shooting mechanism too, but not that much like in typical shooter games, where every player has weapons, etc..
sound great
are there any main differences that i should consider between chossing ngo/mirror when it comes to server-client model? do both support player-hosted lobbys? cuz for now, i dont have much money to hire a dedicated server
As someone who just completed a project with Mirror - I would say if you're going to end up using Unity packages like Lobby/Relay there is almost no reason to choose Mirror over NGO.
unity packages like lobby/relay? what exactly do you meant by that? i thought lobby is being created/coded using ngo?
but yeah, generally i'm gonna use unity packages for backend
There is Fusion Impostor sample, which might be interesting then.
Fusion comes with 100 CCU for free, so no money needed to get going, experiment and find the first players.
There are many services that provide Relay Networks, Lobby, Leaderboards, and Matchmaking. Unity, Steam, Azure Playfab, Amazon GameLift.
oh photon, yeah i heard about it before.. but i still prefer to use 1st party solutions, moreover, the code/api will be almost the same as unet afaik so yeah xD
are these relay servers from unity free? cuz i dont see pricing.. or i'm just blind 
ah i see. i am planning to publish the game on steam, so yeah
The free tiers are very generous. You would be looking at 100+ daily active players before paying anything.
damn thats actually more expensive than i thought
but relay isn't necessary if a player is hosting the game and kinda acting like the server itself, right?
The pricing is not that expensive. And as I said above, you will not be paying anything until you have daily active users in the hundreds.
Sure, if your your players are going to set up port forwarding.
oh hell nah, that would make trouble for most players ig, cuz not everyone knows how to do that 💀
If price is really an issue. then Steam P2P is free outside of the $100 developer fee
But again, you are verly likely never to surpass the Unity Relay fre teir
oh that sounds good. but does that mean, i cant use ngo/mirror or does steam p2p have its own coding api`?
well, if there are over 50 players, then i'm already over the free tier xD total players of 50 at one time, isnt even that much, right?
its an average of 50 CCU for the month, so its more 36000 user hours total
Unity Relay/Steam P2P are just ways of connecting players. They do not directly relate to Networking libraries where you're coding the gameplay. You can pretty much pair any combination of packages you want. Some combinations are easier than others.
That means for one month at any given moment in time you had 50 people playing your game. That's likely to mean 100+ unique users play your game every day and that you have hundreds if not 1,000+ people who have downloaded your game and tried it at least once.
ohhh now i understand. yeah you're right, that should be enough for the beginning lol i mean, as the game's popularity & player amount grows, which will make some money, i can then upgrade tier
then can i just use steam p2p with ngo? that would be fine, right? no costs, easy to setup?
You can use any library but It does mean that would be locked into the Steam Platform
Yes. I would say setting up Relay + NGO is going to be a lot easier, especially for beginners, but yeah Steam P2P and NGO is entirely possible.
relay + ngo is easier, but expensive (later if +++ccu players)
steam p2p + ngo is nice, and free.,
did i get it right?
Unity also now provides this packages, Multiplayer Services Sessions that combines NGO/Relay/Lobby to be set up very quickly.
I would not say Relay + NGO is expensive at any point in time.
@tame slate hi, lets say i am expecting 1000 players a day, playing at various times
which one would be most optimal
gonna take a look! thanks 🙏
alright, i think i'm gonna start with relay then :) thanks for helping
Entirely depends on the needs of your game and your playerbase.
just a basic 2d isometric turn based strategy game
simple codes simple data
Depending on how basic, I wouldn't even look at a Relay service.
For turn based games you should look into using Unity Cloud Code or the other serverless architectures out there.
unity cloud code seems perfect but should i change my code so much
like i am using a lot of listeners, clientrpcs and serverrpcs
It would be a complete redesign from using NGO. You don't need to the real time communication at all.
then i guess i shouldnt change
You should look into the Chess Sample just to see how they did it
This guide just got released today from Unity
https://unity.com/resources/ultimate-guide-advanced-multiplayer-networking
Hello guys, I have a question about turn-based multiplayer games. I am building a card game and I think it is important to know this beforehand before I continue with development.
So what I am interested is if anyone knows which part of the game should be implemented on client side and which on server side. (I actually don't even know if things work like that, server/client, since I am completely new to networking in games). My idea is something like when you try to play a card server checks if it is a valid move, and then everything else is ran on client side, and after that game state is sent again to the server to check if it is valid. I have no idea whether this is how it should be implemented or not, any help would be appreciated.
For a card game, the game validation and logic is done server side. The client then updates the visuals according to the new game state sent from the server. Check out the Chess Sample I linked above for an example
Oh sorry I didn't even look right above, you were already discussing turn-based games, my bad
I looked through your chess code, simple and clean, I understand what you mean
I guessed it would be something like that, where server does all the logic behind the game and client updates the game
I also learned from your example that you can have async Start? I am very familiar with async/await from my work experience, but didn't know you can have it in Unity. I didn't dig through enough on multiplayer yet, I thought it would be coroutines in question. Anyways thank you very much, and for now I will implement everything in Unity client side where I will mock server actions and transfer that mock logic later to the server.
Just FYI, that's not my code. That's an official Unity Sample demonstrating Cloud Code
hi y'all, I have to get data from a Lidar into a unity script, how can I do this in the easiest way? I have never done this before. The Lidar generates data that is accessible through an internet feed
You grab the data from the internet feed and use it… start with google.
Can anyone help me implementing python websocket and voice communication in Unity !?
Just sending and receiving mic audio to and fro from unity and python websocket
can anyone help me fix my multiplayer? im new and coudlnt find a tutorial so i asked chatgpt, and it works but only on same pc. i cant connect from diffrent pc.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
bruh i cant just look on the internet to my fix my multiplayer system
Bruh, i can't just fix your multiplayer system when you haven't shared the first thing about the first thing about what is wrong. Come on. Put in some effort.
i cant connect to online only to local. local worked but when i added online it didnt
You might want to check out some intro to networking,
https://youtube.com/playlist?list=PLQVJk9oC5JKp_8F9LPa3Pv67boA80KLm1&feature=shared
https://youtube.com/playlist?list=PLTk5ZYSbd9Mi_ya5tVFD8NFfU1YZOyml1&feature=shared
https://youtube.com/playlist?list=PLR0bgGon_WTKY2irHaG_lNRZTrA7gAaCj&feature=shared
The internet is one big network. Learn how data travels across a network, how to control that flow of data, and what to expect as a network specialist. What ...
any easy way to integrate my singleplayer almost ready game with multiplayer? Or I should finish 100% of singleplayer mechanicts and then try to migrate to multi all? any ez and fast tut on NGO and lobbies/parties (maybe should use relay but also there is not many tuts on that)
There is no easy way to add multiplayer after the fact. A lot of your systems will have to rewritten
If your code is clean and simple to modify then yes, and you will need a networking solution that will work for it, simple games would use PUN, Fusion Shared Mode or NGO and if it is advanced then NGE or Fusion Host Mode
Read through this guide that just got posted by Unity
#archived-networking message
can anyone help me add multiplayer to my game im new to unity and just want multiplayer set up.
You'll want to hit up the !collab forums
: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
can anyone help me add multiplayer to my game im new to unity and just want multiplayer set up.
@hushed quarry Don't spam the same message in the channel. See pinned materials in the channel for resources and tutorials.
ty ❤️
Hey all, I'm using the VR Multiplayer sample. Can someone explain to me how exactly inheritance and parenting works with multiplayer using the builtin networking scripts?
I built a fairly robust system for the XR Origin only to discover there's only ever one in a multiplayer scene, and because all my work is based off parenting objects with the XR Origin they simply cease to exist for other players despite being network objects before parenting. How would I fix things without restarting everything?
Hi all, I've been running a NGO linux server + web client and was noticing frequent random disconnects, this was the Unity Transport config I was using. When I changed to the default config settings my game seems a lot more stable. I'm trying to understand what exactly might have been causing the random disconnects with this original dodgy config? Was heartbeatTimeoutMS much too high? e.g. only sending "keep alive" messages between client/server every 5s so when the connectTimeoutMS at 1s intervals sends a connect message into a "non-alive" server/client it fails and just disconnects?
idk why i can't see shooting player that is client, I see only host shooting, also on host i can see that client shoots but i cant see on client anything xd any idea?
private void MyInput()
{
Debug.Log("try...");
//Check if allowed to hold down button and take corresponding input
if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
else shooting = Input.GetKeyDown(KeyCode.Mouse0);
//Reloading
if (Input.GetKeyDown(KeyCode.R) && bulletsLeft < magazineSize && !reloading) Reload();
//Reload automatically when trying to shoot without ammo
if (readyToShoot && shooting && !reloading && bulletsLeft <= 0) Reload();
Debug.Log("try2..."+ readyToShoot + " " + shooting + " " + reloading + " " + bulletsLeft);
//Shooting
if (readyToShoot && shooting && !reloading && bulletsLeft > 0)
{
//Set bullets shot to 0
bulletsShot = 0;
if (IsServer)
{
Debug.Log("serwer shoot");
Shoot();
}
else if(IsOwner) {
Debug.Log("sent rpc shoot");
FireServerRpc();
}
}
}
[ServerRpc]
public void FireServerRpc()
{
Debug.Log("RPC....");
Shoot();
}
Shoot()-> contains GameObject currentBullet = Instantiate(bullet//prefab//, attackPoint.position, Quaternion.identity);
You are only instantiating bullets on the server. You need to also spawn them so other clients can see them. Or send the RPC to all clients
I think it's the heartbeat time out that's too high there
I'm using fusion to try to do active ragdoll multiplayer and my player 2 client keeps throwing this error and not rendering the physics. Any ideas?
Do you know if the server or client initiates a heartbeat? If its the server than I guess it means the client is waiting around for a heartbeat, doesn’t get it within its connect timeout then decides to disconnect?
I'm not 100% but I'm pretty sure each endpoint does its own heartbeat to keep the connection alive.
hi, ive been playing around with the ngo. My objects doesnt collide without a rigidbody even tho they have collider is this normal? Do i have rigidbody for objects to collide each other even not simulating physics?
During runtime you can only parent a network object under another network object. Not sure how to solve your issue because I've come across the same. I have tried adding a network object to my local xr rig just for parenting and had some success.
i tried the same thing, but the result was that one player ended up controlling everyone else's body
You don't have to give every client their own camera. Only the local client needs the camera. And only the local player object needs to accept input
In OnNetworkSpawn() you need to check for IsLocalPlayer and if false then disable the Camera object, Player Movement and the Character Controller.
Are you spawning the player automatically with the Network Manager?
He means if you have a prefab dragged in to the NetworkManager that automatically spawns when a client connects
If those scripts you posted are on the player prefab then it should only be disabling the camera on the non local players
You've got something wrong. In that code, the local player camera will remain active.
Check out the guide posted here. It uses the 3rd person controller but the idea is the same
https://unity.com/resources/ultimate-guide-advanced-multiplayer-networking
Is this a channel for networking with other developers?
Wrong kind of networking.
Remove the first person player from the scene. You should be letting the network manager spawn all the players
Yes it needs to be deleted from the scene hierarchy. The network manager should have the prefab
Your player prefab should be save to the project Assets. It should be in the Network Prefab List
Hey all. What options are there for chat moderation?
Vivox has chat moderation built in
https://docs.unity.com/ugs/en-us/manual/moderation/manual/overview
At $0.05/MAU this is ridiculously expensive.
That's after the first 5,000 for free.
Is it possible to have offline rigidbodies in netcode fgo? As in, send Rpcs to all clients, which instantiates the object and make them all handle the physics individually? I'm trying to do that, but the object is not moving, even though it has velocity and is not kinematic
I'm wondering if something is overriding the physics calculations? But moving the object around in the editor manually doesn't cause it to snap back
You need to remove the network rigidbody and network transform
I figured
Any other ideas?
There is nothing stopping that object from moving. Unless its the Projectile Controller itself
Figured it out, simulation mode in project settings was set to 2 instead of 0 for some reason
Thanks for your help
I'm not sure if this is a bug, but when I build my game for a dedicated server I get a OnTriggerEnter2D null reference exception. However the game works fine when not in headless mode
Hey! can someone give me some references for client side prediction?
https://gabrielgambetta.com/client-side-prediction-server-reconciliation.html
I read this article on client side prediction, i understand like what this is all about but idk how do i implement all this in unity. Can someon help me please?
i am using netcode for game objetcts
Helloy guys,
Im facing an issue with unity mutliplayer and netcode.
I have a networkObject for a bullet and whenever a player shoots the bullet leaves a trail behind with a particle system. now the bullet has a particle system attached to it and a child with another particle sys. on clients everything is being rendered correctly. but on the host side the particle effect for the child isnt being rendered however it is being rendered for the parent.
Does anyone know what is going on?
Heres the code for shooting a bullet:
[SerializeField] private Projectile fireBulletPrefab;
[SerializeField] private Transform muzzle;
public override void Shoot() {
if (cooldownEachShotTimer > 0) return;
Player.LocalInstance.GetAgent().GetComponent<AgentAnimator>().TriggerMainAttack();
var centerOfScreenDir = GetCenterOfScreenDirection();
CreateBulletServerRpc(centerOfScreenDir);
}
private Vector3 GetCenterOfScreenDirection() {
Camera playerCamera = Camera.main;
Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
Vector3 targetPoint;
if (Physics.Raycast(ray, out RaycastHit hit)) {
targetPoint = hit.point;
} else {
targetPoint = playerCamera.transform.position + playerCamera.transform.forward * 100f; // Default far distance.
}
Vector3 centerOfScreenDirection = (targetPoint - muzzle.position).normalized;
return centerOfScreenDirection;
}
[ServerRpc(RequireOwnership = false)]
public void CreateBulletServerRpc(Vector3 shootDirection) {
var fireBullet = Instantiate(fireBulletPrefab, muzzle.transform.position, Quaternion.LookRotation(shootDirection));
fireBullet.NetworkObject.Spawn(true);
}
The code seems fine, it could be unity being unity, have you tried doing fireBullet."child".Play(); ?
I would look into client Anticipation instead
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/client-anticipation/
Client anticipation is only relevant for games using a client-server topology.
Does anyone know any hacks that will allow me to disable Nagles algorithm with the below setup?
- Unity 2022 LTS
- Unity Transport 2.3.0
- Using WebSockets and Encryption
I tried implementing one of the community Websocket Transports that made it possible but it wasn't particularly stable and was a bit dated. If there's something I can do with Unity Transport that would be ideal.
Oh is it similar to client prediction??
Netcode for GameObjects doesn't support full client-side prediction and reconciliation, but it does support client anticipation: a simplified model that lacks the full rollback-and-replay prediction loop, but still provides a mechanism for anticipating the server result of an action and then correcting if you anticipated incorrectly.
hello people, merry christmas c:
I was wondering how I would manage myself if I want to make my game online
but also, be able to play it offline (single player)
do I have to recreate my scripts? or something like "public bool IsPlayingOnline" and determine if I should call local functions directly?
or, Unity does that automatically and I don't need to worry much
I was thinking of terraria, they do that but idk how
The easy way is to make it multiplayer first. then the single player can just be a host connecting to itself
yea. 127.0.0.1 never hits the network at all
oh cool! thanks a bunch evilotaku
you've been my big guide most of the time thanks a lot
I made a full online cards game and wouldn't be possible without you c:
lol, one of these days, I'll stop getting distracted by new shiny features and finally complete a game of my own
hey, i have a third person shooter game with netcode for game objects and i have a networktransform on the player, but it is lagging a bit and when i enable interpolation it is better, but the movement is weird and delayed.
is there any other way to implement network transform?
By using ClientNetworkTransform or Client Anticipation
Client anticipation is only relevant for games using a client-server topology.
Introduction
i already use client network transform - it is literally the same but client authoritative and im using fully client side movement and client anticipation is for client-server
the problem im having is that the unity interpolation is just delayed and the player moves weirdly
it is literally the same but client authoritative
You said you were using NetworkTransform. Using the client authoritative version removes interpolation for the local player which is why I suggested it.
the problem im having is that the unity interpolation is just delayed and the player moves weirdly
Naturally, as you are receiving other players movement updates from the server to your local client, it will have delay. There's no way around latency. As for players moving "weirdly", I don't know what that means.
sorry, i meant that the other player sees the first player delayed and weirdly and by weirdly i mean that lets say the player jumps - he goes up, slows down and starts accelerating down, well the other player sees it very differently, the jump acceleration is different etc.. and when the player is running and jumping it looks very differently
Lag exists in every online game, and minimizing it can often be exhausting. The solution to this problem exists in the Asset I've created. As seen on the screen, there is a 1.5-second delay, which is reduced to at least 0.3 seconds. The lag is barely noticeable and the player's movement functions very smoothly.
The usage will be as follows: Ins...
you can see what i mean in this video
For the most part, this is normal and implemented by NGO for a reason. If you lower the interpolation, you will be much more likely to see the effects of latency and jitter on players with a poor connection which can look a lot worse than the interpolation you're currently seeing. It's explained in depth here: https://docs-multiplayer.unity3d.com/netcode/current/learn/clientside_interpolation/
Somebody else in this server didn't like the interpolation and messed around with lowering a setting within one of NGO's scripts to lessen the effects of interpolation: #archived-networking message
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.
I would use Client Anticipation, that way you can control the smoothing yourself for the best results for your game
okay, thanks
yea i did didnt help tho, problem still remains
hey, i need to spawn an object with a client in unity netcode. First i spawn it locally on the client, but then i need to call server rpc to spawn it on the network, but i dont know how to pass a reference to spawn it.
(this code doesnt work, but shows what i mean)
Why do you need to instantiate it on the client first?
so there is no delay
You'd have to instantiate it and spawn it on the server. If you want to go that route to minimize delay, spawn a separate object locally and replace it with the one the server spawns when it spawns on the client.
okay, so i would have to pass all the values (buildList[buildIndex], buildPoint, buildRotation) to the server rpc? and also how would i replace the object, destroy the local object, but when? How do i know that the network object is already spawned so i can destroy the local one?
OnNetworkSpawn of the object, most likely
Okay, thanks, but also how would i get the reference to the local object on the network object to destroy it?
either through ownership or a stored ID
If you can only have one of these per player be spawned one at a time, assign ownership when spawning the networkobject, and then in the OnNetworkSpawn, get the owner to find the localSpawnedBuild
If that doesn't work because for whatever reason, maybe you can spawn builds really fast or something - assign an ID to the local object, pass it through the RPC, and assign it to the NetworkObject via RPC or NetworkVariable
Then in OnNetworkSpawn it has the ID of the local build, can find it and destroy it
okay, this should work, but also how does the network object find the local object by the ID?
I would use a network variable to store the id used to spawn it
yes, but in my game i will have a lot of these objects spawned quickly so this would be very good
Either spawn the locals under a specific parent or put them in a collection for the NetworkObject to search through
Would just make a basic script for the local to hold the ID
If its that many then I wouldn't use network objects at all. I would have a manager class that keeps track of them
i dont know what you mean with the collection, but the parent one should work, thanks
a list or an array
how would that work
oh yeah, i will probably use the parent one cuz it seems easier
thanks for the help
I just meant having the parent object keep a Network list of the IDs and locations of your object. Clients could send an RPC to update that list when they need to spawn an object
hey folks, do you guys know how to apply the players name above the player in 2D multiplay?
What solution are you using?
Netcode for Gameobjects
I tried to just add an canvas and text and set the vector 2 position of it, but it didnt work. I think I have to use NetworkVariables, but I don't know how or if I'm even right
Yeah, you'll want to use a NetworkVariable.
You'll store the name in a NetworkVariable use OnValueChanged to update your text.
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...
yeah that's ok for me, but my problem is the position of the canvas on the player... I don't get it. the player is on the left bottom corner and the text UI in the middle of the canvas, do i position the textbox just above the player and that works?
I mean, that’s kind of personal preference of where you want to put it.
Personally, I would just make the canvas a child of the player object. Probably in the Player Prefab itself.
Presuming you’re already syncing player movement - the canvas can just piggyback off of that.
hmm ok i try... I'm not very familiar with UI in Unity, I'm a coding guy haha
I got it when the Host is connecting it says "Admin" in red and when the Client connects it should say "Player" + ObjectId, but on the Player my Debug.Logs says "You are not the owner and cannot change the player name". is there a doc how to set a client as an owner of a network variable?
It depends on the owner of the network object.
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#permissions
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...
I usually put the network variable on the player and give it owner write permissions. Your local UI manager could then loop through all the players and update UI elements accordingly
private NetworkVariable<FixedString64Bytes> playerName = new NetworkVariable<FixedString64Bytes>(
default,
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Owner
);
you mean this?
Yes
yeah i did this, but still not the owner of the networkobject...
would it work when I get the NetworkObject with GetComponent and then:
if (!networkObject.IsOwner)
{
networkObject.ChangeOwnership(OwnerClientId);
}
ok it didnt work haha
Keep in mind that only the Server can change ownership
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/#ownership
A NetworkObject is a GameObject with a NetworkObject component and at least one NetworkBehaviour component, which enables the GameObject to respond to and interact with netcode. NetworkObjects are session-mode agnostic and used in both client-server and distributed authority contexts.
yeah i tried with plenty lines of code but it's always the same, the console says "I'm not the owner"... hmm maybe I try something different or even a tutorial from the internet
This is my first experience using Network for Gameobjects, documentation doesn't specify that Web builds do not work, but does not include web in the list of supported platforms, resources on the internet state that Web is supported and you have to use the WebSockets in the Unity Transport settings, I am not using Relay, I made a test project with URP ShaderGraph, Network for Gameobjects and lobby, and a web build failed for some reason
Is this normal or am I misinformed?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Websockets work with NGO. You just can't host from a WEBGL page and will need to use a Dedicate Server or another platform as Host
I got it. FixedString32Bytes has an known error. you need to evade this by creating a struct
public struct NetworkString : INetworkSerializeByMemcpy
{
private ForceNetworkSerializeByMemcpy<FixedString32Bytes> _info;
public void NetworkSerialize<T>(BufferSerializer<T> serializer)
where T : IReaderWriter
{
serializer.SerializeValue(ref _info);
}
public override string ToString()
{
return _info.Value.ToString();
}
public static implicit operator string(NetworkString s) => s.ToString();
public static implicit operator NetworkString(string s) => new NetworkString() { _info = new FixedString32Bytes(s) };
}
What version of NGO are you using? That issue got fix a while back
The latest version. But now it works perfect
weird. NGO 2.2.0 definietely does not have that issue.
I use 2.1.1 and it says no update available...
are you on unity 6? if so it should be in the versions, although 2.1.1 is still the recommended it looks like
You can install is by name and specify the version. but the fixed string issue was fixed in 2.0 back in august
I think after hours of working and fixing the bug, i will keep the netcode 2.1.1^^ I don't want to change my code again...
Oh thanks, then the failure of the build is caused by a problem on my side
I'll recheck my settings
Hi there! New to the discord, but been using Unity for years. Currently working on a Unity 6 multiplayer project in which I'm attempting to synchronize player info from the server to clients using ClientRpc and ServerRpc. However, on my non-host clients, they are not populating with the info even though on the host's end they seem to populate correctly. Are there any NetworkObject settings I should know about to make sure that type of synchronization works correctly?
you may want to share your (relevant) code
All the pieces work together in this script, but I removed about half of the code not relevant to this issue (though still a decent amount involved). The main crux is the AssignPlayerNumbersAndPieces, and its involved ClientRpc functions)
so what exactly isn't working, the AssignPiecesToPlayerClientRpc doesn't receive the correct values on the client?
As of right now, the players are receiving the information correctly on the host's client (each player has all their information fully filled out), but for any other client connected, the players information is empty (such as their sprites and prefabs). To me, it seems like it should be working correctly on the client's end based on the code, which makes me wonder if its a scripting issue or a network object setting I am missing that needs to be enabled on the player prefabs
Their network object info on the player prefab
did you check whether the other clients actually get the RPC? did you put a unconditional log in there?
The only data that will be synced are through Network Variables and RPCs(or Custom Messages) . Sprites and Prefabs are not serializable so will not be synced
Hmmm I have not. I will attempt to do that
So if I want the players to acquire their sprites and prefabs upon the game starting from the OnlineGameManager, is there a workflow that can work? I read about potentially referencing the sprites in the resources folder as an option
Usually you store things like that in an array or a list, and then each client can search for it locally with an ID or index
thats not the issue here
@austere yacht this is his current issue. We're telling him ways to design around it.
did you read the code, there is no sync of unsupported types
his issue is logic flow and that some RPCs don't get sent
signatures like this not working
[ClientRpc]
private void AssignPiecesToPlayerClientRpc(ulong playerNetworkId, ulong largePieceId, ulong mediumPieceId, ulong smallPieceId)
{
another question would be why its architected in this way, and whether thats even neccesary but at this moment that seems irrelevant?
I initially wrote that portion based on a recommendation I received, but it may not be relevant to the proper way to implement the data for the clients. Very open to other avenues in how to implement the player assets properly
I understand he's not trying to directly sync unsupported types. But if you change something like a Sprite on the host's end, a NetworkObject is not going to automatically sync it.
and that's what he's doing.
So yes, I did read the code.
StartGame() -> AssignPlayerNumbersAndPieces()
is all gated by if (!IsServer) return;
which calls functions that set sprites locally on the server only
So for any sprite or prefabs or things of that variety, I have to reference a file of that instance instead of referencing it as a prefab in the script (e.g., reference the Resources/Script/asset if I want to reference it)?
I was gating it via that so that client's couldn't make changes to the game itself, but could that be gating it so that they aren't populating as well?
How you want to handle the logic is up to you. I personally wouldn’t do anything related to pulling files from the Resources folder - IMO that’s overkill. I would simply just make a manager script that all clients can reference and store sprites there.
Hmmmm is that not what I'm doing with the current script though? I currently have prefabs and sprites that then are assigned to the different players based on their player number
Also thank you all for the insight! This issue is bottle necking my project quite a bit unfortunately, so this is very helpful so far
@fluid lily I’m not 100% sure as I’ve only briefly gone through your code, all I can say is that it looks like you’re setting sprites through this flow of function calls which only the server does. Meaning the clients have no knowledge of those sprites being assigned.
Hmmm okay that makes sense. So in that regard, would I follow a similar flow function that would be called upon that completing which replicates this actions via ClientRpc?
Or rather just not restrict that to server only and let it run for everyone?
Yep! Those are both options. I’d probably go with the second if you can make it work for your setup.
Understood! I'll try some of these changes out. If I run into more issues, I may return! Haha. Thank you
with a class INetworkSerializable` it can only be used in RPCs or Custom Messages. Network Variables can only use structs
with a class?
Hi, so I am making a server authoritative movement system using Fishnet. I was wondering what the industry standard is for sending inputs from the client to the server? Is it fine to be sending the inputs using rpcs every fixed update frame? Should I be optimizing it so that we only send inputs when relevant such as when the input is changed? Is the difference between the two minor?
industry standard is that you don't use fishnet, you will not be able to make anything close to "industry standard" when using a bad solution with a lot of bugs
I was under the impression fishnet was a mature solution for Unity.
It’s certainly more mature than NGO
What’s your take based on?
the dev spams everywhere that it's a mature/good solution, and he's banned in this server and many others for that and for other reasons
and it's not more mature than NGO. NGO supports host migration, very core feature for indie games, fishnet does not
fishnet has a lot of bugs and is very jittery. that's what i hear from every fishnet user, and myself when i first tested it
I see
Very interesting
But NGO is flawed and over engineered.
It’s not anything I would consider
These are both just opinions. Both solutions are suitable options for a variety of different projects.
Just out of curiosity has NGO been deployed as a network solution to any serious FPS game?
you talked in this server for the first time ever to defend fishnet
new fishnet creator alt?
Nope
Wrote my own netcode because neither fishnet nor NGO were adequate
I’ll stand by what I said
yet you talked in here for the FIRST TIME EVER to defend a third party solution
Recently new to discord and I found I like it
Not defending fishnet, just thought it was better than I had thought
Actually worked with unity for several years prototyping a FPS (and thus my own netcode) but then Unity happened last year and I went looking at Godot, then Unreal, and now building my own engine.
you are not making a lot of sense, you said you wrote your own netcode yet you still care to talk for the first time ever in this server to defend a third party solution
I said from the start “I was under the impression…”
I honestly don’t see how that rises to defending anything
you said it's more mature than ngo and that ngo is over engineered
belittling another solution to make fishnet look better
Those were my impressions from what I had read a couple years ago on the Unity forum.
I am not here to defend it. I accept what you said.
Why did what I say bother you? It’s just my impression from a couple years ago.
fishnet creator has many alts that do this exact same thing, maybe you are being honest here, but it's not looking like it because your first conversation ever in here was defending it, exactly what the alt accounts do
I see
Well I never felt like being active on discord until I began building my own engine. That lead me here to the Vulkan servers. The rendering engine is the big unknown for me. I am learning graphics engineering at this point. The discord server for Vulkan is great and now I love discord (who would have thought?)
yet you keep an eye on the networking channel for an engine you don't even use
smh
I just thought I would peek in on unity network server.
to defend fishnet...
ok, i am done
I may return back to Unity for my first title (or unreal). My engine won’t be ready for at least two years .
Being that the Fishnet dev has sleeper accounts, uses alts to promote their asset and employs other users to do the same, it's suspicious. But unfortunately you can only be vigilant and choose to not engage.
If you want to continue the conversation, at least make a thread.
@compact agate !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
ah thanks !
didn't mean to spark a war 💀 but uh yes i do know of the downsides of fishnet but i want to experiment with it and test it out. but going back to the original question, is it fine to be sending the inputs using rpcs every fixed update frame? Should I be optimizing it so that we only send inputs when relevant such as when the input is changed? Is the difference between the two minor?
Depends on your game. But as long as the RPCs are not being send reliably then it should be fine
would this work for a fast paced, top down 2d roguelike? im not too worried about cheating. just want to provide a fun game for friends to play if they wanna cheat go ahead xd
I would go with a Client Authority model in that case. Much easier to work with
ahhh ok ok i was thinking about that but doesn't that mean i wont have one source of truth? ill have to deal with race situations such as clients both attacking the same target and "killing" that target, etc.? do you think that those downsides outweight the responsive feel of client authority?
Again it kinda depends on you game. The host is still running the simulation and would resolve any race conditions that pop up.
ah ic ic so a hybrid approach where certain things such as player driven actions are done by clients like movement and animations, while other more important things such as health management, and projectiles are handled by the server?
Thats basically how I handle it. the Players handle their own movement and stats. The host handles movement and stats for everything else. Projectiles are a bit tricky. They need to be instantiated local then requested to be spawned.
thank you so much! this perfect for what i want ill probably go with this ^^
idk why but when i try to run host and client client all time auto reset itself and need to click Start Client again... and again and again and cant connect. When i killed both finally i got msg in console "[Netcode] NetworkConfig mismatch. The configuration between the server and client does not match" but idk HOW XD cuz i am using unity6 config that spawns one additional window of game...
Im having an odd issue relating to network rigidbodies.
owner authoritative network transforms, all 3 options on the network rigidbody checked
the rigidbody is NOT kinematic, but won't move at all. I am only setting the kinematic state when the player is dead, and the player is not (I have 3 things telling me the player is not dead), and dead is evaluated BEFORE kinematic is set regardless.
The owner of all objects is correct
Only the host can move. Client-owned network rigidbodies act kinematic even when they're not
screenshot 1 is of the properties window of the client's instance. Their rigidbody is not set to kinematic
screenshot 2 is of the host's inspector of the client's character. their rigidbody IS set to kinematic, as it should be because the host does not own this player.
Has anyone encountered anything similar to this?
the same statment that i check if thre gameobjectg is not null?
I have very little experience here haha
you want to find out if you (the person running this function) are the owner of the object
like such:
if (gameObject != null && IsOwner)
{
// Find the camera that is a child of the player
playerCamera = gameObject.GetComponentInChildren<Camera>();
if (playerCamera != null)
{
Debug.Log("Player camera assigned successfully!");
}
else
{
Debug.LogWarning("No camera found as a child of the player!");
}
}
else
{
Debug.LogError("Player GameObject is not assigned!");
}
Yeah.
aaa code block not working moment
You'd just skip all of that
oh right, and more pertinently...
the Camera shouldn't be enabled for anyone but the owner of the object
hey, sometimes when i change something on my player prefab in unity netcode and run the game and try to join as a client i get these error messages
how does one go about disabling the camera for not owners?
Are you using ParrelSync to test this?
make sure that the client copy got reloaded too
well, you have an IsOwner property...
what is that?
Probably not then, haha
But then how are you testing your game?
I know Unity got some kind of in-editor testing system recently
im using the new unity multiplayer play mode
yeah thats what im using
like such?
if (!IsOwner)
{
// skip over this somehow
}
else
{
playerCamera = gameObject.GetComponentInChildren<Camera>();
}
You should be disabling it if (!IsOwner)
Literally just cam.enabled = IsOwner;
The error makes me think that the client is using old data somehow
yeah, i just tried it by just building the second build and it works normally
wait, you're making builds?
An old client build definitely won't be able to talk to a newer version of the server correctly
Networking is all about understanding what should be the same for every player and what should be different
i fixed it by restarting the player in the multiplayer play mode window
In this case, IsOwner produces true for one person and false for everyone else
This allows you to produce divergent behavior
before this in editor feature came out yeah i did
is there some other way or what?
thanks
what does "restarting the player" mean here?
now none of the cameras work lmao
i disabled and enabled the player
i've probably done something wrong again
is IsOwner ever actually true?
it should be
You should be using OnNetworkSpawn instead of Start
oh
it doesn't exist according to visual studio
instantiate though
Make sure its a NetworkBehaviour
it is
public override void OnNetworkSpawn() { }
ah thanks
real
oh no nvm i know what the error is
now its never setting the camera ever
and throwing a nullreferenceexception for the camera 🫠
I would just be dragging the camera in to playerCamera in the inspector instead of doing GetComponent for it - could make debugging your issue easier
i would do that but the player is a prefab and it doesn't let me do that
oh
it did let me
but it's still not working
IsOwner is never true apparently
it always thinks the host is the owner now
aaa i fixed it!!
turns out when setting the camera, i also didn't question if isowner again
i used to work on gtag fan games but if I added Photon Engine to implement multiplayer in my game, would that work or would it mess up?
cause Photon would allow me to have multiplayer.
Or could I do netcode and then Photon Voice?
i think i might use the Photon Quantum
Adding multiplayer after the fact is going to be a bad time. It's doable but it's going to require reworking large parts of your code.
I don't know what type of game this is but Photon is an option. I use Unity Netcode and Vivox for voice chat.
dang
my game is a multiplayer strategy-speedrunner. It is singleplayer rn, but I am adding multiplayer, you run up towers and shoot other players down so they fall.
here is a example: https://www.youtube.com/watch?v=2rxbKp25Pgg
Hey guys, I need help with this error. I got Photon Quantum working, but Photon Voice 2 isn't being imported and this keeps popping up.
Hello! I have an issue where the code keeps sending 429 requests to join a lobby. I've tried many ways of fixing this (unity discussion page, stackoverflow, and the least helpful chatgpt)
I keep getting the same error where it requests to join the lobby too many times and crashes.
The code is as below in the link:
https://paste.ofcode.org/Mmtv45aVtqkAs2t7N6CTGz
Please may I have some assistance?
Thanks.
Edit: it keeps running line 147 (logging the debug for the LobbyServiceException)
You're calling JoinLobbyByCodeAsync back to back.
How do I add https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop?path=%2FPackages%2Fcom.unity.multiplayer.samples.coop#main to my Unity? I have used Git URL but it still isn't working for me and says that it is invalid.
WAIT WTF I DON'T EVEN NEED NETCODE??
you need git installed
so i have another error. it says the join code could not be found
hold on i gotta link the relay script now
Relay script: https://paste.ofcode.org/37AsgPrW6hzwyQvgMYzvLtY
but it also says it joined the lobby above
If you just need the normal basic functionalities of Lobby/Relay and are using NGO, I'd reccomend this: https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual
it combines Lobby/Relay/NGO quite nicely
thanks. i'll have a read
all of the Lobby and Relay code you're doing currently is wrapped up in to a couple lines on this package
hold on so i unnescacarily coded this then?
aa i'll just make another project and try again
It's always good to know what Lobby and Relay are doing under the hood, but yeah, this handles a lot of the routine stuff people use Lobby and Relay for
thank you!
i'll check it out in the morning as i've been handling the same errors for a while haha
Hi guys, I'm 100% new at networking, someone can give me some tutorials about it? Of course about networking in Unity.
it is
Can anybody here help me figure out what is wrong with my Mirror/Steam project? I was following this tutorial here: https://www.youtube.com/watch?v=kld9sINMLGw
Everything in the editor works perfectly but when I build it it doesn't work. I am using Unity Version 2022.3.53f1, Mirror version 40.0.9, and FizzySteamworks version 4.4.1. I haven't added anything additional besides the tutorial code. I can attach the scripts below.
I realize I should also send the log file from running the build. It seems like 90% of the errors are coming from NetworkWriter, and NetworkReader. None of the errors are coming from the tutorial scripts that I rewrote. Here is the log file:
Sorry, I just figured it out. If anybody else has the same issue though just follow this thread on github and use Mirror version 46.0.4:
Hi everyone, I'm currently working on updating my project from Photon Fusion 1 to Fusion 2. After updating to Fusion 2, I encountered the following error:
AssetsScripts\Photon Scripts\MapLoader.cs(37,85): error CS0246: The type or namespace name 'FinishedLoadingDelegate' could not be found (are you missing a using directive or an assembly reference?)
Here’s the relevant code snippet causing the issue called MapLoader.cs. Has anyone else encountered the same issue? I need some help.
How can I check from the client's point a view that the host has disconnected ?
Does ConnectionEvent.ClientDisconnected fire for the client iteslf?
It gets fired on the server and the disconnecting client.
When the host disconnects, the entire network drops for everyone.
so I'm starting to get into networking (ideally with dots/ecs but wow that's hard to jump into both lol), and I just want to check some presumptions I'm making but not confident in:
- If the client sends inputs and predicts its movement, but the server is fully authoritive over the final position, movement hacks cannot exist
- Sending only inputs means that you would use a weapon (e.g.) on both the client and server side instead of the client telling the server what it thinks it shot
- This might mean there's issues with latency mismatch, and so you still need to account for what the client thinks is true some of the time
Ok thx
Hey, I need help on something about p2p networking, I got a little bit confused, I am using Unity.Netcode in Unity 6 and I got making lobbies and joining them working, When on Lan/local network I can connect it works perfectly, I create a lobby on one instance and join from other, it connects, shows the name on player list and controllers are all working as they should, but when I try to join a lobby from a different network, it does join, I can see the player names on both sides, but on the client none of the player controllers spawn, and on the host, only the client's controller doesn't spawn (I also tested with 3 players, 2 are in same network 1 is remote, local ones are working fine but only the remote one not spawning and can't don't have other controllers.)
Yea, that's how client prediction works
ok nice ^-^
hi, quick question.
when signing in annonymously, does the following code:
InitializationOptions hostOptions = new InitializationOptions().SetProfile("host");
InitializationOptions clientOptions = new InitializationOptions().SetProfile("client");
await UnityServices.InitializeAsync(hostOptions);
it makes it set host profile. does this impact anything at all or is it normal? (start function btw)
You mean the player objects are not spawning?
That's recommended if you are using the same pc to test
thanks!
if i do get it working properly, do i switch it to client?
or will it not matter?
You'll need to figure out how you want to switch between the two
Ah alright. Thank you!
If i get this finally working i’ll hVe a play
Yes when the remote player connects, but the player object does not spawn only on the remote connections.
on the client that's connected: neither the existing players (only the local network ones can spawn I mean those) or the joined player (self).
on host: only the remotely connected player doesn't spawn
Are you spawning the players manually? or automatically with the network manager?
Network manager automatically spawns them
so i have an issue...
the host successfully creates the lobby and the client joins the lobby but the prefab never spawns and a relayserviceexception is thrown saying the join code is not found. however when i rejoin, it says it's already a member but still doesn't seem to spawn the player
i'll link the relay script in just a seconjd
Hello, sorry to ping you again just wanted to check if you forgot abt me? ^^
if its still not spawning, then you must have console errors reventing it
I will send a video as soon as I open unity, there's no console errors
it actually joins the lobby now and says that it's joined the lobby. however, after it reaches the end of the try, it goes to the catch
public async void JoinLobbyByCode(string lobbyCode)
{
try {
JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions
{
Player = GetPlayer()
};
Debug.Log(lobbyCode);
// await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);
Lobby joinedLobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);
relay.JoinRelay(lobbyCode);
Debug.Log($"Joined lobby by code {lobbyCode}");
} // reachest the end and logs the above but then thros the exception?!??!
catch (LobbyServiceException ex) {
Debug.Log(ex);
}
}
are you using MPPM? Are you sure its properly switching profiles?
What’s MPPM?
Is it the thing that makes you use multiple windows with unity 6?
If so, i’m not using unity 6
yea, Multiplayer Play Mode. or ParellSync on older versions
Oh. I was just making a build and running the editor
ok, profile should not be an issue there
hi, is there anyone knowledgeable about interpolation between server ticks ?
The code below is called in my update, each frame
_tickInterpolationTime += Time.unscaledDeltaTime;
float interpolationFactor = Mathf.Clamp01(_tickInterpolationTime / _tickRate);
_controller.enabled = false;
_controller.transform.position = Vector3.Lerp(_previousPosition, _targetPosition, interpolationFactor);
_controller.enabled = true;
And the code below is called per tick (along with other stuff like previousPosition and targetPosition
_tickInterpolationTime = Time.unscaledDeltaTime;
However it only seems to work with a lower tickrate, like 30, when using 128 tickrate it just reconciliates all the time. I'm thinking it's an issue with how fps are unstable so the interpolation wouldn't finish before the next tickrate, so i'm curious to know how i can fix this.
hi y'all, I am working on a project where i have data from a lidar that I need to send to a quest headset. What would be the easiest way to do this? The lidar data capture system is in C++. Should I define a TCP socket ? The information flows only one way, from the Lidar system to the quest (not the other way)
For that kind of data, not 100% sure but UDP protocol would be more efficient.
there is only a very tiny amount of information that needs to flow, only a few kilobytes per second
it is basically a 4 by 4 table of integers, 10 times per second
(the lidar system sends only processed data)
just the target locations
Ah, then it doesn't really matter much, but yeah using websockets is your solution
ok thanks. The fact that the other thing on the lidar is not in C# does not matter? I can make a server in C++ and a client in Unity ?
The language difference between the two doesn’t matter as long as they use the same communication protocol. If you only need to send small amounts of data (like your 4x4 table), WebSockets would allow you to establish a persistent connection and handle messages in a structured way. Unity has libraries (like WebSocketSharp or built-in networking APIs) that make WebSocket integration straightforward.
So your plan of C++ server and Unity client should work perfectly. Just make sure the data serialization format (e.g., JSON, binary, or something else) is agreed upon between the two sides.
No problem, always glad to help ^^
Don't hesitate to hmu with a ping if you need more specific help
thanks!
anyone ?
I was researching it for you.
that's why i came here, the problem with that is that very few people go that deeply into it, they just quickly explain it
and thank you
No problem, Always glad to help ^^
It sounds like the issue is related to how _tickInterpolationTime is being handled in relation to the high tick rate (128 Hz). At such a high rate, the time between ticks is very small (1/128 ≈ 0.0078 seconds), and any instability in your frame timing could cause the interpolation to overshoot or fail to complete before the next tick update. Here’s how you can address it:
1. Accumulate Time Correctly
Instead of resetting _tickInterpolationTime to Time.unscaledDeltaTime in your tick update logic, it should accumulate time between ticks smoothly in your update method:
_tickInterpolationTime += Time.unscaledDeltaTime;
2. Use a Fixed Tick Duration
Calculate the duration of a single tick based on your tick rate:
float tickDuration = 1f / _tickRate;
Then use this value to calculate the interpolation factor:
float interpolationFactor = Mathf.Clamp01(_tickInterpolationTime / tickDuration);
This ensures that the interpolation factor scales smoothly from 0 to 1 over the duration of a tick.
3. Handle Excess Time
If _tickInterpolationTime exceeds the tick duration, you should subtract the tick duration to account for the extra time. This ensures the interpolation remains aligned with the tick updates:
if (_tickInterpolationTime > tickDuration)
{
_tickInterpolationTime -= tickDuration; // Carry over extra time
}
4. Full Updated Code
Here’s how your code might look:
Update Logic (per frame):
_tickInterpolationTime += Time.unscaledDeltaTime; // Accumulate time
float tickDuration = 1f / _tickRate;
float interpolationFactor = Mathf.Clamp01(_tickInterpolationTime / tickDuration);
// Interpolate between previous and target positions
_controller.enabled = false;
_controller.transform.position = Vector3.Lerp(_previousPosition, _targetPosition, interpolationFactor);
_controller.enabled = true;
Tick Update Logic:
_tickInterpolationTime -= (1f / _tickRate); // Subtract tick duration
_previousPosition = _targetPosition; // Update previous position
_targetPosition = newTargetPosition; // Set the new target position
5. Debugging
Add debug logs to ensure _tickInterpolationTime and the interpolation factor behave as expected:
Debug.Log($"InterpolationFactor: {interpolationFactor}, TickInterpolationTime: {_tickInterpolationTime}");
Why This Works
By ensuring _tickInterpolationTime accumulates consistently and is adjusted when it exceeds the tick duration, you align your interpolation with the server ticks even at high rates. This prevents overshooting and frequent reconciliation.
Let me know if you need further clarification or help debugging!
(I wrote this without testing beforehand from the things I saw on the internet so I need your feedback if these adjustments will help you or not. There can be something wrong with my logic but without testing I wouldn't know.)
_tickRate is already 1f/tickrate, and the rest is basically what i already do just written a different way
I understand that the logic might look similar at first glance, but there are key differences that could be causing your issue with reconciliation:
-
Time Accumulation: In your current approach,
_tickInterpolationTimeis reset toTime.unscaledDeltaTimeduring each tick, which doesn’t account for leftover time. The revised method accumulates_tickInterpolationTimeacross frames and subtracts the tick duration (1f / tickRate) only when necessary. -
Interpolation Factor: The revised code uses
Mathf.Clamp01to prevent overshooting and explicitly defines the tick duration (1f / _tickRate) for clarity and stability. -
Handling Excess Time: The revised code gracefully handles situations where
_tickInterpolationTimeexceeds the tick duration, which is critical at high tick rates like 128 Hz.
These changes might seem subtle, but they address issues with high tick rates, uneven frame timing, and reconciliation.
private void MoveClient()
{
_lastTickTime += Time.unscaledDeltaTime;
while (_lastTickTime >= _tickRate)
{
_previousPosition = _controller.transform.position;
_prevTime = Time.deltaTime;
Grounded();
Move(_moveInput, _jumpInput);
ApplyPhysics();
_targetPosition = _controller.transform.position;
int bufferIndex = _tick % BufferSize;
_inputBuffer[bufferIndex] = getInputBuffer();
_stateBuffer[bufferIndex] = getStateBuffer(_tick);
SendInputServerRpc(getInputBuffer(), _rotationX);
_lastTickTime -= _tickRate;
_tick++;
_tickInterpolationTime = Time.unscaledDeltaTime;
}
}
This is my tickrate method, using _lastTickTime instead of _tickInterpolationTime does nothing. The reason i was resetting it to Time.unscaledDeltaTime is to make it finish one frame earlier than the next tickrate update to account for unprecisions, however none of those solutions, logically, are perfect
I mean we can only work with the data from the last frame since we can't know the future, so realistically no perfect solution is present. But predictions can be made, like you can get an average of the frametimes and make a healthly prediction too by using it directly or using it to weight the current Time.unscaledDeltaTime
yea i figured it kinda works if i end the interp way before the next tick but once again this will vary if i change the tickrate so idk what to use
Hey do you mind if I ask to AI smth about your code?
i don't mind
Okay thanks
It gave a solution but not sure if it's gonna do much differenct, as far as I see it did some adjustments and explained them, which make sense on the paper but not far off from what we already have on your code.
Though I can give the response it gave if you want to give it a try
i think i know what it does lol, when i hit a roadblock i do it too
but this is ultimated undocumented roadblock
So I am the Head Manager of Shrouded development. I’m here looking for people that want to hire devs. I recommend you come to us for mostly builders, scripters, modellers, animators and clothing designers. We offer phenomenal devs with astonishing results. If you’re interested please dm me so we discuss details etc. We look for good pay and take basically any project.
It said this followed by the code it gave.
Instead of resetting _tickInterpolationTime to Time.unscaledDeltaTime each time, consider smoothly accumulating the time between ticks and making sure that you handle the transition between frames more carefully. Here’s how you can improve the code:
yeah smoothly means at a regular rate, so using deltatime, but since frames are inconsistent, the interpolation might end up after the next state, which causes reconciliation since the player isn't at the right location
Which brings us to same loop where the problem arise
indeed, why is interpolation not documented enough
I really have no idea, I wish for more documentation on that part too. I have an possible way to find a solution but it's a little unorthodox.
what is it
Check how other engines if they've documented interpolation, there may be some stuff that'd lead to a solution, maybe you can take some logic that works from there to you adopt to your own project
idk how to do that lol, idek what project to look at
We can hop on DM's for more detail
sure
You can look at how Network Transform handles interpolation
how did i not think about that sooner... I thought about looking at the rigidbody's interpolate setting but its not opensource
ty
ngl that's genius
nvm the code is insanely huge and uses a lot of functions and variables idek how a human can read that stuff
Lol, it a lot but it's in there
AnticipatedNetworkTransform might be what you need
does it work with server auth
it is explicitly server auth only
oh god thank you i'll try that
Client anticipation is only relevant for games using a client-server topology.
You are a godsent @sharp axle
there is a sample here
A collection of smaller Bitesize samples to educate in isolation features of Netcode for GameObjects and related technologies. - Unity-Technologies/com.unity.multiplayer.samples.bitesize
i will just fix my code first because now it broke
somehow
aight guys i think the issue lies somewhere else
even without interpolating, i get resynced a lot when running the server on 128 tickrate
ok so high tickrate is the problem. I'll stick to 60hz servers
does anyone know if the character controller's slope logic cause random movement ? Because it's causing my client to desync when i move my capsule around edges
Hmm can sounds like undeterministic physics issue?
it sure looks like when i was trying to replicate a rigidbody, it's only when i walk on edges, the rest is totally fine
There's one component that made specifically for rigidbodies, are you sure you are using it?
Ahh I see, but when you use rigidBody, make sure to use the it
yes thanks
aight im sorry i gotta send a file but please someone tell me why is this, running on 60 tick per second, RANDOMLY getting out of sync ?
I tried everything i could, but nothing worked, i'm tired... Ignore the lerping function it's not definitive and also does not concern the issue. Thanks
also idk if it helps but the higher the tickrate the more desync i get
Code seems fine, issue can be somewhere else, we can inspect more in detail when I have a free time if you haven't solve the issue then
gonna sleep now and tomorrow i'm out all day. I swear i want to give up once again because it's bugged out
No giving up, we will fix it when we both free 
i've restarted so so many times because there isn't a single damn soul competent enough to explain from beginning to end how to do the MOST IMPORTANT basic secured multiplayer setup
like the ESSENTIAL
you just 'figure it out'
i mustve made like 20 projects in a few months
There is nothing basic about client prediction. Its a hard problem. NGO Client Anticipation gets you about 80% there but doesn't cover physics.
it's not basic but i don't understand why using videos, reading docs, and even using ai i can't setup physicless normal client prediction in weeks, when in one week i made a voxel engine with no knowledge... I even tried mirror and fishnet, but same lack of ressources
yet so many people make it, it makes me feel dumb for no reason
The anticipation sample I posted is exactly that
i'll look into it tmr thx
i'm just so mad rn
Don't worry we (at least I) feel you
gn
gn
Hey guys. Before I go ahead with an idea that im having. I just want to know if its possible. Im looking at doing a doom clone with multiplayer. My question is how would I tackle the enemy sprite look at and sprite change between different players. Would I just locally render them? Would that be the best?
Also with animation I'm obviously gonna need multiple "shooting" animations for each direction too.
The usual rule of thumb for networking things is the server handles the logic, the client handles the cosmetics
I.e. Server tells clients where it's looking, clients choose which sprite to render based on their local perspective
u are using chatgpt to write this?
100%
To format and fix the grammar, my English is not that great so to keep it easy to understand I paste the code + explanation it just formats it.
This would be handled locally. Monster prefab would have all 8 or whatever sprites, then locally based on the main camera position the monster would switch to the correct sprite.
Unless you have an army of artists, it might be easier to use a shader to this same results. Like how Dead Cells does it
It is against the rules, using chatgpt will get you banned here
I see.
I have trouble setting a TCP server in C++ and a TCP client. How does this work exactly, should the Client request the connection to the TCP server? The client just needs to know the TCP IP address (the IP address of my computer that runs it) and the port ?
I think its fine as long as you label it as such. But I'm not a mod
the client can connect to any TCP server that is listening on an address
I will ask the mods, I just wanted to make my sentences easier to read, didn't use AI to make the code, logic and code adjustments were from me, if I'd format it manually it would take so long to reply with a readable way, I just wanted to help 😔
Anyone?
how come when using Unity netcore, if I start an instance of the game as the host, and then move to the top left corner, and on my clone of the game I join as a client, itll spawn the character in where the host left off but there is only one player on the screen? shouldn't there be two?
hi y'all, for the TCP server in C++, I have a weird issue. I am trying to check if the server is working by running Putty to connect to it. If Putty runs on the same machine, it seems that a connection happens (from what the server side says), however if Putty runs on another PC nothing happens. What could be the cause? I also noticed that wireshark only shows traffic on that particular port (5002) if it runs on the same machine as the TCP server. I added an exception for TCP port 5002 inbound and outbound on windows firewall, but still no change
Hey so I am thinking of writing a server in C++, and client logic in C++, only thing is, the server will be a completely seperate program from the unity game application. Is this a good way to do things? I'm not sure how people implement anticheats, if it's just serverside logic that detects strange packets, or if its a server running the gameworld and checking strange behavior within it.
that's how it works in Python, and that's how the protocol works, client sends ACK to begin with
sorry
I meant client sends SYN request first
then the server sends back an ACK
I have the same problem, trying to write a TCP server that is in C++ because i have a lidar that works in C++, completely separate from my quest (I need to send the data to the quest)
you're making a VR game?
no I am a faculty in engineering and I want to make a demo system for traffic safety with AR
it is passthrough
my students have some trouble (civil engineering) so I am taking the holidays to implement the app
what is a quest?
meta quest 3
augmented reality
kk
I think that you could definitley implement that quite easiy, you dont need any anticheat, all you really need to do is send data over the connection whenever a client performs some sortof input
Im worried about implementing it in my case, because I'm making a multiplayer game that would have the requirement of preventing cheaters
you could possibly be using a LAN address instead of a WAN address
does your ip look like 127.0.0....
no it looks like 192.168...
yeah thats a LAN address im pretty sure
yeah you have to find your WAN address
with ipconfig ?
let me figure it out quick
with ipconfig in the Wireless Lan adapter section it gives me the same address
Try ipconfig /all
You should have some different addresses pop up, including your WAN address
That’s the address your quest will have to try and connect to, and then connect to the same port you have selected
It’s possible that there’s another issue causing the quest to not connect, but if you write the logic this way, it should be able to work at other locations, you just have to be sure to know what your WAN address of the host is when trying to connect to a server
I got the address from ipconfig. The weird thing is that the PCs can't even ping each other
I can ping 8.8.8.8 for example with no issue. But the two PCs connected to the same wifi gateway cannot ping each other
That sounds like a firewall issue. If you are on a school or company wifi there may be router settings to prevent random inbound connections
so I am at home, I have been messing up with the setting of my wifi gateway. I was able randomly to be able to eventually ping my gateway (I could not before, despite the fact I had internet), however strangely I can ping my quest headset, devices like my cellphone, but not the other computers on the network. Super weird.
I could ping the quest from my PC so it should be fine ?
ok now I have a better idea. I used wireshark to see the packets. I see that my quest sends a SYN packet, and after that keeps sending SYN retransmissions. There is nothing sent back by the TCP server
Hey guys im pretty new to networking and was wondering if u guys could help me with this problem: I have a bullet projectile and it works fine on the server and functionally it works fine on the clients too but visually it looks extremely choppy. Since the server is the one that owns the object it looks fine there so how can I make it look nice on the clients too. My game will not be server authorative if that matters.
Are you using rigidbody/physics or directly applying transforms to you projectile
I am applying the movment directly to the transform
I had trouble with the projectiles phazing through walls with the RB so I just used the transform and raycasts
Then interpolation might help you a, though it wouldn't fix choppyness 100% on unstable connections
try different configurations of these interpolation features to interpolate between ticks so it reduces the choppiness
ok ill try that thanks
Always glad to help ^^
you can always ping me if you need further help
Wow it worked better than expected, the projectiles look pretty good even with high ping. Thanks again for the help!
You're absolutely welcome ^^
Hey, I have no issues on this local testing of two editors connecting on the same computer but when I try to create a lobby on one device and connect from other everything goes south. This is the original NGO example from Unity, it was working when I created the project a few days ago. But now not working at all...
On the images all of them are connected to same session, the image that has 1 editor is the other device that tries to connect to host.
I mean they definitelly have some sort of connection since the all of the players names pop up in all the clients and the host. But players are not spawning on clients on and from the other devices
Check for any console errors on the client side.
How come the client IDs in OwnerClientId and ConnectionEventData.ClientId are different?
What connection event type is this?
there are none
ClientConnect
There is a socket warning in the screenshot you posted
weird. ClientConnect should only fire on the server and the connecting client.
It does yes, but the ID of the connecting client doesn't match its OwnerClientId
Oh, the OwnerClientId for the network object will not be set until OnNetworkSpawn() is called. THe Connection Event would be before objects get spawned
Oh ok thank you
How would I get around that?
So OnNetworkSpawn fires for whom when a client connects? Only the connecting client?
Yeah that's generally a hit or miss, it sometimes giving it sometimes not but the result is always the same
It depends on which object this is on. OnNetworkSpawn() gets called on all In Scene Network Objects when the scene loads on all clients.
I suppose it could be some kind of firewall issue. Its allowing to join the Session through websockets but its preventing the Transport from connecting. But I would think an error would be thrown if it times out
I will check it, it's possible, even though I disabled the firewall on both devices
you put your network prefabs into the NetworkPrefabsList scriptable object that you've already assigned to the network manager
#💻┃unity-talk message
i have to put my player's prefab in the list tho, and it isn't a network prefab
can't drag it there
you have to put it into the list in the scriptable object that is assigned there in that screenshot
The player prefab should be a network prefab. make sure you are putting it in the list on the SO
i linked to your message with the screenshot where it wasn't and specifically pointed out that a scriptable object of type NetworkPrefabsList was assigned there
i'm so sorry man, i missed that
tysm
I got a weird issue... I tested a TCP server/client with the client on a meta quest and the server on a PC. I am using home wifi for all systems. On my work laptop, the system doesn't work, but on another desktop PC (non work), it seems to work fine. I have added an exception in the windows firewall rules, but it didn't change anything. Any idea of what the problem can be ?
Are you able to turn off the firewall on the work laptop? Could also be an anti-virus preventing remote connections
I put a rule to allow that particular program to work, but still nothing. I don't understand
I see that the client tries to connect, but nothing happens, no response from the server
I have this issue but i dont Know how to fix it
There's probably a method that gets called when you have joined a room. Joining a room is a networked process, so you can't immediately start doing things as if you were already in.
Got it fix but thanks
Forgive me if this isn't the right channel.
It looks like I've turned on some kind of network visualization tool in the scene and I'm having trouble figuring out what I turned on so I can turn it off.
If you don't see the multiplayer tools in your toolbars there then you can open them from the Windows -> Multiplayer menu
I am attempting to connect two players to a lobby using Relay, Lobby and NGO. The connection of the lobby itself seems fine, but approval has an issue which I am unsure how to tackle. If anyone has any ideas. Thanks.
Solved it :). My connection approval stuff was a little off
could someone help me figure out why my UpdateLocationOwnedByIndexValueServerRpc() function does not work when run by a client? am new to using Unity's netcode for gameobjects 🙏
am stuck with this
It needs to be a Network Behaviour
Hi guys I'm 100% beginner at networking, someone have good tutorial on YouTube or can help me with basics?
Hi, i want to make a generic function to send rpc, actually i got this:
{
// Récupérer l'EntityManager
EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
// Créer une entité RPC
Entity rpcEntity = entityManager.CreateEntity();
// Ajouter les données RPC et la commande d'envoi
entityManager.AddComponentData(rpcEntity, rpcData);
entityManager.AddComponentData(rpcEntity, new SendRpcCommandRequest());
// Log pour confirmer l'envoi
Debug.Log($"Sending RPC of type {typeof(T).Name} with data: {rpcData}");
}```
but AddComponentData want a non nullable variable and rpcData is actually nullable
how can i changed this to make it working?
Okay now it worked, AddComponentData can only have unmanaged struct, so i just changed this to make it worked
Does unity support p2p yet where host creates a lobby and 3 other players join, or do I need to use fishnet or mirror?
@sharp axleThis is with netcode for gameobjects?
It can be used with NGO or Mirror
Ah it seems this service is outside of the actual netcode stuff, can NGO support a player host and 3 participants then?
Over LAN? Sure
No over the internet. Lobby/Relay seems to just be a match making service hosted by Unity?
I mean when you actually in the game playing, after you joined the host
The Relay service is for connecting over the Internet
So there was something broken in the packages, I think something got corrupted, I remported the packages and recreated the scene now I can get an error even if the same issue still persists
Baselib failed to send 1 packets
0x00007fffe51516ee (Unity) Stacktrace::GetStacktrace
0x00007fffe36b1b3a (Unity) DefaultBurstRuntimeLogCallback
0x00007fffe2fb539a (Unity) BurstCompilerService_CUSTOM_RuntimeLog
0x00007fffda64ef1f (4d4cfdb4eea0ef7add2a1c1f48a9091) Unity.Networking.Transport.UDPNetworkInterface.FlushSendJob.ProcessSendResults (at C:/Users/gtame/proceduralTest/Library/PackageCache/com.unity.burst/.Runtime/Library/PackageCache/com.unity.transport/Runtime/UDPNetworkInterface.cs:347)
0x00007fffda64d78d (4d4cfdb4eea0ef7add2a1c1f48a9091) 425bfe2d860aa3fe7881d5e323e8f7d9
0x00007fffe39fc3c5 (Unity) ExecuteJob
0x00007fffe39fd4dd (Unity) ForwardJobToManaged
0x00007fffe39f96a9 (Unity) ujob_execute_job
0x00007fffe39f8a9f (Unity) lane_guts
0x00007fffe39fb714 (Unity) worker_thread_routine
0x00007fffe3bf157d (Unity) Thread::RunThreadWrapper
0x00007ff8d101e8d7 (KERNEL32) BaseThreadInitThunk
0x00007ff8d1adfbcc (ntdll) RtlUserThreadStart
Also got this too
Failed to connect to server.
UnityEngine.Debug:LogError (object)
Unity.Netcode.Transports.UTP.UnityTransport:ProcessEvent () (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs:924)
Unity.Netcode.Transports.UTP.UnityTransport:OnEarlyUpdate () (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs:973)
Unity.Netcode.NetworkTransport:EarlyUpdate () (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Transports/NetworkTransport.cs:126)
Unity.Netcode.NetworkManager:NetworkUpdate (Unity.Netcode.NetworkUpdateStage) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Core/NetworkManager.cs:324)
Unity.Netcode.NetworkUpdateLoop:RunNetworkUpdateStage (Unity.Netcode.NetworkUpdateStage) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Core/NetworkUpdateLoop.cs:191)
Unity.Netcode.NetworkUpdateLoop/NetworkEarlyUpdate/<>c:<CreateLoopSystem>b__0_0 () (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Core/NetworkUpdateLoop.cs:214)
`private void OnCharacterButtonClicked()
{
CharacterSelection characterSelection = GameObject.Find("Canvas").GetComponent<CharacterSelection>();
characterSelection.ReplacePodium(((int)NetworkManager.Singleton.LocalClientId), buttonCharacter.podiumPrefab);
Debug.Log(NetworkManager.Singleton.LocalClientId);
}`
` public void ReplacePodium(int index, GameObject newPodium)
{
if (index >= 0 && index < podiums.Length)
{
// Destroy the existing podium at the index
if (podiums[index] != null)
{
Destroy(podiums[index]); // Clean up the old podium
}
// Instantiate the new podium at the same position
podiums[index] = Instantiate(newPodium, podiumPos[index], emptyPodium.transform.rotation);
Debug.Log("Podium replaced at index " + index);
}
else
{
Debug.LogWarning("Invalid podium index for replacement");
}
}`
how can I make this work for all players syncronized. What I want is example if it's second player on the network, it should change second podium not first and it should be synced with other clients too.
I made relay and lobbies already with tutorials but Im kinda stuck here.
I would make ReplacePodium() an RPC. I would make a list of podiums on in the characterSelection class, then send that index for newPodium in the RPC.
can you give me an example please?
Of an RPC?
[Rpc(SendTo.Server)]
public void ReplacePodiumRpc(int newPodiumIndex, RpcParams rpcParams = default)
You can find the full docs on RPCs here
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
[Rpc(SendTo.Server)]
public void ReplacePodiumServerRpc(int index, GameObject newPodium)
{
if (index >= 0 && index < podiums.Length)
{
// Destroy the existing podium at the index
if (podiums[index] != null)
{
Destroy(podiums[index]); // Clean up the old podium
}
// Instantiate the new podium at the same position
podiums[index] = Instantiate(newPodium, podiumPos[index], emptyPodium.transform.rotation);
podiums[index].GetComponent<NetworkObject>().Spawn();
Debug.Log("Podium replaced at index " + index);
}
else
{
Debug.LogWarning("Invalid podium index for replacement");
}
}
I made that but it gives error Assets\Scripts\CharacterSelection.cs(32,9): error - ReplacePodiumServerRpc - Don't know how to deserialize UnityEngine.GameObject. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. If this type is external and you are sure its memory layout makes it serializable by memcpy, you can replace UnityEngine.GameObject with ForceNetworkSerializeByMemcpy`1<UnityEngine.GameObject>, or you can create extension methods for FastBufferReader.ReadValueSafe(this FastBufferReader, out UnityEngine.GameObject) and FastBufferWriter.WriteValueSafe(this FastBufferWriter, in UnityEngine.GameObject) to define serialization for this type.
GameObjects can’t be sent through RPCs.
how Im supposed to do it then I just cant understand
what I want is just when player presses a button of character icon, it should replace the prefab but also sync
Have a list of prefabs in CharacterSelection. The RPC would then spawn the prefab at the index sent by the RPC
okay Ive done but I have still a issue. If it's not an rpc it works. However when I call it as an rpc it doesnt
[Rpc(SendTo.Server)]
public void ReplacePodiumServerRpc(int podiumId, int characterIndex)
{
foreach (GameObject podium in podiums)
{
if(podium.GetComponent<Podium>().PodiumID == podiumId)
{
Destroy(podium);
GameObject replacedPodium = Instantiate(MainManager.Instance.characterDB.GetCharacter(characterIndex).podiumPrefab, podiumPos[podiumId], emptyPodium.transform.rotation);
replacedPodium.GetComponent<NetworkObject>().Spawn();
}
}
}
private void OnCharacterButtonClicked()
{
CharacterSelection characterSelection = GameObject.Find("Canvas").GetComponent<CharacterSelection>();
characterSelection.ReplacePodiumServerRpc(0, characterIndex);
Debug.Log(NetworkManager.Singleton.LocalClientId);
}
Character Selection needs to be a Network Behavior
it is 😦
Hello, I need help setting up networking for my project, where do I start?
Use this guide to learn how to create your first client-server Netcode for GameObjects project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects.
thx
[Rpc(sources: RpcSources.StateAuthority, targets: RpcTargets.InputAuthority)]
public void RPC_RequestPickUp()
{
var playerManager = owner;
Debug.Log($"Current Input auth plID = {playerManager.Object.InputAuthority}");
if (playerManager != null)
{
// make sure inputauth runs the inventory logic
if (!IsInventoryFull(playerManager))
{
var internalName = identifyer.internalName;
var printName = playerManager.itemContainer.GetItemByInternalName(internalName).printName;
var itemQuantity = identifyer.quantity;
Debug.Log($"Player {playerManager.Object.Id} picked up {itemQuantity} instances of {printName}");
// add the item to the players inventory
playerManager.playerInventory.AddItemToInventory(this);
// despawn the item
Debug.Log("Calling RPC_Player Picked Up");
RPC_RItemPickedUp();
}
else
{
Debug.Log("Inventory is full on InputAuthority side");
}
}
}
[Rpc(sources: RpcSources.InputAuthority, targets: RpcTargets.StateAuthority)]
public void RPC_RItemPickedUp()
{
Debug.Log("Called RPC_Player Picked Up");
if(Object.HasStateAuthority)
{
iState = mu_item_state.picked_up;
}
}
I'm trying to change a networked variable (iState) via a InputAuthority side RPC call. This works if the host calls it, but if any non-stateAuth client calls this, it stops at RPC_RItemPickedUp();.
It prints the line before, but the Debug Log inside the RPC Never get's called, not by the host, not by any clients.
I've tried setting the rpc Targets and or sources to All, and that also has not worked.
What could cause this, how could i debug it proper?
owner is also a networked variable, and that gets update properly, which is why i'm able to use it in this case.
What networking library are you using? It doesn't look like one I'm familiar with
Photon Fusion 2
For some reason the HelloWorldManager script it tells me to copy and paste completely breaks my project no matter what
None of the scripts the guide for networkobjects gives me work, they all break my project for some reason
Any errors?
I’m just trying to get it setup how it tells me so I can customize the scripts
Assets\Scripts\RpcTest.cs(4,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'RpcTest'
Assets\RpcTest.cs(5,14): error CS0263: Partial declarations of 'RpcTest' must not specify different base classes
Assets\Scripts\HelloWorldPlayer.cs(24,39): error CS0246: The type or namespace name 'RpcParams' could not be found (are you missing a using directive or an assembly reference?)
This is likely due to importing/moving/copying scripts in to your project incorrectly? Do you accidentally have two copies of RpcTest?
If you're on too old of a version of NGO, RpcParams won't exist.
Well according to that error there is two, but nowhere else in my project, is there another script with any of that information
Unless I’m supposed to edit the source files of the plugin?
No. These are sample scripts.
If you can't find it you may need to restart Unity or reimport your project.
There's a chance these sample scripts may come with the package when you install it, but that's just a guess, you'd have to check.
How do you reimport your project
Okay so I'm able to get to the point where i click start host on the NetworkManager game object, and it works, it spawns a player instance in the game after that. But as soon as I try to create any of the scripts that it mentions after that point in the tutorial, it completely melts down, and I have to delete the scripts
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo/ following this tutorial
Use this guide to learn how to create your first client-server Netcode for GameObjects project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects.
Is there an easier way to figure out how to use this package without creating these scripts to have as examples? They seem to be very broken, which worries me that any other scripts I try to write will break it
okay i think i have sortof figured it out
shouldn't be too dfficult now, I think that other guide from unity was getting me to ovverwrite already written network variables
Hi, does anyone know how much delay the NetworkTransform adds for client interpolation in Netcode for GameObjects to allow a buffer for snapshot interpolation? Is it a fixed value like 300ms or something?
Hello
I was currently using Unity 2017 Wii U build and I'm working on using UnityEngine.Networking
After checked a bit the Wii U Unity Manual it seems i need add
[GUITarget((int)DisplayIndex.TV, (int)DisplayIndex.GamePad)]
void OnGUI(){
......
}```
To let it render GUI on both TV and GamePad
I was trying to add that to the Network Manager HUD but it seems in the ``Unity\Editor\Data\UnityExtensions\Unity\Networking``
and since it's a dll file i got to open it by using smth like IDA Pro, and i do found "Awake", "Update" and "OnGUI" of Network Manager HUD, but it's in .Net code so it will be pain to convert them one by one to C# :/
So do there got any places i can get the sourse script of it?
Network Transform doesn't do snapshots. It sends RPCs whenever the transform changes. The built in interpolation I believe is just a standard Lerp to the new position
mabye because of the RpcSources
I've tried RpcSources.All
And printing the InputAuthority before calling the RPC confirms that the localPlayer has Input Authority.
try not to call an RPC inside RPC
and its better to ask in photon discord server
It's behind a paywall unfortunately :/
I Can't seem to find it. All sources point to The Unity Networking discord, if not pointing to the circle server.
Manage your global cross platform multiplayer game backend.
That leads me here.
I'm guessing this is a discord issue...
If i embed the channel id, it leads to this.
So i have no clue what my problem here is ._.
contact their support email, they might be able to make an invite manually for you
using UnityEngine;
public class GameManager : NetworkBehaviour {
// A method to check all players' health and modify it if they are in a hazard zone
private void Update(){
if (IsServer){
// Iterate through all connected players
foreach (var player in NetworkManager.Singleton.ConnectedClients.Values){
}
}
}
[ServerRPC]
public void movePlayer(){
}
}
``` Attempting to write some code for my game manager object, for some reason, ServerRpc is giving me issues
Assets\Scripts\GameManager.cs(14,6): error CS0246: The type or namespace name 'ServerRPCAttribute' could not be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\GameManager.cs(14,6): error CS0246: The type or namespace name 'ServerRPC' could not be found (are you missing a using directive or an assembly reference?)
Its [ServerRpc] but I would use [Rpc] instead
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
Assets\Scripts\GameManager.cs(14,10): error CS0103: The name 'SendTo' does not exist in the current context
getting this issue now, do I have to import more modules to use rpc?
no, as long as you are NGO 1.8+ it should work
Make sure that this is on a NetworkBehaviour
it says its version 1.5.2, but there no updates
or maybe the option for updates isnt showing?
ngo 1.5.2
I updated unity and got the correct version, thankyou sir
how can I get a reference to the current client's id in it's script?
NetworkManager.Singleton.LocalClientId;
OwnerClientId can also be referenced on any NetworkObject or inside of any NetworkBehaviour
thx
How can you get the gameobject associated with the clientID?
nvm i found it in the docs
[ClientRpc]
public void playerJumpClientRpc(Vector3 magnitudeOfJump, ulong clientID, float jumpForce){
if (IsServer){
NetworkObject playerObject = NetworkManager.Singleton.ConnectedClients[clientID].PlayerObject;
Rigidbody rb = playerObject.GetComponent<Rigidbody>();
//if (rb. (Some sortof collision detection)
// Sideways movement of jump.
rb.AddRelativeForce(magnitudeOfJump, ForceMode.Impulse);
// Upwards movement of jump.
rb.AddForce(0, jumpForce, 0, ForceMode.Impulse);
}
}``` my server logic, I'm trying to figure out a way to detect collisions of the client object serverside, not sure how I should do this. Raycast downwards?
What does "detect collisions of the client object serverside" mean
I have an object in the gameworld that holds all of the serverside logic, takes input from client. I need that object to detect whether or not the client requesting the jump method is grounded or not,
you can use the methods OnCollisionStay().. etc if youre working with a script attached to the object, but this script is attached to a different object. The reason im doing this is because I dont want the player to just be able to send a isGrounded to the server logic
I want the object performing the serverside logic to detect on it's own, whether the client object is actually grounded or not
Client wants to jump
Client RPC Server with the input
Server checks if the server instance is ground
Server says "aight" if they are, applies the jump force, then syncs all client instances
yeah, the issue im having is how does the server check if the instance is grounded
I have a reference to the RigidBody, what can I use on that to detect if its grounded
well, that would apply like any other way you check if something is grounded
The way ive been checking is by using the OnCollisionStay() etc methods, on a script attached to the actual game object
but now im doing a serverside check, and im unsure of how to use that method on the client instance from the server
there wouldn't be a difference between how you do it on the client or server
if the server is syncing it then they are updating how it works on the client instance
usually the server syncs the physics bodies, while the client has some local visual elements for the sake of latency
Im just trying to prevent code injection
^ for a server authoritive approach
otherwise the client could just say its grounded when it isnt and infiniteley jump
at most, a client should just have authority over their own input, and maybe the camera if you want to make things easier
Yeah ive got that down, its just the simple procedure of checking whether or not the client instance is grounded, from the server object
instead of the client telling the server its grounded
program it as the server is controlling everything like a normal game
then swap it over and let it listen to client input
I got it
I just made a raycast
downwards
on player
to check for any collisions
Damn I finally got all my player movement to be validated server side, pretty stoked
I’m just hoping I did it the correct way, I made an object in the scene, attached a script to it that validates all of the player prefabs input
hello guys, im pretty new to netowkin and was wondering if any of you could help me with this issue im having, im using the NetworkObjectPool class found here: https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/v2.2.0/Assets/Scripts/Infrastructure/NetworkObjectPool.cs
but it keeps on using object that I believe are not returned yet. Here is where I spawn them:
[Rpc(SendTo.Server)]
private void SpawnBulletServerRpc(int bulletPrefabIndex, NetworkBulletParams networkBulletParams)
{
Bullet bulletPrefab = GetBulletFromIndex(bulletPrefabIndex);
NetworkObject bullet = NetworkObjectPool.Singleton.GetNetworkObject(bulletPrefab.gameObject, networkBulletParams.bulletSpawnPosition, networkBulletParams.bulletSpawnRotation);
bullet.Spawn();
bullet.GetComponent<Bullet>().Setup(bulletPrefab ,networkBulletParams.weaponBarrelPosition, networkBulletParams.bulletDamage, networkBulletParams.damageRetainedAfterPierce, networkBulletParams.bulletSpeed, networkBulletParams.bulletPierce);
NetworkObject bulletTrailNetworkObject = NetworkObjectPool.Singleton.GetNetworkObject(bulletTrailPrefab);
if (!bulletTrailNetworkObject.IsSpawned)
{
bulletTrailNetworkObject.Spawn(true);
}
bulletTrailNetworkObject.transform.SetParent(bullet.transform, false);
SetTrailClientRpc(bullet, bulletTrailNetworkObject, networkBulletParams);
}
Im not sure if im missing anything or not. The reson I know they are being reused before they are returned is because I am getting an error saying that network objects cannot be spawned if they are already spawned and because the bullet visual goes missing.
You don't have to call GetNetworkObject directly. The prefab Handler will do all that for you with .Spawn()
so all i would have to do is bullet.spawn
I'm wrong. the server calls GetNetworkObject() instead of instantiate.
and would need to .ReturnNetworkObject() before Despawning
Yea I do that here:
[Rpc(SendTo.Server)]
private void DespawnBulletServerRpc(NetworkObjectReference bulletNetworkObjectRefrence, int bulletPrefabIndex)
{
GameObject bulletPrefab = GetBulletFromIndex(bulletPrefabIndex).gameObject;
bulletNetworkObjectRefrence.TryGet(out NetworkObject bulletNetorkObject);
TrailRenderer bulletTrail = bulletNetorkObject.GetComponentInChildren<TrailRenderer>();
if (bulletTrail != null)
{
bulletTrail.transform.SetParent(null, true);
bulletTrail.transform.position = bulletNetorkObject.transform.position;
StartCoroutine(DelayedDisableTrail(bulletTrail));
}
NetworkObjectPool.Singleton.ReturnNetworkObject(bulletNetorkObject, bulletPrefab);
bulletNetorkObject.Despawn();
}
Wait I just tested something and the DespawnFunction is getting called right before they get reused so im pretty confused now
Hey guys! I need some clever mind to explain something to me, as like in traditional fassion, I copy/pasted some code from StackOverflow and surprisingly IT WORKS, however it totaly breaks my understanding of how RPCs work in netcode for go. In my uderstanding it should not work at all.
I was trying to make command pattern system with heavy layer of abstraction, but then I hit a wall when it occured to me that RPCs do not support generic methods, and network serialization does not work well with abstraction. I found someone on stack with exactly the same problem and he got it working with RPCs declared directly in a command. I tested it myself and it works, despite RPC being in a pure c# object and not any network behaviour or something, which I thought is mandatory to work. According to everything I read in docs, and whole monologue my friend GeParT, it should not work, yet it does and thus RPCs are only more confusing to me now then before...
public class TestMoveCommand : INetworkSerializable
{
Vector3 targetPos;
public void Execute(UnityEngine.Object executer, Vector3 parameter)
{
if(executer.IsNetworkObject(out var networkObject))
{
targetPos = parameter;
Execute_ServerRPC(networkObject);
}
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref targetPos);
}
[ServerRpc(RequireOwnership = false)]
private void Execute_ServerRPC(NetworkObjectReference networkObject)
{
Execute_ClientRPC(networkObject);
}
[ClientRpc]
private void Execute_ClientRPC(NetworkObjectReference networkObject)
{
//..do stuff
}
}
How are you testing this? Are you just testing it locally with a host?
Im entering multiplayer play mode with 2 instances, start host, join client, and then call new TestMoveCommand().Execute(agent, hitInfo.point); (to move agent to a place where clicked). Result is that this command is basically broadcasted and target agent moves both on client and on host
Don't get me wrong, it does exactly what I wanted, i simply can't understand why it works O.o
Yeah, I'm kind of in the same boat. From what I know that should not work. But I guess if you're calling new TestMoveCommand().Execute(agent, hitInfo.point); from within a NetworkBehaviour that may allow it to work?
Maybe... New year is coming so I'm afk atm, but tomorrow I'll test what happens when I do the same from a regular mono behaviour
This mystery must be solved nonetheless 🤔
The iNetworkSerialiable is doing nothing here. That can all be removed. If TestMoveCommand is defined within a NetworkBehaviour then RPCs should still work as normal.
If it's it's own class then I have no idea how the network manager knows which object the RPCs belongs to
You mean it works because constrctor is called within a Network Behaviour? It is called from a Network Behaviour, but its not a nested class or something to be "defined in" a Network Behaviour
Then it seems it just creates again more questions and answers 🙄
Personally I would just take a step back from where you're at currently. As mentioned above, INetworkSerializable isn't even needed and you could probably simplify this setup.
Hello quick question. Im trying to work on host disconnect in a simple form using the event onClientDisconnectCallback and checking if client id is == serverclientid but when i do the host always exits with a client id of 1 and not zero.
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
public class HostDisconnectUI : MonoBehaviour
{
[SerializeField] private Button mainMenuButton;
private void Awake()
{
mainMenuButton.onClick.AddListener( () =>
{
NetworkManager.Singleton.Shutdown();
Loader.Load(Loader.Scene.MainMenu);
} );
}
private void Start()
{
NetworkManager.Singleton.OnClientDisconnectCallback += NetworkManagerOnClientDisconnectCallback;
Hide();
}
private void NetworkManagerOnClientDisconnectCallback(ulong clientId)
{
Debug.Log($"the Disconneted client id {clientId} and server id {NetworkManager.ServerClientId}");
if (clientId == NetworkManager.ServerClientId)
{
Debug.Log("server is shutting down");
Show();
}
}
private void Show()
{
gameObject.SetActive(true);
}
private void Hide()
{
gameObject.SetActive(false);
}
private void OnDestroy()
{
NetworkManager.Singleton.OnClientDisconnectCallback -= NetworkManagerOnClientDisconnectCallback;
}
}
the given script above
it seems this bug may have reappeared or I am doing something wrong
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/2799
A host disconnect is simply the server stopping. You'd be better of listening for OnServerStopped.
ill give that a try @tame slate
There is no need to check the client id. If the client gets that event, it has disconnected from the network
oops just saw that you were checking for host disconnect. OnServerStopped is the way to go there
alright hold up getting a strange null reference that shouldnt be
that also seem not to work for me oddly.... also I apologize I am following a tutorial as networking is something i am new too.
What doesn't work?
when i used onserverstopped callback the client should a window pop up that says host disconnected but no such window appears
AFAIK, OnServerStopped will only fire for a host/server.
If you want a callback for when the client disconnects, use OnClientDisconnectCallback as you were before.
but when host disconnects then it shows a client id of 1 disconnecting not 0
which is strange to me
Why do you need to know the IDs upon disconnect?
making sure the host disconnects
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Is using Firebase for the multiplayer a good choice? I want something simple to store game instance state (player position, facing direction, current action and few others) for up to 5 players per session and would like a real-time updates out of the box, like what Firebase is offering.
Unless they have another service I'm not aware of, Firebase is just a database. So it could potentially store your gamestate but you wouldn't use it for real time communication between clients
isnt real-time database from Firebase updates data automatically across all clients?
https://firebase.google.com/docs/database/unity/start
I am just wondering if I can get away without a need for a server
If its turn based then that will be fine.
hm, it is not, but say I can do 10 ticks per second - what would be a good solution?
Hey everyone, I'm having an issue where matchmaker doesn't set the client ticket status to "Found". It just keeps processing the ticket until it times out. The pool timeout time is more than 2 mins, the server is successfully allocated, and a match is created. (Using UGS services + NGO)
Depends on the game. But I can't see it being good for update object transforms. If you don't want dedicated server then using Relay is the only other choice for real time games
Are you seeing the ticket matched in the cloud dashboard?
no
only received
You might need to double check your rules. Maybe add a relax so the game can start with only one player
Just checking, this rule should let 1 player in right?
{
"Name": "Arena",
"MatchDefinition": {
"Teams": [
{
"Name": "SoloPlayer",
"TeamCount": {
"Min": 1,
"Max": 2,
"Relaxations": []
},
"PlayerCount": {
"Min": 1,
"Max": 1,
"Relaxations": []
},
"TeamRules": []
}
],
"MatchRules": []
},
"BackfillEnabled": false
}
That should work, yea. You'll want to increase the max player count and enable backfill if you want to test multiplayer
Well it works, I'm getting this (serverside) in Engine.log:
"matchProperties": {
"teams": [
{
"teamName": "SoloPlayer",
"teamId": "13af80ea-70bb-4c98-a6d9-68ed674c17b0",
"playerIds": [
"vcNhjpduaj03v413Y4lKOtttbZZ9"
]
}
],
"players": [
{
"id": "vcNhjpduaj03v413Y4lKOtttbZZ9",
"customData": {}
}
],
"region": "5a53890e-6ae7-40fd-9320-2e9454618ccd",
"backfillTicketId": "efea07e8-d0c0-4007-b946-5168bb50591e"
},
....
If I understand correctly, matchmaker is the one responsible for setting the ticket status to found
not the server
yea. a match has been created by that point. Are you using Multiplayer Services SDK?
You don't have to. It just does a lot of the boilerplate stuff like polling tickets for you automatically.
Does anyone have a recommendation for a course or guide on how to structure multiplayer games?
This guide by Unity. Or the Code Monkey Multiplayer courses
Do you know if there's anything similar to that using Fishnet? I know Bobsi has some, but they aren't as in depth as those.
Hmm, I feel like I tried everything to fix the matchmaker responding to the client (thru ticket) on my end
Everything serverside works as expected
Is there any way I can debug matchmaker to see why it's not setting the ticket status to "Found"?
my poll looks like this:
private async void PollTicketStatus()
{
MultiplayAssignment multiplayAssignment = null;
bool gotAssignment = false;
int elapsedPoolTime = 0;
do
{
await Task.Delay(TimeSpan.FromSeconds(1f));
elapsedPoolTime++;
var ticketStatus = await MatchmakerService.Instance.GetTicketAsync(_ticketId);
if (ticketStatus == null) continue;
if (ticketStatus.Type == typeof(MultiplayAssignment))
{
multiplayAssignment = ticketStatus.Value as MultiplayAssignment;
}
switch (multiplayAssignment.Status)
{
case StatusOptions.Found:
gotAssignment = true;
TicketAssigned(multiplayAssignment);
break;
case StatusOptions.InProgress:
Debug.Log("Ticket poll in progress");
break;
case StatusOptions.Failed:
gotAssignment = true;
Debug.LogError($"Failed to get ticket status. Error: {multiplayAssignment.Message}");
break;
case StatusOptions.Timeout:
gotAssignment = true;
Debug.LogError($"Failed to get ticket status. Ticket timed out.");
break;
default:
throw new InvalidOperationException();
}
}
while (!gotAssignment);
Debug.Log("Elapsed Poll Time: " + elapsedPoolTime);
}
Is ticketStaus Timing out or Failing? Or is it just forever null?
timing out
It could be timing out due to the time it takes to spin up a fresh server. What happens when you immediately try matching again after it times out and the server is still running?
protected override void OnSpawned()
{
base.OnSpawned();
enabled = isOwner;
playerCamera.gameObject.SetActive(isOwner);
crosshairImage.enabled = true;
}```
this makes it so only the host has the crosshair enabled, how do i make it so everyone has the crosshair enabled?
If this is a scene object then it will always be owned by the host/server. You can spawn it with the player or just make it a Child of the camera
its connected to the player prefab
Do you know how I might be able to figure out what the interpolation delay for that is? For example, one of my enemies has a charge attack and I need to play the "charging" animation as soon as they start moving. Currently the animation starts before the actual movement due to the interpolation delay.
/// <summary>
/// There's two factors affecting interpolation: buffering (set in NetworkManager's NetworkTimeSystem) and interpolation time, which is the amount of time it'll take to reach the target. This is to affect the second one.
/// </summary>
public float MaximumInterpolationTime = 0.1f;
So 0.1 + the delay introduced by buffering? What I'm trying to work out is how many ticks in that buffer delay
or does that vary during runtime?
Same thing happens, ticket isn't found
I would probably use root motion animation to prevent that type of delay
I'm not sure what you mean? You mean avoid doing the interpolation of movement altogether?
right. The charge animation itself is moving the enemy
Hey, I'm currently facing a somewhat problem streaming data from unity to python. The core idea is to have a unity client that connects to the python server, Sends and receives some initial data (metadata about how the streamed data is formatted, amount of object send etc. After that the Client streams the data it gathered from it's unity scene to the server where it then get stored and processed. Currently I'm using a packet based websocket system for this task. But because of this i have to write the code for all my packets in both python and unity. The question now is. Am I actually on the right that with this packet based approach, or is there a better alternative? If yes, is there a way to avoid writing the code in both c# and python?
I would recommend google protobuf as a solution for an efficient message serialization system as it has code gen for many platforms (inc C# and python)
https://protobuf.dev/
The alternative is your "packets" being more flexible and sent in say json/xml or something else that can be parsed on each end.
off topic but Id not want to write a server in python if it needs to be quick and responsive. Tbh you could have gone with C# and solved your problem with a shared lib for your messages/networking.
There is also bebop but i dont know that much about it: https://github.com/betwixt-labs/bebop
Hey, thanks for your answer. When trying to solve my problem i actually looked at protobuf, but couldn't find a lot of projects/documentation on how to use it with unity.
Using json or xml does not solve the problem either (at least as far as i know) as you still need reader and writer classes for the json on both sides.
As we are trying to implement machine learning on the python side it is somewhat crucial that the server is written in python as we have lots of tools/pre programmed code for that language and switching would require a lot more work.
Regarding bebop there was also no info/documentation on how to use it with unity.
But i think both bebop and protobuf seem like a valid answer to my problem. So the question now is, is there a tutorial/actual implementation examples of protobuf in unity? (also bebop, but you mentioned you don't know much about it)
I have used protobuf in every project I work on where I work. The workflow is to define messages in .proto files. Then you use the proto compiler to generate the code in c# and py which represents the messages.
There is a library for each platform also. Follow the c# tutorial to see how to get and Serialize a message to/from bytes.
https://protobuf.dev/getting-started/csharptutorial/
A basic C# programmers introduction to working with protocol buffers.
hi 🙂
New to this server so sorry if this is in the wrong place. Asked this earlier and was told to go here.
But I am using Photon VR and I am trying to use an object in game as a button to switch the player model when it is pressed (I am trying to make a vr game btw). But I have no clue how to do that. Can anyone help?
Note: I am still kinda new to Unity, I have attempted to make vr games before but never followed through with anything, so this player model changing thing is brand new to me.
Hi. I'm looking for a way to querry a Unity Lobby before joining. I'm looking to implement a naming system where the player must use a unique name to join the lobby. If not, they are refused entry.
It seems impossible to querry player names without joining the lobby first which defeats the point of the system. Is there a way to achieve this logically? Note I am using the Join Code lobby system, not a publicly accessable lobby.
You could make a json list of player names Public lobby data. But also Unity Authentication Player Names are already uniquely numbered
Thanks. The problem I have is I can't get any of that data until I join a lobby. I'm tempted to just code it that way as the visuals don't necessarily need to reflect that we are already in a lobby
You can get the Lobby Data from GetLobbyAsync(lobbyid). Anyone can then get any Public Lobby Data or Public Player Data. For player names you can loop through Lobby.Players[].PlayerProfile.Name
I can't use that, the lobby is not public. It's private with Join Codes
I dont think you can even refuse connection with join codes. Anyone with the code can join the lobby
Yeah that would explain it. Thanks for the help
Sorry for reaching so far back lol. Working on my first multiplayer concept so this is all new to me. Is the localhost connection guaranteed to succeed with this IP? I would want the offline play to be easy to start up, so ideally the player wouldn't need to go through a whole UI process to connect and play offline, and all of this would just happen behind the scenes. I just don't know enough about the space to know if that would work.
Yes. 127.0.0.1/localhost is just a loopback to the current device.
Perfect, thanks!
for unity distributed authority ngo, how exactly does one migrate scenes properly? there really is no documentation surrounding it
The session owner is the one who controls scene management
Hello guys I was wondering if any of you could help me with this issue I am having. The video shows the problem. Basically the bullet trail on the clients looks like it teleports to the origin and then comes back to where it should be but this doesnt happen all of the time. Another issue is that the bullet trail doesnt activate on the weapon barrel and instead the center of the player. These issues are not present on the server despite it having a network transform and the objects are owned by the server so it should copy the same position .Here is the code that manages spawning the bullets: https://hastebin.skyra.pw/vahupecuma.csharp
Basically what its supposed to do is spawn the bullet on the server using the network object pool that unity provides and then set up a bullet trail that is a separate game object than the bullet for each of the clients. Then when we despawn the bullet we get the bullet trail game object that is associated with that bullet and despawn it too with a delay so that the trail animation finishes playing.
The bullet trail is fully a visual effect and stuff like speed and collisions are handled by the actual bullet object itself?
Yes
It is just a game object that gets spawned as a child of the bullet with no script
If it is purely visual, there's not much reason to have it as a NetworkObject that gets spawned.
I would just make it so that whenever a bullet is spawned, each client locally instantiates the trail themselves. You could do this pretty easily inside of the OnNetworkSpawn of the Bullet object.
That sounds much easier than what I have
And more consistent
Ok I'll give it a shot thank you
You've already done the heavy lifting of spawning the bullet across the network and syncing its position. It's often best to piggyback visual effects off of networking that's already been implemented.
Can I pass parameters through RPC's as their inherited type?
For example I have a class Item and GunItem : Item which just inherits it. When I make an RPC method with said Item type as a parameter and pass a GunItem through, it automatically gets recast as an Item on the client side and any value that it may have contained relating to the Gun part is lost. I tried recasting it afterwards but no luck. Also tried doing a test on just a normal non RPC method and it obviously works.
The RPC has to know what to type to deserialize. You won't be able to send abstract or Generic parameters either
so how would I go about sending an inherited type like GunItem but also be able to send a regular Item?
Need to have a separate RPC for each.
I suppose you could have optional default values and keep them in the same RPC
Yeah thats not really gonna work for me, Ill probably just have an AdditionalData struct or something like that to account for the other types
thanks for the help tho
Someone fill me in with the current networking situations please
What's the most convenient official networking solution as of right now? Netcode for GameObjects?
Is it stable enough yet? I see transport api has been deprecated
Wait no it's just called Unity Transport now
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
I think this makes the case NGO is not production ready. If you disagree, then by all means continue using NGO. Just my assessment of the framework based upon Unity's best practices described in the article.
Hi all! Getting started with Unity NGO and I was curious about how data is handled in a non-dedicated host / client environment? i.e. game is an rpg and players A & B both have the same stat types like Strength & Equipped Head ID, but differing values.
Things like Stats are usually synced with Network Variables. They can be either Host/Server Authoritative or Client/Owner Authoritative
What's a good production option currently then?
I've been away for a couple years and everything still looks like a mess
NGO is not production ready
Yet it's used in some very successful games (for instance, Lethal Company), in production.
I would say something is not production ready when it's unstable and has game-breaking bugs, which does not seem to be the case with NGO.
The products by Photon, Fusion and Quantum, have been out for years, with many successful games made with them.
If you want something "production-ready" and safe, those are what to look at.
If you want something free, but not perfectly stable, then the options are plenty for that, including the solutions from Unity (Netcode for GameObjects, and Netcode For Entities).
The only production ready code for Unity that I know of is Photon, but it isn't free - so I wrote my own netcode.
I would say something is not production ready when a serious flaw in its architecture is exposed.
But as I said, if you want to use it, by all means...
What's the serious flaw?
Did you read the article?
Not really, is parenting not supported or is it just difficult to do?
On the Unity forums two years ago there were at least two people who claimed they spent months trying to simply pick up a tool and join it to the hand transform of their avatar.
Months...
The solution - the best practice by Unity... very eye opening.
I'm not sure what you mean here. Network Object parenting is supported and does work. It just has some rules for it
I said what I wanted to say. I don't want to get into debates. I don't want to sound all negative. I just want to point out why my assessment of NGO is that it isn't something I would use. (I was accused of being a fishnet alt account for saying so, LOL).
Using distributed authority, how do u load a scene for only one player that may or may not be the host, currently I’m trying to make a portal like element where ok contact you get teleported to another scene, but I want the rest of the players to stay in the first scene until they choose to jump in too
Since only the session owner can load scene how do I make it so that they won’t get pulled in too or other players
Any help is welcome thanks in advance
You would load the scene additively. Make sure that its moved out of range of the other players. You could also use scene validation if you need to prevent the scene from loading at all on some clients
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/using-networkscenemanager/#scene-validation
Netcode for GameObjects Integrated Scene Management
Thank you
I am trying to run a Distributed Authority game on webgl, but I keep getting this error message on the console in the browser.
Relay server data indicates usage of WebSockets, but "Use WebSockets" checkbox isn't checked under "Unity Transport" component.
But the Use Web Sockets in the Network Manager in the Unity Transport is checked.
Do I need to do anything special do run a distributed authority game as webgl?
Switch the Unity Transport with the Distributed Authority Transport and check Use WebSockets there
I think that helped. Thanks. Still having issues, but that one I solved.
Another question, can I use using System.Threading.Tasks; with WebGL? I heard a youtuber saying you couldn't.
I don't believe webgl supports threads. at least not yet.
Support is limited. You need to be careful when using it due to silent failures if you accidentally invoke something that depends on threading. UniTask is a safe alternative with better out of the box integration with Unity's gameplay loop.
Hi! I wanted to know why on unity 6 while using the network system from unity the editor puts my network objects in pink

