#archived-networking
1 messages · Page 26 of 1
It's already terrible that I have to migrate from photon PUN because it's not supported anymore
migrating again if the unpopular tool gets discontinued would be painful again
alteruna multiplayer
Yo, im new into Unity how long would it take to, like start knowing the engine?
sry
I think this one is kinda popular @final laurel
try to ask Bobsi, he creates a lot of video on it
I'll check it out, thanks
Does anyone know how I can fix this, I have been stumped on this for DAYS (2).
Using Unity's Relay and Network Manager to grab the Relay join code and redisplay it when a server/host is activated on the host's screen
Is anyone else having major issues with the new Starter Assets 3rd person and netcode for objects? I just cant get it working at all. When I do, I get one character falling through the world and can only control one character, will not control the other clients. I am using cinemachine on all characters. Is it a known issue with the new starter assests controller or just me?
Hello
Guys i make project with fishnet but when i realize the video dont explain what i want and idk if there video explain what i want with fishnet
So i want ask here how can i make menu for lobbys with fish net
Sry for my english
@final olive You can get help on the Fishnet Discord if you don't get an answer here. Top right of the page. https://fish-networking.gitbook.io/docs
Okay i want ask what is the asset to help me make online game photon or netnode or something else?
what type of game it is?
The Client Driven sample uses the 3rd Person Controller starter asset
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/v1.2.1/Basic/ClientDriven
@sharp axle Ahh thank you, I will look into that one.
I think you need to typecast “transport” to the more specific type than what you’re doing there in the screenshot. See if transport is of type Relay before doing relay transport operations (like querying RelayServerData properties).
RelayTransport relayTransport = unityTransport as RelayTransport;
if (relayTransport != null && relayTransport.RelayServerData.AllocationId != Guid.Empty)
This is not how you get the allocation id
https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo
@final olive There are many networking assets. I use Fishnet myself, but the others are also good. Mirror, Photon, NGO, etc. There's a lot of different solutions. Your best best is to download them, look through each one comparing how RPCs, sync variables, etc. work, and pick the one you like. Many have demos that come with them. One of the most important things is support and being able to ask questions. Fishnet, Mirror, etc. have their own discords with 24/7 help. Pretty good free help for everyone.
i don't recommend fishnet though
To each their own. Nothing wrong with trying out every option and seeing for yourself.
its developer is not a good person
photon
When my wife was alive, I didn't think she was a good person many times. People say hurtful things or do things they regret. But, I still stayed with her because I liked the features of the asset and it was the best 10 years I had in my life. Have to take things with a grain of salt and find what works best for you.
i am sorry for your loss
you liked the features of the asset?
pls don't bring your personal life matters into a gamedev discussion
Best feature was her kindness. Cared for everyone no matter who they are and what they had done in the past. That rubbed off on me over the years.
No one is deleting anything. Stop trashing people and be nice. I know you are upset for some reason, it's okay. Everyone gets to pick the solution they want to use. Let people choose on their own. It's important they look at every option regardless of opinion to make a good decision with information they see for themselves.
i didn't trash you
you changed the subject and talked about a completely different thing
pls don't bring personal conversations into gamedev discussion
i don't understand, trying to make a point?
I think its too far to say that
@ripe mesa ngo is good or bad?
hmm depends, but most of the time bad
Mirror is a wiser choice
really?
both are not really differ, but for a game more than Indie I recommend Mirror.
I have seen couple of good NGO Games, but they are small coop games..
While Mirror has been battle-tested, I've seen and played several games with it including the MMO
nice, what games?
Heartwood online
GAME FEATURESHeartwood Online is a true cross-platform free-to-play MMO currently available on Steam, Apple, and Android. We plan to bring it to all major consoles as development progresses.Explore a vast and immersive world filled with adventure and exploration. Join forces with other players to battle fearsome raid bosses, uncover hidden treas...
the pixel art kinda not perfect: resolution and style consistency, but I find the game is solid
Why what the different
some netcodes are built for MMO, coop games, competitive, shooter, physics game
all depends on your need
I want something like vr chat but without vr a game for real life talking sit you can call it Simulation
And sry for english
simple chill, talk, with friends game?
I was think about make coz i want enter in college a room design
Yep
photon fusion, shared mode
- Free 100CCU
- No Server Required
I found a fix, restarted my script using the Unity Docs, now I just need to delcare the code so that it can update the text
can i still use a player input manager to detect if a device was connected/disconnected or is being used even if i'm making a networked game?
I don't see why not
i don't know. the split screen function of it made me think of it as a "local" feature
i mean thinking about it it should stay local
it probably should. as a client, why would I care if some other remote player plugged in a controller or not.
true that. well if i wanted to propagate what device is being used i could just reference the input manager in a player script and make the current used input device as a variable and show that, right?
That should be doable. Just not sure why you would want to
don't know. was just thinking at a "a way out" like character selection screen
Does it do this even for a network game?
yep
nvm
What .dll should I use in order to set up a websocket and make an API call?
Currently I've read about WebSocketSharp and NativeWebSocket but they seems deprecated... am I wrong?
Potential WebSocket alternatives:
UnityTransport: https://docs-multiplayer.unity3d.com/transport/current/minimal-workflow-ws/
SimpleWebTransport: https://github.com/James-Frowen/SimpleWebTransport
I don't think either of the ones you mentioned are deprecated
WebSocketSharp has been getting daily updates for the past week month and NativeWebSocket is used by a commercial multiplayer framework.
Just to give a reference of the request I'll have to do, here's the API I must figure out how to call: https://dev.hume.ai/reference/empathic-voice-interface-evi/chat/chat
Ok then I'll try websocketsharp first
are there any restrictions on doing this kind of request on webgl builds?
Not aware of any. The data is piped from WASM to JS, so if you can do it in JS, it should be fine.
Though I'm not sure if I would put a lot of weight on these changes now that I looked at them a bit more.. 😅
I just need something that works 😅 since I have poor knowledge in this topic I have to pick one and start studying it, thats why I asked here for which was the best (in terms of semplicity and reliability)
If you just need to call a REST API, then UnityWebRequest would probably be easiest
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html
does anyone know how your supposed to spawn local objects using unity netcode for gameobjects?
i keep spawning local objects using new GameObject() but every time a new player joins they seem to get deleted when i dont want them to?
Only solution i seem to come across is adding a NetworkObject component to them and then spawning them using NetworkObject().Spawn() and then changing visibility per client, but this would require me to rewrite my entire chunk system and is just a lot of hassle.
Do co-op non-compeititve games such as lethal company, deep rock galactic, phasmophobia, etc. use client side prediction? Is client authoritative movement okay? I'm not so much worried about cheating, but more so worried about how the experience will be if someone has a laggy connection
I don't think they use it.
Client-Side Prediction is not only about cheating, it also helps with making interactions between players and the environment more accurate.
Because clients are preparing their inputs ahead of time to a certain future tick in the server, that means actions between players are going to line up better than when clients are just doing things as they wish (client-auth).
It also means you can avoid other players looking laggy for good connection clients. Because the server can simulate their characters even if they have packet loss and their inputs are being lost. So with non-CSP games, you usually see laggy players teleport. In CSP games, if a laggy player was falling, it will keep falling nicely for other observing clients when that client has packet loss/jitter, because the server is still simulating gravity for them.
Also if you want somewhat accurate physics interactions and collisions, CSP is the best way to handle this.
But for a simple co-op game, this could be overkill or not needed.
Local objects are not spawned which is why they don't get replicated for new clients. You could have a separate manager that is keeping track of things a client instantiates locally in a network list. That list can get replicated to all clients
no i dont want replication thats what im saying
im only trying to create the object locally
but when other players join, the local objects get deleted
when there is nothing in my code deleting them
Weird. Regular Gameobjects do not just self-destruct.
ik thats why im really confused
ive seem to find a semi work around which is just doing it as childs of my player object
and that seems to work
but idk why i have to do it like that in the first place
is there a reason you're doing new GameObject() instead of Instantiate?
its just an empty gameobject that im adding stuff to at runtime
it happens if i use an empty prefab too anyway
Right. Makes sense.
I'm not sure about Netcode but Mirror does not like when scene hierarchies are out of sync between the server and the client.
My guess would be that Netcode is the same.
Man if only people said "NGO" instead of "netcode"
and this matters why?
"netcode" is a term for the network libary/framework
this is the correct wording:
- csgo netcode is good
- is there a game with a good netcode?
- how to build a good netcode for games?
He mentioned in his original message that he was using NGO. Pretty sure he knew what I meant. Netcode is a perfectly acceptable short form in this context lol.
I just felt like its too criminal to refer it as ngo
Also there is Netcode for GameObjects and Netcode for Entities. Just to further the confusion. Unity naming is real bad
@sharp axle
Hello all! It's me again 😁
I finally got the ClientNetworkTransform to work which then made me able to control the client player. However., when the host hits the puck, it responds properly. But when the client does, it kinda moves glitchy back and forth before bouncing off to the properly predicted position. This position isn't reflected on the host. And when the host hits the puck, the clients copy telelorts to the host copy's location
Host - right
Client - left
I need to know how to fix it so the puck syncs properly thru the host and client
I'm trying to use multiplayer play mode, but when I check the Player 2 Virtual player, it just keeps spinning and saying activating. Am I missing something?
You'll need a client prediction system to sync the physics properly. If you are on NGO 1.9.1 then you can use the Anticipation System
If you are on Unity 6, try updating MPPM to v1.1.0
I am getting this error with the multiplayer play mode:
An error occurred while resolving packages:
Project has invalid dependencies:
package: The file [...\Packages\package\package.json] cannot be found
I am using the latest
Looks like latest is 1.0.0. How do I get 1.1.0?
You can install it by name. and specify the version.
oh the minimum Unity version for it is 6000.0.3f1
If you are still getting invalid dependencies then you might need to reimport the project or just delete the Library folder
Well I deleted the folder that it was mentioning, but now I get this error in the virtual player window: Assertion failed on expression: 'scriptedImporterClass == SCRIPTING_NULL || uniqueDomainId == MonoDomainGetUniqueId()'
I'll try deleting the library folder
Yh, anticipatedNetworkTransform, it's what I used to go this far
You'll need to use OnReanticipate() to get the smoothing right
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/main/Experimental/Anticipation Sample
Another option is to use NGO 2.0 and Ditributed Authority
https://docs-multiplayer.unity3d.com/netcode/current/terms-concepts/distributed-authority/
Distributed authority is one possible network topology you can use for your multiplayer game.
You should probably take a step back before worrying about Client Side Prediction. NGO is more than capable of running a 2D air hockey game with essentially no desync and very little delay for clients. You should be aiming to get to the point where the puck is not teleporting on either host or client, and the client's puck should only be slightly behind the host's. This obviously may not be good enough for your final product, but it's where you should aim to be before adding in stuff like Client Side Prediction.
Adjusting your NetworkManager's tick rate, your NetworkTransform and your NetworkRigidbody sync settings like interpolation + thresholds and probably most importantly making sure your local code + your networking calls are as perfect as they can be.
For your final product you may want Client Side Prediction (especially if you're letting players hammer the puck super fast 😄) but again, NGO definitely is capable of allowing you to make a perfectly fun air hockey game (with just a little bit of delay for clients) even if you don't decide to use it.
The first two games I made with NGO were before 1.0.0.. CSP didn't even exist as part of the package. You had to code it yourself! Which I never bothered doing because of the reasons I stated above. If you play within the bounds of the library, you can still have basic physics sims with little delay that most players will hardly even notice.
I had the idea, but I'm so new to Unity and networking that I didn't want to ruin the settings. Also I'm running Unity on a laptop, so the long delays between script loadings and whatnot definitely discouraged me from tweaking.
I would try your idea though. Everything is a solution as long as it's not giving up 😁
Even more reason to leave Client Side Prediction until later. A lot of game development is about building blocks. You can't add the top of the tower before the base is solid. Game engines are powerful tools and if you love games it's hard not to just want to jump right to the final product and have the best game you can imagine. But it's all about iteration, don't get discouraged!
Changing the values in inspector for Network components won't cause scripts to recompile so you're safe there. Will obviously have a little effect on the wait time when you hit Play, but you always have to wait a bit for that on lower end devices anyway so nbd I'd say.
Not sure how new you are, but to help with iteration and the testing of your own code.. Attributes are really helpful so you can change values in inspector instead of directly in your scripts.
[Space] - will create a space between variables in the inspector
[Header("HeaderNameHere")] - helps you label and/or group your variables
[SerializeField] - exposes private variables so they can be seen and edited in inspector while maintaining their access level in your code
Thanks! I'm actually not that new tho
ah, just Unity AND Networking. Gotcha 😄
Anyone have tips to figure out how many server processes can fit on a particular host? I’m curious if anyone has gone through the exercise of figuring this out for themselves.
I’m using AWS gamelift, which ultimately runs on an EC2 instance. I’m not 100% sure how many server processes to start up per EC2 instance, or how to determine the type of ec2 I should want to use.
The game itself is a death match multiplayer looter shooter, if that helps at all.
You have to test that for your specific game. Besides cores which can be mapped exclusively you also need to consider other hardware resources that are shared, like the network adapter(s). Typically you can expect 1 process per real core to work out nicely, given your server is designed well and doesn’t rely on multithreaded code or saturates the NIC. If it does, all bets are off. For HPC nodes with lots of cores you can probably make it work for multithreaded servers but it’s likely better to run multiple smaller nodes as they are more isolated from each other.
You have to test that for your specific game
Yea, that’s my original question… how? Any tips?
Run the server locally and look at how much memory and CPU it's using. You should also be able to just look at the game lift dashboard to tell what server resources are being used. In a development build you can attach the Unity Profiler remotely
Is it a bad idea to have client authoritative movement for a co-op game where players are on a ship that can pitch and roll in an ocean? My concern is that if the ship’s pitching and rolling is server side, and if a client has an unstable connection, other players will see the client potentially hovering in the air or clipped into a wall. Because of this, I’m wondering if I should use server authoritative movement for everything with clientside prediction. Is this a good idea, or overkill for a co-op game where I’m not concerned about cheating? I just want the game to be accurate and reactive for players
Guess heavy load scenarios, write scripts for them to validate and monitor analytics. You can most likely figure out something relatively safe and tune it once your live.
You can run the network simulator to test against poor network conditions
https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/
The Network Simulator tool allows you to test your multiplayer game in less-than-ideal network conditions, enabling you to discover issues in simulated real-world scenarios and fix them before they surface in production. It facilitates simulating network events, such as network disconnects, lag spikes, and packet loss.
How do I handle any kind of resource collection over multiplayer with client prediction? So say a player has insane ping, collects 4 coins, updates coin counter locally. The server then registers all that and sends confirmations to the client with their current coin sounter value. So now the player sees their counte go to 4, then to 1, then slowly to 4 again. Should I instead just return a boolean from the server indicating whether the player successfully collected the thing and if no, just deduct it back on the client instead of sending the entire state?
I'm trying to spawn my players at a custom position, but no matter what i try they still spawn at their local position. Why?
[SerializeField] private Transform spawnPointParent;
private List<Vector3> spawnPoints = new List<Vector3>();
private void Awake()
{
var networkManager = gameObject.GetComponent<NetworkManager>();
networkManager.ConnectionApprovalCallback += ConnectionApprovalWithSpawnPos;
for (int i = 0; i < spawnPointParent.childCount; i++)
{
spawnPoints.Add(spawnPointParent.GetChild(i).localPosition);
}
}
private void ConnectionApprovalWithSpawnPos(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
response.CreatePlayerObject = true;
if ((int)request.ClientNetworkId <= (spawnPoints.Count - 1)) {
Debug.Log("expected spawnpoint is: "+ spawnPoints[(int)request.ClientNetworkId]); //This fires.
// response.Position = spawnPoints[(int)request.ClientNetworkId];
response.Position = new Vector3(100,100,0); //debug code, playerObject still spawns at his position
}
response.Rotation = Quaternion.identity;
response.Approved = true;
}
i'm guessing this doesn't work for the host. that's my issue, don't know how to fix it
I think it's better to just spawn the player anywhere, and then tell the server later for the desired spawn position.
Depending on your game, you might need to respawn the player again in the future.
So that way the system will behave more appropriately for the entire life cycle of the game.
I think it's a bad idea only in respect to having to enable PhysX prediction which is quite costly.
Other than that, it will make the gameplay experience way better overall, assuming you are using a proper CSP implementation.
Though, if you choose to not use CSP, there are probably many ways to workaround your problem, like parenting, etc. They will all suffer from certain limitations that wouldn't otherwise exist if you were using CSP.
This is not how client-side prediction works.
The behavior you described is a failure of prediction.
A proper client-side prediction system will make this entire process invisible to the player, the game will just play as if it's a single player game
But that's only when the client does not experience outward packet loss, or some other things that cause high degree of non-determinism.
Which means its inputs are getting lost and thus the server simply never executed those movement inputs that led the client to collect those coins, thus causing the mis prediction that might cause the coins counter to rollback.
However, usually games don't predict things like that, because of continuous possbility of other clients collecting the coins before you, causing the misprediction. But usually it's only a real problem if things like the movement of your character or other important gameplay aspects are affected by what you collect.
I have a C++ game and a Unity clientside. Is there anything out there people recommend for reliable udp/networking between Unity and a C++ program?
The Unity project will run on a Meta Quest (Android).
I’m not sure how simple it’d be to get C++ working in Unity as a native library for Quest 3, but several networking libraries are single header C++ files that should be straightforward to compile if only I knew the right build steps.
Would anyone be open to helping with this?
Thanks!
Alternatively, a reliable udp library with both up-to-date C and C# implementations?
What you are attempting sounds like a lot of pain. I wouldn't do this without huge benefits.
What part?
This isn’t a preference. It’s a requirement. Existing C++ application (server) and Android Meta Quest 3 client (Unity Engine client)
I’d like some existing networking solution if there is one, hopefully. I’m flexible otherwise.
Why is the server in C++?
Because I chose to write it years ago. The serverside is a full thousands of lines program. Meta Quest applications are easiest to write in Unity C# projects rather than native.
Are you suggesting there’s no cross-language solution that is actively maintained?
I was looking at enet
and valve’s sockets library
but eh..
Yes, was about to say that. ENET is probably what you want.
enet has a single header version
I am just unfamiliar with how to make a native android plugin to slot into Unity
valve’s library is probably more robust, but it looks painful to use
The point of this experiment is to fo some cross-device experience
Would you know how to make a native plugin?
That’s kind of what’s making me doubt this
It’s too bad Unity doesn’t have a builtin codegen thing to let you just add a C++ file
You use the C# version of ENET, and the C++ version in your C++ server.
There’s no up-to-date C# version of Enet
The versions would conflict
I think
https://github.com/zpl-c/enet This is an enet fork
Try it.
probably there’s no C# equivalent for that one
If they change the protocol it’s probably not good but ok I can give it a shot
but maybe it’s better to “own” the build process?
Yea I didn't notice that, may not work.
also standard enet doesn’t support the fork’s features
Are there any good references for just building it myself? I’m on mac, so I don’t know if Unity included a build tool. I assume I need some Android build tool.
“As of now, library can be built with MSVC on Windows and with GCC on Linux. OS X support is planned in the future releases.”
uhhh unclear if Android’s supported and I pretty much need mac support.
But okay I see what’s happening
I should just survey the libraries available a little better
But it would still help to know if anyone’s figured out a nice workflow for building native plugins cross-platform
maybe another channel?
I don't have experience with that, so can't help on that one.
fair enough
thanks for the links though
https://github.com/nxrighthere/ENet-CSharp
It may be possible to use this with a specitic other enet version, but I’m unsure
Looks like the core of this is actually written in C, so yea the modified protocol is already in C.
Oh
I could straight use the files already in there
nice
I just have to figure out how to build this though…
All it says is to use NDK. That’s very unspecific when it comes to how to set up the project… hmm
Hi, i have two player both of which are gameobjects.
How do i detect collision between them ?
they handle collision between other surfaces with rigidbodies well but between each other they just simply pass through
If these are network objects, then your physics should probably be handled by the host/server.
what else needs to be done for that ? i have added rigidbody and colliders on the player
i am not sure what you meant by handled ?
if a client fires a bullet that is a network object and it should bounce off from colliding another network object that how should i handle that on server ?
the best i can do is add collider and rigidbody on both of them. Is there anything that i am missing ? because the bullet is passing through the player object
Are you using Network Rigidbody? On the server, all collision events will happen as normal. It might be delayed on the clients due to latency
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/
There are many different ways to manage physics simulation in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.
Doesn't seem like a network issue then. The bullets might be traveling too fast. Or the Layer Collison Matrix is wrong
found the issue, edge collider was giving me problems, if i changed to box collider the collisions were happening
i used the edge collider because i wanted a triangular collider
will try with polygon collider
it worked
thanks for the help @sharp axle
I have followed along with the unity API reference for Half Vector3 but it didn't work and the player's position was not synchronized over the network. Can anyone help me out? Both method #1 and #2 doesnt work at all.
Hello. I am trying to create a multiplayer game where people can host servers and let others join with a code (Something like the game "muck")
Are there any good free solutions for a multiplayer game like this?
Also, I currently already have the singleplayer version completely done, so hopefully something where I can easily transition from single to multiplayer
i'm so sorry...
i made the same mistake once
yeah no you're gonna have to basically rebuild at least a good 60% of your game
and for servers it depends, if you want like player hosted custom rooms you could do it, but if you want like independent servers you'd have to pay that
tbh they are all really similar with the difference being in some features
So far ive tried out fishnet and mirror but IMO mirror is way more convenient
You can check out Netick too, it's the highest performing networking solution for Unity, bandwidth-use.
Easy to use and has a very easy to use Client-Side Prediction system, if you are into that.
Only Mirror, NGO, and Fishnet are similar to each other.
The new modern Photon solutions are radically different, for instance.
indeed, should've specified that
It kinda is important to the gameplay. It's not actually about coins but other resource, so I dumbed it down
I ended up just doing all the management on client with server permission
"I spent 3 of this resource"
"Ok"
"And this"
"No, this one doesn't add up, revert that operation"
And then sync it up occasionally, like when the server explicitly changes player's resource amount
Is this a good way to handle this?🤔
📃 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.
So I have a script that can change the position of an object when you hold the right mousbutton. the objekt will Lerp to the PakageHolder. problem the host can do it but the client not. the pakage objekt has a client transform commponent and a Network Gameobjekt commponent.
📃 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.
📃 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.
!code https://hatebin.com/ozqccleunv How can i change the position on the client?
What will happen when the value in the server never changes and thus never replicates to the client?
What I'd personally most likely do is not predict the action of collecting coins.
It would at the very least replicate once when the player joins
And just let the latency be?
You mean
My case is more like minecraft
Where .1 delay between placing blocks would defo be noticeable :\
And minecraft itself does prediction on this side I imagine
Main issue is handling inventory
Is your game also voxel-based?
I see a couple reasons for the server to explicitly tell the client how much they have: When they's a clear error (Player thinks they have enough resources, but they don't) and on initial join
Otherwise, since the resources change from the permission of server anyway, it should mostly be in sync
It depends on what networking system you use, and what replication system it uses.
Some netcodes would sync the entire game state each update, so you don't even need to worry about these issues, meaning the value would only snap back when the server failed to do the same actions as you.
I'm using a custom low level library that doesn't take care of this unfortunately
Ah I see
You can sync the full state of each object in the game each second, to check for desyncs.
A lil overkill 😅
Like, I read up on how old rts games were made
Yea, that's like a bad solution, but an easy one
It's basically 90% simulation
They use lockstep, they only sync inputs.
Yep. Would be hell to sync up entire state back in the day
Because when you have +1000 objects, you can't just sync the pos/rot of all of them, it will kill the bandwidth.
But this is very hard to do in Unity.
Because almost everything is non-deterministic.
So you will need to roll your own solutions for even things like AI navigation.
Though another solution to the problem of syncing objects is to use Delta Snpashots.
Eh, those can be server side I guess. I won't have thousands of units in my game
Which means you only sync changes to the networked state.
It's just that responsiveness is kinda critical in this specific system
Another one is Optimistic Replication (Eventual Consistency), Photon loves this method, but I think it's bad and has tons of problems.
It's also what Unreal networking uses.
You can have a big "networked array" for all your collectables
That you keep going through and sending parts of it, each update.
So with enough time you would have resent the whole thing.
And it won't use a lot of bandwidth. Just latency.
It's to check for desyncs.
When new changes happen, you just send them directly.
Or, when the client changes something, it marks that property as awaiting server confirmation, after X seconds the server didn't confirm, you rollback to authoritative values.
Yep, that's the idea
What I'm doing right now is that whenever client does something that would change the resource count, it immediately changes it locally, awaits confirmation from server, and if never receives or receives reject just undoes that change
Because if the server confirmed and changed it on server side as well, they should be in sync
However, when the server explicitly changes client's resource count, it sends the entire thing yeah
Something like that might not scale well.
I think many voxel games, including Minecraft, use what they call "Streaming" which is what I suggested of going through the networked data and sending parts of it each update.
What can go wrong with scaling though
The checking logic, it might be a bit slow if you are doing it for a lot of things.
🤔
Something like an Area of Interest manager would probably help with that. Photon Fusion has one built in. Netcode for Entities has a Priority system where objects closer to you will get synced more frequently than objects farther away. You can look to them for some inspiration
ah ok, do you know one that can be hosted inside unity ? we do not want to have an external server
Why such an opposition to having an external server?
Ah because we are working in an offline environment and there is no network connection
So I enstablished a simple Websocket connection to a testing url (echo.websocket.org)
Here's the code: https://pastebin.com/ja4eNd2D
Now I've tried to use the url I actually need to connect to but I always get "error 1002 can't perform an handshake" and I can't figure out why, the request syntax should be very simple.
Can somebody please help me to figure out what's wrong?
Here's the documentation: https://dev.hume.ai/reference/empathic-voice-interface-evi/chat/chat
This is the url I should point to: wss://api.hume.ai/v0/evi/chat
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Right. Interesting predicament.. You're going to be hard pressed to find a solution that already exists. If you're not going to want to code your own custom solution, you could maybe just try using one of the handful of Networking Libraries for Unity that are out there? Theoretically you could put the output of a camera on to a RenderTexture, convert that in to bytes, send it to connected clients and then convert it back on their end. I'm not sure what kind of quality or frame rate you'd be able to realistically achieve doing this, but.. I can't think of much else you could try.
@drowsy terrace you said you have two devices you want to stream the camera between.. do you happen to a computer not in use that isn't one of these two devices?
Yeah maybe we can get webrtc to work, we do not need high fidelty and a bit of lagging is ok as well. We got it working with Picos Streaming SDK but we would prefer a platform agnostic solution.
no we have no third device, one VR headset and one tablet it is
but I like your idea of raw byte streaming, I will give that a go over TCP
Is there a way to make a NetworkTransform sync on manual request rather than automatic?
I know you could do it via rpc calls but wanted to use a networktransform for the simplicity and reliability if it's an option
No. But I NGO 1.9.1, you can set the sync rate for network variables. Under the hood network Transform is sending RPCs as well so doing it that way is fine too.
ah ok, is there any documentation on when networktransforms send out their info?
was curious timing wise (eg. fixedupdate,update,lateupdate and all that)
I believe RPCs always get sent in fixed update. But beyond transform won't send anything unless it moved. The source for the script is in the package
Everyone having a good day? Excited to get back to networking after a tiring vacation!
JKim I am still on the fence. Can you help me out in your decision?
If a user logins on the web page outside Unity content. Is it safe to pass the token through js to Unity? How can that be best handled when login outside Unity?
Sure, you can. Just make sure authenticate on the server
Tell me more… Are you letting users log in to a traditional website?
Hi guys I have a question about the network animator. I'm encountering this error:
[Netcode] [DestinationState To Transition Info] Layer (0) does not exist!
I tried searching online for a solution, but I couldn't find anything. Do you know how to solve this?
Well I pretty much decided on using mirror because that was the only solution that worked without having to rebuild my entire game
Hello, I am updating to 2022.3 on my Mac. On loading game I am getting a proxy error from Package Manager. Has anyone dealt with this before?
I have been adusting my network proxy settings Manual suggestions yet with no success. Yet I have never dealt proxy settings before and maybe in error some where.
Probably just an authentication issue. Try signing out and restarting hub & editor.
Thanks for the reply. I will give it a shot.
its better not to engage with @visual cypress , its a Fishnet Author discord alt account
Hi, I am planning a game, I would like to ask some questions about multiplayer here :).
I am going to use Netcode for Game Objects, the game will have 1 vs 1 matches and there may be some players spectating the match (think of clash royale).
I am not sure if I should have a dedicated server or one of the players should be the host. If one of the players is the host, is it too much workload for the device to "stream" for the spectating ones? (the device may be a mobile) I would probably limit the spectators to 6 or something like that.
If I use a dedicated server (unity services server), with netcode approach I would need 1 game instance running per 2 players and I don't think this scales too well.
I know this is somehow stupid to ask but is it easier to kind of hack the game if the server is the client? (netcode host)
In clash royale, there is a delay of 1 second when you use a card, I assume this is to make sure the card appears in both devices at the same time, is this easy to do? I assume there is an rpc that sends the client time to the server and the server resends it to the other client but how accurate is it the client server time synchronization? Not sure if I explained myself, sorry.
Are rpc methods tcp and network variables udp or something like that?
Thanks in advance 🙂
quantum is going to be the perfect approach for this
Are rpc methods tcp and network variables udp or something like that?
I dont think we can treat them that way but merely,
RPC = Reliable
Variables = also reliable too actually
okay, let me take a look, thanks
RPCs and Network Variables are sent reliably in NGO as well. But if you don't need real time interactions, you can look into serverless solutions like Unity Cloud Code or AWS Lambda
thanks for the info, I will take a look at that as well
about quantum, it really fits the needs but I feel it is a different game engine almost. The game does use some unity key features at runtime like terrain generation and nav mesh generation, I am not sure how well quantum will integrate with that.
Not sure about this but you must use their servers to use quantum i would say
is your game similar to clash royale gameplay-wise?
no, the gameplay is not similar
but it is in the way the user interacts
there will be like actions you can take, so the input is discrete.
Unity Cloud Code and AWS Lambda seems to solve some problems but I feel the way I should make the game will be completely different from the netcode approach right?
It will be more similar to http requests, not sure if I am right
Basically, yea. The player would drop a card. The game sends the request to the cloud function. It will verify and process any logic and return a new game state. That new game state also gets saved in the cloud forthe next player/spectators to see
yea, I see, thanks
<@&502884371011731486>
That makes sense. Don't make things more difficult than they need to be. What did you come from?
!mute 343032164469702666 3d You've been told already not to bring this up or you will be muted.
stinkysteak was muted.
hi, to be fair, you told me, not him
They saw the same message
[ServerRpc]
public void RollNewSeedServerRpc()
{
currentRandomSeed.Value = UnityEngine.Random.Range(0, 1000000);
GameNetworkManager.AddLog("Setting Seed To: " + currentRandomSeed.Value);
RollNewSeedClientRpc();
}
[ClientRpc]
public void RollNewSeedClientRpc()
{
random = new Random(currentRandomSeed.Value);
}
With this code, is the order of execution with these network calls consistent? will clients recieve the new networkvariable value before they recieve the clientrpc call?
can somebody please help?
i'm really struggling to understand what's wrong
I doubt it.
Though I have a question. If NGO supports on changed callback on network variables, you could use it to set the seed and do whatever else you need with it.
oh yeah theres def routes i can go about solving it if it doesnt. I'm just new to networking and wasn't sure if it works in a way where like it adds them to a stack in order yknow
Most networking solutions don't give consistency on how data replicates, which can cause race conditions, etc. Though not all suffer from this issue.
like i know both these calls will get sent to the clients at a unpredictable amount of time but because of the order im calling them here would #2 ever run before #1 when the client gets these
You will have to ask NGO devs.
Though, in high quality networked games, RPCs are rarely ever used, due to potential issues like this and because they are a bad way to solve sync problems usually.
When you don't use RPCs, you can ensure consistency way better.
But again, not all networking solutions offer what it requires for this to be easily possible.
i am
this is the networking channel in the unity discord 😛
Ah, there is a actually a discord for NGO, where the devs are more likely to answer you.
But I haven't seen them answer any questions since I was a member in there.
that doesnt seem likely at all
Not sure what you mean. I am just expressing my personal experience.
I'm one of the mods on the Unity Netcode Discord. The devs do post occasionally. But for legit bugs posting a GitHub issue would be better
To you question though, RPCs are sent in a reliable channel be default so order is guaranteed as long as they are called on the same object. You can change RPCs to unreliable delivery or change the sync rate of network variables in the latest version of NGO 1.9.1
Awesome ok thank you. out of curiousity what makes it inconsistent outside of the same object?
I know how unity order of execution works just nothing too deep about netcode stuff
It's not really a Netcode thing. The order GameObjects run their Update() is random. You cannot say one object will run their Update before some other object. Same for fixed update when the network tick happens.
Hi, I just joined the unity discord server and wanted to learn about multiplayer. but there are so many terms i need to learn such as fishnet, netcode for gameobjects and photon. Can anyone wanted to explain to me what are those?
Oh ok just making sure it was on that side and not netcode side. I guess it's semi reliable with defined order of execution on singleton esque stuff
Hi,
Photon is a company that makes networking solutions.
Netcode for GameObjects is the official Unity networking solution, for the classic Unity (GameObjects).
Fishnet is a community-made networking solution, heavily inspired by Mirror which is a revival of the classic and outdated UNET networking solution.
ok, thanks for explain me, my english not good.
do u have tutorial? me new multiplayer
ok thank you, i want to learn to build fps game maybe with 16 players, is the tutorial good for it
You need to first learn the fundamentals and problems of networked games.
Then you can think about actually making a multiplayer game.
ok, my friend tell me to explore fishnet. maybe i start with it
I don't recommend Fishnet for a beginner, it's not as stable as NGO or other solutions like Photon Fusion.
okok, good info
thank you mr karrar
Lol, Mirror is the most used networking solution for Unity.
<@&502884371011731486> Flagging @lunar leaf as a possible guerilla marketing account for fishnet - please investigate? Apologizes if I'm wrong. Flagging because I don't like the manipulation of this style of marketing
!ban 1180838287733182528 Marketing spam
carzyckq_52366 was banned.
Thanks for investigating!
@old mural whats wrong with fishnet?
my friend keeps recommending it to me, maybe I should investigate it
what guerilla marketing, my english not good
Scammy marketing. A lot of other questionable activities.
No patience for it here.
wow, crazy. what is the questionable activities.
if story is true, i tell my friend
@sharp axle Thank you so much for sharing https://gamenetcode.com/. I've been reading through the articles and watching the talks on that site and they're just so high quality. Still working my way through but have been reading since you shared it about a week or two ago. Just wanted to loop back and share some appreciation.
i myself is gay, i cannot accpet homo hater
gamenetcode.com is maintained by ThusSpokeNomad who worked at Unity on NGO.
Good list.
Oh cool, didn't realize that historic context. It's suuuuuch a good list, yea
@timber bluff Please don't dredge this up. We're not going to drag their drama here, thanks.
why do you remove my message? are you against the non-binarian community?
I try help non-binary people
You will be kicked from this server if you keep up with it. No, we an inclusive here.
@timber bluff And there's no off-topic here. Read #📖┃code-of-conduct .
ok, will keep my voice down
Afternoon, anyone using ai bots with photoncloud for webGl ? I wonder if a websocket could handle e,g, the masterclient controlling lets say 8 ai bots ?
(Netcode for gameobjects) I have a network animator, and the transitions arent syncing, when i test in unity the transition is there, when i try with another player it doesnt work
Hey guys, i'm developing a counter strike like shooter and wanted to hire someone to develop the guns for the game. What should I be looking for when hiring? let's say 10 guns at Call fo duty quality.
wrong type of networking, lol.
Unity Forums are the best place for !collab advice
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Is this the correcct place to ask about multiplayer services for my game? I have a top down shooter game that I'm looking to add multiplayer to with a simple capability of create match / join lobby with code integration (maybe option to make lobby publicly joinable and show a list to others if thats not too hard)
Not sure if its reasonable to continue using playfab which I'm currently using for user authentication/account tracking, economy, leaderboards, etc. or if I should go with something else like the Unity multiplayer packages which seems simple to implement from what I've seen. Pricing is also a factor. I can't tell what the pricing is like between the options
Playfab is mostly backend services and does really handle the real-time communication part. You can still keep using playfab if you use NGO, or Mirror, or Photon.
Sorry do you mean "doesn't" handle it for the real-time communication?
There is no Network Transport layer for Playfab unless they added to the service recently
Ok thank you
thank you
I'm using NGO. Started to have weird problems with the OnClientConnected callback, after using it for weeks now, it started to give errors. I reinstalled NGO, and now this pops up: Library\PackageCache\com.unity.multiplayer.tools\Adapters\Ngo1\Ngo1Adapter.cs(46,13): error CS0123: No overload for 'OnClientConnected' matches delegate 'Action<NetworkManager, ConnectionEventData>'
Why?
That sounds like the delegate for OnConnectionEvent instead of OnClientConnected
Why is the property HasAuthority unrecognized on my class which inherits NetworkBehaviour?
Nevermind, I was looking at the experimental documentation
it does. in fact i tried changing it to onclientocnnected and it worked, im not sure what even changed. I'm getting so many errors literally out of nowhere. Did my project get corrupted?
Dunno. You can try deleting the Library folder and reimporting everything
Any tips for a kill cam, like call of duty?
How to record the state changes over time before the kill cam recording? How to handle the real time replay (initial thought: stop rendering other players on the level except for the relevant players for the kill cam performance)?
Make buffer of state changes for 5 second kill cam, and allow replay when a player dies?
Thanks for help. Just trying to wrap my head around any possible implementation for kill cam.
Hi, can anyone help me out for this HalfVector3 not being synchronized over the network.
Here`s the script :-
void FixedUpdate()
{
if (!IsOwner) return;
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 move = new Vector3(h, 0, v).normalized;
controller.Move(move * 6f * Time.deltaTime);
Vector3 full = transform.position;
HalfVector3 half = new HalfVector3(full);
MoveServerRpc(half);
}
[ServerRpc]
void MoveServerRpc(HalfVector3 p)
{
MoveClientRpc(p);
}
[ClientRpc]
void MoveClientRpc(HalfVector3 p)
{
if (IsOwner) return;
transform.position = p.ToVector3();
}
This will be much easier and effortless if you don't depend on any RPCs for how players are rendered in the client.
So basically you make it so that the entire logic state needed to render characters is contained in networked state (network variables), and events are just reactions to state changes, using On Changed, if it exists in your networking solution of choice.
So that you can simply reset the players and replay them from your buffer.
Potential issues: if the networking system you use does not ensure all network variables are synced together (for a certain behavior, at least), then you might experience desync issues that could ruin the visuals of the character. Like a character being stuck in a certain pose, for example. It depends on the specific logic though.
Hello! I'm very new to Unity and learning about the UnityAethentication service
I followed the guide https://www.youtube.com/watch?v=XVqYIFcjhLE and was successfully able to login
However, I am unable to write the Sign-out and make it work, every time I try to sign in again after Signed Out it responds with:
PlayerAccountsException: Player is already signed in.
Unity.Services.Authentication.PlayerAccounts.PlayerAccountServiceInternal.StartSignInAsync (System.Boolean isSigningUp) (at ./Library/PackageCache/com.unity.services.authentication@3.3.1/Player Accounts/Runtime/PlayerAccountServiceInternal.cs:60)
Habillage.AuthenticationUnityPlayerAccountsControl.InitSignIn () (at Assets/Scripts/Authentication/AuthenticationUnityPlayerAccountsControl.cs:43)
Habillage.AuthenticationUI.LoginButtonPressed () (at Assets/Scripts/Authentication/AuthenticationUI.cs:46)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <b11ba2a8fbf24f219f7cc98532a11304>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <c5ed782439084ef1bc2ad85eec89e9fe>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <c5ed782439084ef1bc2ad85eec89e9fe>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <c5ed782439084ef1bc2ad85eec89e9fe>:0)
This is how I write my SignOut Task
public async Task InitSignOut()
{
try
{
AuthenticationService.Instance.SignOut(true);
AuthenticationService.Instance.ClearSessionToken();
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
Debug.Log("Signed Out");
OnSignedOut?.Invoke("Signed Out Completed");
}
catch (AuthenticationException ex)
{
authenticationUI.ShowMessage(ex.Message, AuthenticationUI.ResponseMessageType.error);
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
authenticationUI.ShowMessage(ex.Message, AuthenticationUI.ResponseMessageType.error);
Debug.LogException(ex);
}
}
0:33 - Installing Authentication Package
0:58 - Connect Project
1:14 - Adding Player Accounts to Identity
1:27 - Client ID from Dashboard
1:40 - LoginController script
3:26 - UILogin script
6:40 -Testing
6:55 - Google Login
7:05 - Logged In
7:21 - Exporting to android
8:22 - Testing Android
8:34 - Matching Ids
Edit 5/2/2024
Code used in the ...
Need Help on Consulting
Hi everyone,
This is my first time on this server. Recently, there's been a "community issues" regarding Fishnet community. We have several games in production that use Fishnet, but my Discord account was banned from the Fishnet server.
The reason for the ban was because I asked what was happening within local Fishnet communities. FirstGearGames then asked about the footage of our shipped games. Unfortunately, due to the our B2B games and a non-disclosure agreement (NDA), we couldn't disclose that information.
As a corporation, we are looking for the safest option for both our internal team and our customers. Our recent experience with Fishnet is negative.
As a result, we're currently looking for alternatives to Fishnet. We're aware of Mirror, Coherence, Netick and Normcore, but Which ones do you think we should expore. we're open to other suggestions as well.
PS: We only used Mirror for briefly and other such as Photon PUN, and Netick.
Here're the one of the game specifications:
- The game is teaching about how to operate a mining site with real-time interactions such as vehicles: trucks, excavator and stockpiles
So I've set up a script to make and handle a websocket communication with an api service
{
Debug.Log("WebSocket message received: " + e.Data);
// Deserialize the JSON data to a BaseMessage object
BaseMessage baseMessage = JsonConvert.DeserializeObject<BaseMessage>(e.Data);
// Check the type of the message
switch (baseMessage.type)
{
case "chat_metadata":
//Debug.Log("Message type received: Chat Data");
break;
case "assistant_message":
Debug.Log("Message type received: Assistant Text");
HandleAssistantText(e.Data);
break;
case "audio_output":
Debug.Log("Message type received: Assistant Audio");
HandleAssistantAudio(e.Data);
break;
case "assistant_end":
Debug.Log("Message type received: Assistant End");
break;
default:
Debug.LogWarning("Unknown message type received: " + baseMessage.type);
break;
}
}```
It works but the problem is when I call methods from there to process the data I receive, I get this error:
"Exception: UnityEngine.UnityException: FindObjectsOfType can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."
How can I solve this?
presumably the deserialization is happening on a different thread, were you aware of that?
without seeing where you're doing that it's a bit hard to say but either you want to ensure you do it on the main thread, or you need to schedule the processing code to run on the main thread after the thread that's deserializing the data finishes
Here's the code contained in the method that generas the error:
{
var message = JsonConvert.DeserializeObject<AudioOutputMessage>(jsonData);
string base64String = message.data;
Debug.Log(base64String);
SaveText(base64String);
}```
Is is indeed a deserialization
Btw the deserialization of the Json I receive isn't generating any issue
The problem are the method I call after, to elaborate that data, such as storing a string or turning that string into an audio file
Doesn't seem like a networking thing. Are you using the job system to schedule this?
I dont think so
also keep in mind the true method that generates the error is this one, I forgot to include it cause it was temporarly commented:
{
string filePath = System.IO.Path.Combine(Application.persistentDataPath, "clipboardText.txt");
System.IO.File.WriteAllText(filePath, content);
Debug.Log("Clipboard text written to: " + filePath);
}```
I have no knowledge on this topic since I've never had this need before
I read that I should use something like this:
UnityMainThreadDispatcher.Instance().Enqueue(()
but I'm not quite sure on if it will do the job and if it works at all
might be a better question for #archived-code-advanced
Gotcha. At time of death, have server somehow send over the stream of state changes 3-6 seconds before player kill?
Or are kill cams entirely client side, meaning each client has a buffer of state changes for all other players…? Hmm, this is actually kinda tricky
Yea, it can be tricky.
I am currently working on a Rocket League inspired game. The way I'm planning on doing replays is by simply replaying the game in the server and it will simply synchronize to clients.
But for a COD-like killcam, you will want to do this in client-side. So yea, store a histroy buffer for all players. One issue with this is that if you had packet loss while playing the game and other players looked laggy, the replay will also look laggy.
Or, you can make the server handle this per client basis, which will be the most annoying solution.
Hmmmmm. HMMMMMmmmm.
What netcode lib you using? Is the state change buffer built into the lib or is it something you’ll have to write yourself?
When player dies, it then makes an RPC call to server to have the server stream state changes from right before kill… is that the gist of your proposed solution? How does one switch from default behavior of SyncVars, which streams live/current delta compressed values from server to clients, to instead stream from history?
I am using Netick, my networking solution.
Yes, it's built into it, it's a 1.2 second buffer (by default) of the entire networked game state, in the server. But it's meant mainly for delta compressing the entire network state of the game. I have a code gen system that combines the entire networked game state contiguously in memory. So copying it around is costless. But currently there is no API to access the internal buffers, I will expose it soon.
I will also add a Disable Authoritative Updates to my NetworkObject, so I can safely change around objects in the client while ignoring all incoming server states, which is ideal for doing COD-like kill cams. But all that state is already stored in an authoritative buffer. So by simply disabling the option, the object will get synced again. The idea of streaming from histroy is pretty cool, I will think about adding that built-in.
Though, you can still do all of this yourself anyway without the need of internal support. Just do a rolling buffer of a struct of all the needed state to replay the character properly.
I don't know how SyncVars work. But I don't think SyncVars are delta compressed in Mirror or NGO. They simply use the underlying transport reliability option for it (I think), which is not the same thing to what Delta Compression means in game networking.
In NGO 1.9.1, Network Variables are using delta compression. Or at least they are sending deltas
I will take a look.
you can check out the commit here. I haven't dug too deep into it yet
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/pull/2813
They mean instead of sending the whole collection each time an element changes, they will only send the specific changed fields/values.
While delta compression (delta encoding) means delta-encoded serialization, which means you are sending the specific bits of the specific changed fields. And it's usually meant as an operation that acts on the entire game. Which is what's meant by consistent replication.
So in NGO, if you have a network variable of Vector3 type. When it changes, it will be sent in full, so all 3 fields.
While in delta compression, only the specific bits will be sent.
Delta compression is a complex feature that can't just be added in an update/patch. It requires an architecture built from the ground up to support it.
Mirror support delta-encoding in their NetworkTransformReliable, but it's not useful because it uses reliable transfer to send the data.
So by adding even a bit of packet loss, you will have huge delay.
I stand corrected. I assumed delta compression. Woah, surprised.
In netick, you can switch which “stream” of state is being sent from the server? At some point the state will have to change from LIVE to HISTORIC for that one player; that’s the part that’s kinda tripping me up right now.
I.E. the game server knows the player dies so it’d have to somehow know to send down the different stream of state, but just for that one dead player and only for as long as the kill cam feature is happening. Just curious… how? Feel free to speak in netick.
Doing it as a client-side only operation is way easier.
But streaming it from the server is tricky. The way I will do this is by making a "kill cam" network behaviour which will have all the state needed to replay the characters. And it's per-client, so if the game has 16 players, you will have 16 kill cam network behaviour. And I will use Interest Management to only replicate each one to its specific target client.
So, in a simple way:
// per-client
public class KillCamState : NetworkBehaviour
{
[Networked(16)]
public NetworkArray<CharacterState> Characters => new(16);
}
I will only change Characters in the server. The server can use its own rolling buffer or the internal system buffers to apply data to these arrays. Most likely a custom rolling buffer since we want it to be longer than 5 seconds, and we can only change the internal buffers for the whole game, so it will a lot of useless memory usage. In the client, I will simply apply each state to its player.
public override void NetworkFixedUpdate()
{
for (int i; i < 16; i++)
CharactersObjects[i].ApplyState(Characters[i]);
}
Though as I said, you will want to disable incoming server states, so you will enable Disable Authoritative Updates on the players, in the client, during the killcam.
I will not use RPCs for this at all. Because RPCs don't support compression, and I am just against them 90% of the time as they are just the wrong way to sync gameplay.
Thinking about it more, I think this is the most optimal solution. Support for this as a netcode feature is not worth it and will complicate things even more since you might want some things to not replay.
Cool this makes more sense to me. Thanks!!
(putting this in netowrking because maybe the other players gamamnager is interferring?
sorry i didnt have my coffee yet
it was a simple mistake
@tame slate dont destroy on load, didnt properly handle the singleton, had an instance in every scene
anyway i can use websocket client on android, and connect to a server running on my pc?
If its a web sever, I don't see why not
Hey in NGO using the Relay system is there anyway to set a custom JoinCode or do you have to do it through the lobby system?
Hey guys I have a finished game (3rd person shooter PvE) with a narrative storyline and endless wave mode
Realistically, how difficult will it be to implement a seperate PvP mode (multiplayer) aside from rebalancing mechanics
I just started digging into the new multiplayer services SDK. There is a CreateOrJoinSessionAsync() that will let you specify a session id to join or create.
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/get-started
I did look into this but it does not appear to work with RelayUnityTransport I will try again though
It does. Its kinda crazy how easy it is. it even integrates matchmaking
Then how do I run it I can't find this Function anywhere
You should be prepared to rewrite the majority of your code
Thank you so much I have been looking for something like this forever.
Ah alright, in what regard?
The multiplayer would hopefully be just a seperate gamemode so wouldnt the rest of the game (which is single player) just remain the same
or would this also become affected
It depends on how your code is structured. But I doubt your single player game is currently set up with RPCs and/or Network Variables in mind
Im free 🤟 @blissful jay
Hey, im currently working on a game and just started with netcode so i barely know anything about it.
I got the connection part of the players working but right now im trying to make name tags above the player and im struggling to get it working.
If anyone could point me into the right direction that would be awesome
I tried using network variables but i don't quite understand how they work yet
This channel would be better if the name is #multiplayer instead of #archived-networking
I got this error when i call an API ```Curl error 60: Cert verify failed. Certificate is not correctly signed by a trusted CA. UnityTls error code: 7
Syncing usernames
I am using this class to prevent this error from occurring but I'm still getting this error ```using UnityEngine.Networking;
public class BypassCertificate : CertificateHandler
{
protected override bool ValidateCertificate(byte[] certificateData)
{
//Simply return true no matter what
return true;
}
}```
request.certificateHandler = new BypassCertificate();
I'm trying to port my interaction system from single player to multiplayer. Right now it's basically an interactor script on the player prefab that whenever finds an interactable object runs this code
private void OnInteract(InputAction.CallbackContext context)
{
if (_interactable != null)
{
_interactable.Interact(this);
}
}
and then the Interact function of the object runs the code like this
public bool Interact(Interactor interactor)
{
Debug.Log("Interacted!");
this.gameObject.GetComponent<MeshRenderer>().material.color = Color.black;
DisableInteraction();
return true;
}
I tried making OnInteract() a ServerRpc and Interact() a ClientRpc but I got numerous errors since the Interactor type is "non-serializable", and even if i removed it, obviously since the code of the OnInteract() function was running on the Server, the _interactable.Interact(this); line would give nullReferenceException. What would be the best solution to this? I'd still like to keep the reference to my interactor
i'm using ngo
i see makes sense
all enemy ai shouldnt be affected since they wont exist within the multiplayer realm so i guess the only issue would be making potentially a seperate character controller for the multiplayer + health (only for this mode)
i dont see that being too bad tbh
Inside Interact() you should be calling an RPC and passing it the color. Something like ColorChangeRpc(Color.Black) that RPC will run the line to change the material color.
What if i wanted a code to act on the interactor? Like change it's color to black instead?
for that you need to send a NetworkObjectReference of the Interactor in the RPC as well
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/
Brief explanation on using NetworkObject and NetworkBehaviour in Network for GameObjects
Does anyone know any good tutorials on making multiplayer? I'm making a first person horror game that's going to be single player and multiplayer. Need to know the basics
If you are using NGO, then Code Monkey has the most complete tutorials.
is netcode for gameobjects good solution for adding multiplayer
why would i use netcode instead of pun 2 for example
Pun2 is deprecated. Photon Fusion 2 is the new offering. Its a fine alternative to NGO
what is NGO? Im still learning about multiplayer. My game will be on steam will that work?
Netcode for GameObject. You can check the pinned message here for more resources. They all will work well with Steam and Steamworks if you want
i think its better for you to explain what is the gameplay like
sometimes certain network library wont suit your needs
different architecture, you have to have a host or server using NGO. While PUN, the server is on cloud
PUN is good for light games.
NGO is good for coop games
Hello everyone, I am trying to make Inventory but it doesnt work, I want it that when I pickup an item it will go to the first empty slot and change icon according to item I picked up, I want it to be able to pickup other items while Im holding my item and that other items will be assign to remaining empty slots. And I want it to switch between them with numbers from 1-5 and when I press G on item Im holding it will drop it from hand and inventory. This is Item script thats attached to items:https://hastebin.com/share/ozagayorev.csharp and this is Inventory script attachted to gameobject holding 5 slots(which are 5 ui images): https://hastebin.com/share/uficaziniw.csharp and this is interaction manager script: https://hastebin.com/share/afabehexiq.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is for multiplayer project using PUN
My game is a first person horror game
is that all you can share?
what is inv.items?
in the // area? @ripe mesa
I'm trying to do Matchmaking. It does receive tickets but not match
Does anybody know more about this who maybe can help me?
@ripe mesa in the // are it is something that I tried with chatgpt his solution that didnt work
You'll need to double check your tickets and make sure the Matchmaking rules can catch them.
I have a game that I'm making that works like this. 0 gravity basket ball in 2d basically. I have set up multiplayer but am struggling figuring out how to let everyone interact with the ball (being able to grab and throw it) At the moment I have it so the ball can be grabbed and thrown by the host, and so that everyone else can see the ball but not interact.. Wanting direction as to where I should look, at the moment been trying to serverRpc but not sure if I should keep trying or do something else.. Here's how I spawn it in currently:
if (Input.GetKeyDown(KeyCode.B))
{
SpawnBallServerRpc();
}
}
[ServerRpc]
void SpawnBallServerRpc()
{
Ball = Instantiate(BallPref);
Ball.GetComponent<NetworkObject>().Spawn(true);
BallRB = Ball.GetComponent<Rigidbody2D>();
BallNetworkObject = Ball.GetComponent<NetworkObject>();
BallNetworkObject.ChangeOwnership(NetworkManager.LocalClientId);
foundBall = true;
}```
and some other stuff I've tried implementing
```c#
[ServerRpc]
void HoldBallServerRpc(Vector2 handPos)
{
BallRB.MovePosition(handPos);
}
[ServerRpc]
void SetBallVelServerRpc(Vector2 vel)
{
BallRB.velocity = vel;
}```
And some other stuff for when I grab the ball
```c#
else if (HoldingOntoBall && foundBall) {
Debug.Log("Holding");
// Move the hand to the desired position
HandRB.MovePosition(towardsPosition);
//Move the ball via server rpc
HoldBallServerRpc(HandRB.position);
// Calculate velocity
Vector2 velocity = (towardsPosition - BallRB.position) / Time.fixedDeltaTime;
Vector2 clampedVelocity = Vector2.ClampMagnitude(velocity, MaxBallVelocity);
//Set Velocity
SetBallVelServerRpc(clampedVelocity);```
Let me know if I need to include other important parts of the project I may have over looked. Thanks in advance for at least reading this 🙂
Hey !
I have a question, i create an MMORPG and I was wondering if create an GameObject with all script relative to Player and have a gameobject "Player" with only visual component and controlling script it's not better for control and use all script (Stats of player, level,...) to make it easier to use the scripts together
if i wanted to use steam networking do i have to pay them?
public async void CreateRelay()
{
if (IsServer) return;
... Other code to start relay
i dont want players to be able to start relay if already connected. Server is getting shut down but it seems the game still thinks im server? Creating game works first time but then after shutting server down and trying again it still thinks im server
How are you creating a game? How are you shutting it down?
public async void CreateRelay()
{
OpenHostMenu();
await UnityServices.InitializeAsync();
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
Debug.Log("You Signed In" + AuthenticationService.Instance.PlayerId);
}
try
{
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(4);
generatedRoomCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
NetworkManager.Singleton.GetComponent<UnityTransport>().SetHostRelayData(allocation.RelayServer.IpV4, (ushort)allocation.RelayServer.Port, allocation.AllocationIdBytes, allocation.Key, allocation.ConnectionData);
GameManager.instance.StartHost();
RoomCodeFieldBox roomBox = FindAnyObjectByType<RoomCodeFieldBox>();
if (roomBox != null)
{
roomBox.ApplyRoomCodeToDisplay();
}
hostBackButton.interactable = true;
}
catch (RelayServiceException e)
{
Debug.Log(e);
}
}
public void ShutDownServer()
{
OnServerDisconnectCallback(OwnerClientId);
NetworkManager.Singleton.Shutdown();
MenusManager mm = FindAnyObjectByType<MenusManager>();
if (mm != null)
{
mm.CloseAllMenuPanelsAndOpenMM();
}
}```
Nothing looks out of the ordinary to me.
Do you switch scenes or anything after Shutdown?
nope, idk if you noticed too im not sure it matters but shutdown server is instance from another script, im handling the instance proerly though, no duplicates
I'd probably just try destroying the NetworkManager and making a new one.
If you are on NGO 1.8.1+, there is a 5 second delay for the Network Manager to fully shutdown
You can poll NetworkManager.ShutdownInProgress to know when it's finished.
Hey!
I am working on a multiplayer game for the first time, and I am wondering how you can get a well working UI setup for multiple players?
I have problems with them either not getting the UIs properly for each, or having a synced UI?
How can I have a script where I can modify a players UI seperately for each players?`
I am using the Mirror package for the multiplayer!
I'd recommend setting up SyncVars and using hooks to update UI whenever there's a value change
You can also use TargetRpc to run a function on a specific client
Does SyncVar work that all clients have the same value on that specific script?
And without, only that client have that value?
And would I have a canvas for each player? Or 1 canvas, and have clients clone a prefab with a UI for them on it?
Say 1 prefab as a UI base for each client, and inside there is diff UIs?
Nothing really...
Would I just do like I would do in a singleplayer game?
I am trying to make like a TAB menu to see all players if that makes sense lol
is this the channel for multiplayer and stuff
and just use a SyncVar for their names
[SyncVar(hook = nameof(OnNameChanged))]
private string playerName = "null";
private void OnNameChanged(string oldVal, string newVal)
{
nameText.text = newVal;
}
basically all you need to have set up for values like a player's name to be synced to all clients
( I deadass didn't know about TargetRPC, and stuff finally started appearing 🙏 )
Thank you, I'll see what I can cook up now 🔥
Just be careful when using TargetRpc because newly joined clients won't have any changes you've made from a previous TargetRpc
That's why you want to use SyncVars with hooks most of the time
What to do if when I enter the lobby the PhotonView is mine but when another player enters it is no longer mine ?? (both from the same computer)
How does Input system works with Unity netcode for gameobjects ? I am at the beggining of my investigation. I have a fully working local coop game that instantiate prefabs on player join. But now it seems i also have to instantiate prefab when they join by network. How does people mix these 2 packages together ?
When the remote player prefab spawns you check its IsLocalPlayer and disable its input component if that is false.
its better to show your script
I'm using Netcode and I have a problem with RPCs, I have this RPC:
[Rpc(SendTo.NotMe)]
public void EndPlatformPlayersCallRpc() {
GetComponent<Rigidbody>().position = new Vector3(BASE_X_SPAWN, BASE_Y_SPAWN, BASE_Z_SPAWN);
}
And I'm calling it like this:
public void EndPlatform(bool callOthers) {
// [...]
if (callOthers) { EndPlatformPlayersCallRpc(); }
// [...]
}
I have a spawn platform where everyone spawns and an ending platform, beneath the starting platform, and when someone arrives to the ending platform, EndPlatform(true) is called, and it calls EndPlatformPlayersCallRpc which does stuff but primarily should teleport everyone on the starting platform, but it doesn't work for some reason, it only works for the person that has called EndPlatform(true)
Any idea why it happens and how to solve it ? (please ping me for responses)
Hello!
I'm testing basic networking for my game and connecting to another machine using Hamachi.
Whenever the other part tries connecting as Client, this error gets thrown
"Cannot start client while an instance is already running" even when no other instances are running.
What could be the cause of this?
(Host/Client setup)
RPCs are tied to the object they are on. So if this RPC is on the player then only that player object will be teleported. You would need to the server to loop through all the player objects and teleport them individually
How would I do that ?
hi!
That's the first thing I tried but I found nothing
i'm trying to do some uga booga level networking, i just want to send a object from one PC to another inside the same LAN in unity, how would i do that?
i prefeer to do it using sockets but idk
You can loop though all the Connected clients dictionary on the server
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/#finding-playerobjects
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.
oh, thanks
I'll try it tomorrow, if it doesn't work or I need more help would you be ok with me pinging you ?
C# has a TCPclient you can use if you can convert that object to a byte array
That's the same for UDP i supose
Sure, just drop any questions here or over on the Unity Netcode Discord
thanks
thx
!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.
Hey everyone. I am getting this error sometimes, when using Nakama and sending Rpc Calls. https://paste.ofcode.org/kYbEDCUs2Q5pmv6Ptvmb4M
From my knowledge, there seems to be something wrong with the returned value of the server while executing? Is there anything I can do to prevent or fallback. Simple try catch did not work, because it does not break to execute but meanwhile it is awaiting the call I guess.
Working with Netcode For Entities, I'd like to handle server dc's nicer, but following the example's when the server shutsdown the client obviously stops getting updates, but then just kind of hangs or crashes after it timesout. I'd like to be able to handle that and load the player back to our pre-login scene and clean up their entities.
Is there any good examples of this? I haven't seen any in the docs/samples yet.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
i'd start with some null checks, don't see a single one
One message removed from a suspended account.
every reference, it's basic defensive programming.
example:
string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);```
vs
```Allocation allocation = await RelayService.Instance.CreateAllocationAsync(7);
if( allocation != null) {
string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
}```
Even RelayService.Instance can be null
One message removed from a suspended account.
that will help you identify yes, but keep in mind, depending on what platform you are on, it's also possible for things to become unexpectedly null.
For example: some mobile platforms will reclaim memory if they are running low and that can hit your references
to be safe you generally want to always check if a reference is null before you access any methods or members on it
think any time you use a dot to access a member, if the thing on the left side could be null you'll get an exception
somethings will just crash and you won't get an exception
but especially with asynchronous code, the code is being executed, and then paused, and the CPU is then executing other things before coming back to that code, the state of memory can change during that time
@sharp axle It half works, now when the host touches the end platform, only him gets teleported on the start platform, but when it is a client that touches the platform, everything works perfectly
Here's my code:
public void EndPlatform() { EndPlatformServerRpc(); }
[Rpc(SendTo.Everyone)]
public void EndPlatformServerRpc() {
if (!IsServer) {
round++;
if (round > ROUND_THRESHOLD) { LoadSecondPhaseRpc(); }
else {
roundText.text = $"{roundTextBase}{round}";
lifePoints = BASE_LIFE;
healthText.text = $"{healthTextBase}{lifePoints}";
rb.transform.position = new Vector3(BASE_X_SPAWN, BASE_Y_SPAWN, BASE_Z_SPAWN);
}
}
foreach (KeyValuePair<ulong, NetworkClient> id_player in NetworkManager.Singleton.ConnectedClients) {
var po = id_player.Value.PlayerObject;
var pob = po.GetComponent<BlocCollider>();
if (pob.round > ROUND_THRESHOLD) { pob.LoadSecondPhaseRpc(); }
else {
pob.round++;
if (pob.round > ROUND_THRESHOLD) { pob.LoadSecondPhaseRpc(); }
pob.roundText.text = $"{roundTextBase}{pob.round}";
pob.lifePoints = BASE_LIFE;
pob.healthText.text = $"{healthTextBase}{pob.lifePoints}";
po.transform.position = new Vector3(BASE_X_SPAWN, BASE_Y_SPAWN, BASE_Z_SPAWN);
}
}
}
Where BlocCollider is a component with a script that handles collisions, including the end platform collision (passed 3 rounds, all players should be loading a second phase which basically teleports them on a second map)
Looks like I've solved my problem, it doesn't work just for the host, so I'll just make it impossible for people to be host, only server or client
You have a !IsServer check in your code. Best to avoid those and just use IsClient to allow hosts.
Also assuming you're using NetworkTransforms - they have a .Teleport function to set positions without interpolation.
📃 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.
Hello. In my game, I am having an issue where the client and the host players don’t move at the same speed. My game is 2d and the player moves with rigidbody velocity. How can I fix this?
Im guessing the host needs to handle all the movement but im not sure how to send the clients input to the host.
Client Authoritative movement is the easiest solution for most simple games and for beginners.
Are you using Mirror, Netcode for GameObjects, other?
netcode
Hey y’all! I am making a 3d multiplayer horror game, but I don’t know how to actually add the multiplayer . . . Could I have some help setting it up? DM me if you know! Thanks
PS I’m using the modular first person package
You don't just add multiplayer to a game.
You need to rewrite large amounts of your game for it to be a multiplayer game.
Introduction
There's a sample component you can use to allow each client to handle and sync their own movement to the server.
Which I also believe the documentation recommends you add a NetworkRigidbody to
Thank you. Ill check it out.
How can I fix that classes loose their data when being networked?
I have a class that stores some information and when I add a [SyncVar] in mirror with a hook, and I listen to that on other clients that are not the host, the data is just empty?
Anyone knows why this is?
Its pretty straight forward:
public class Test
{
public string Something { get; set; }
public Test() { }
public Test(string something)
{
Something = something;
}
}
public class Player : NetworkBehaviour
{
[SyncVar(hook = nameof(OnTestChanged))]
public Test test = new();
public void OnTestChanged(Test oldTest, Test newTest)
{
Debug.Log("Something: " + newTest.Something); // Returns nothing on all clients, correctly on host.
}
[Command]
public void CmdSetTest(string something)
{
test = new Test(something);
}
}
can SyncVar used for class?
hello, im trying to get a random client's gameObject so i can change a variable in their script using unity's relay system how would i go about doing that?
for example, in among us a random player is selected to be the imposter
- search all object of players, it could be using FindObjectOfType, or you have a custom list for it.
- select random
ok thanks
The issue was that I needed to make the class over to a struct instead
then it worked as intended apparently
Hi there ! I am using Netcode for my coop game, i'm having an issue where my two player prefabs are spawning (The camera in my main editor and my parrallel sync activate) but after 1 or 2 seconds, they both disapear from the scene and I get "No cameras rendering". For the lobby part i followed Dapper Dino tutorial (https://youtu.be/bNCzpKX4frg) and now i'm just trying to make my players actually spawn and stay.
Any idea where the issue might be ?
PS: I know the players are indeed spawning because i also get the audio source problem (to be fixed later ik).
Netcode Player Prefab disapearing
I'm integrating UGS Server Hosting and Matchmaking. It works up until the clients connect to the server via Netcode. It times out with Failed to connect to server. Cant figure out what I'm doing wrong, my Matchplay project is working fine, but my own project doesnt work.
make sure the ip and port from the MultiplayAssignment is getting set correctly on the client
yes they match
Server ConnectionData: 0.0.0.0:9000
client ConnectionData: x.x.x.x:9000 (matches ip of server, comes from MatchplayAssignment).
Any other ideas?
have you tested a case where the server is outside LAN?
im not sure I understand, this test is run from an uploaded dedicated server to Game Server Hosting
I understood that very well, before you tested out UGS, have you tested to deploy a server just outside LAN?
instead of jumping to UGS directly
could you help me understand how I would do that?
just use your friend computer to host the game
but make sure they have NAT open
I havent tried that, but i have another working project in UGS
seems like theres only so many variables required to connect to a server (ip:port)
If you can see the server allocated in the cloud dashboard, then try to connect the client directly to its IP without matchmaker
thats a good idea, same result: Failed to connect to server
@sharp axle @ripe mesa oh wow, really stupid typo on my part: 🤦♂️
var unityTransport = NetworkManager.Singleton.gameObject.AddComponent<UnityTransport>();
the addComponent?
yeah...
i think autocomplete screwed me there lol
thanks for the help, sorry about that
If I want to make a small co-op game (~4 players) using Steam for relay, what frameworks work well together for doing as much heavy lifting codewise as possible?
You can start with NGO and see if it's a good fit for your game. There are several commercially successful co-op games built with NGO.
If not, you can start exploring third-party options.
I plan to publish on Steam anyway, so I'd like to take advantage of their free services for Steam games, including relaying, since I'm already buying into the Steam ecosystem.
I'm seeing FishNet and Mirror as options, with their own plugins for transport on Steam (FishySteamworks and FizzySteamworks respectively). I'm wondering which of these would be the best option, or if there are other free options that are better or simpler while still being "free" solutions (aside from maybe sponsoring for Github source)
There is also Netick. It's the best performing networking solution for Unity (shown by open-source benchmarks), beating paid solutions too. It's exiting beta stage very soon.
It's pretty easy to use, and has a Facepunch transport.
Mirror, NGO, and Fishnet are all derived from the outdated UNET API. Netick uses a modern API that makes building the most complex type of networked games easy. In addition to many other features, it has a feature called sandboxing that makes working with multiplayer games extremally simple since you will never need to build your game or use two editors (or Multiplayer PlayMode), and can start the game and debug it all in the same editor. It's a game changer for quick multiplayer development.
Disclaimer: I am the developer of Netick.
Sounds interesting
I don't want to buy into a system where I have to pay per user/per match/per GB if free options exist, y'know? 🙂
It's free.
Also, the paid solutions are actually not that expensive if you do the actual math, to be fair.
Ok, thanks for the info. Some things to mull over. There will definitely be fewer hurdles just going with NGO until I have something that actually works.
Yes, it's always better to use the official offering if it fits the requirmements.
public async void StartGame()
{
if (currentLobby != null && IsHost())
{
try
{
print("Start Game");
// string relayCode = await TestRelay.Instance.CreateRelay(currentLobby.LobbyCode);
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxPlayers);
string relayCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
print("CODE: " + relayCode);
RelayServerData relayServerData = new(allocation, "dtls");
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData);
NetworkManager.Singleton.StartHost();
// startingGameObject.SetActive(false);
Lobby lobby = await Lobbies.Instance.UpdateLobbyAsync(currentLobby.Id, new UpdateLobbyOptions
{
Data = new Dictionary<string, DataObject>
{
{"IsGameStarted", new DataObject(DataObject.VisibilityOptions.Member, relayCode)},
}
});
generateMap.newMapGeneration = true;
currentLobby = lobby;
}
catch (LobbyServiceException e)
{
print("Error: " + e.Message);
}
}
}
Hi everyone, could you help me understand why this code works correctly the first time, but if I try to run it again (after leaving the game) it gets stuck on this line?
RelayServerData relayServerData = new(allocation, "dtls");
Are you seeing an error message in the console?
nope, nothing
Okay, no problem. It was my mistake, this code is working correctly. I made an error in setting up the UI when a new game starts.
Hey,
So im using photon,
And i had a question,
(I already went over the photon documentation, still cant figure it out)
So, players that join the server have a input field,
Where they have to enter a nickname.
Then, in the top left, a textmeshpro text field will be updated with the username that they submitted in the input field.
this works, but its for some reason only visable for the player who added it.
No one else can see this.
Scripts are links bellow,
Could someone help me please ? 🙂
(i already went over pun documentation, and cant figure it out, also after reading the articles about RPC
I do not see any network code that updates the value for other players. Not that familar with the current photon tho. Maybe you can explain, where the values should be set/send to other players
Fishnet removed from Asset store? Interesting
Per Player, there is a NickName field, which is automatically synced within a room / game. Your UI can use the PlayerList of the CurrentRoom to show who is who.
If I recall correctly, the PUN Basics Tutorial shows how to show the NickName per player.
https://dev-doc.photonengine.com/pun/current/demos-and-tutorials/
Fishnet removed from Asset store?
The usernames get listed in OnSubscribed
I have some buttons that once clicked I want to desactivate I want them to disappear and not be visible, but when I do, it doesn't work, here is the code:
public class UIManager : MonoBehaviour {
[SerializeField] private Button startServerButton;
[SerializeField] private Button startClientButton;
[SerializeField] private Button goBackButton;
[SerializeField] private Image connectionMenuBackground;
[SerializeField] private TextMeshProUGUI playersInGameText;
[SerializeField] private Camera connectionMenuCamera;
private void Awake() { Cursor.visible = true; }
private void Start() {
playersInGameText.enabled = false;
startServerButton.onClick.AddListener(() => {
if (NetworkManager.Singleton.StartServer()) {
Debug.Log("Server started...");
} else { Debug.Log("Server couldn't be started..."); }
startServerButton.enabled = false;
startClientButton.enabled = false;
goBackButton.enabled = false;
connectionMenuBackground.enabled = false;
connectionMenuCamera.enabled = false;
playersInGameText.enabled = true;
});
startClientButton.onClick.AddListener(() => {
if (NetworkManager.Singleton.StartClient()) {
Debug.Log("Client started...");
} else { Debug.Log("Client couldn't be started..."); }
startServerButton.enabled = false;
startClientButton.enabled = false;
goBackButton.enabled = false;
connectionMenuBackground.enabled = false;
connectionMenuCamera.enabled = false;
playersInGameText.enabled = true;
});
}
}
They just stop functionning, they are not clickable but I still can see them
The background and camera are disabled and not visible, but the buttons still appear for some reason
Any idea how to fix that ? Please ping me if so
Setting .enabled is how you toggle components on and off. What you're probably wanting to do is startServerButton.gameObject.SetActive(false);.
Side note: This specific question technically isn't networking related, so probably best to post questions like this in another channel.
Just for debug reasons, you know, that the notimplemented exception can break your game runtime, right?
Anyone know of a way to refresh the DefaultNetworkPrefabs lists without having to do a Reimport all? My list randomly loses a ref to all the Network Objects, no idea why.
Yeah
Thanks! I tought this problem could be related to the fact the buttons start a host or client, so I put it in here just in case
Hey,
I'm trying to make an UDP client/server.
I can't make the endpoints talk to each other.
The code is running properly and without exceptions as seen on the logs, but there seems to be something weird going on with the listener.
it's not receiving any bytes from the end point which is 0.0.0.0:0
I'm using .NET version 6.0
I have modified the apps firewall settings.
Server
int SERVER_PORT = 11001;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpClient listener = new UdpClient(SERVER_PORT);
Console.WriteLine($"[Server] waiting for broadcast from {ipEndPoint.Address}:{ipEndPoint.Port}");
byte[] bytes = listener.Receive(ref ipEndPoint);
listener.Close();
Console.WriteLine($"received {bytes.Length}(bytes) from {ipEndPoint.Address}");
Console.WriteLine($"MSG: {Encoding.UTF8.GetString(bytes, 0, bytes.Length)}")
Client
int CLIENT_PORT = 11000;
byte[] buffer = Encoding.UTF8.GetBytes("Hello, World!");
IPEndPoint ipEndPoint = new IPEndPoint("192.168.1.255", SERVER_PORT);
UdpClient sender = new UdpClient(CLIENT_PORT);
sender.Connect(ipEndPoint);
Console.WriteLine($"[Client] established endpoint, {ipEndPoint.Address}:{ipEndPoint.Port}");
sender.Send(buffer, buffer.Length);
Console.WriteLine($"[Client] sent {buffer.Length}(bytes) message to {ipEndPoint.Address}:{ipEndPoint.Port}");
Output:
[Server] waiting for broadcast from 0.0.0.0:0
[Client] established endpoint, 192.168.1.255:11001
[Client] sent 13(bytes) message to 192.168.1.255:11001
The server isn't receiving the packet from the client.
Is 0.0.0.0 a valid address?
0.0.0.0 is IPAddress.Any
not really familar with IPEndPoint, but any sounds kinda wrong to me as a parameter. ANd why are you closing the listener,is that the correct way to do it?
Thats what they did on the example:
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/using-udp-services
But you are not waiting for anything. You just open and close the listener
while (true)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine($"Received broadcast from {groupEP} :");
Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
}
this whole part is missing to keep receiving
listener.Receive
is blocking.
It blocks execution until bytes are received
so why would they put it in a while loop then?
To keep listening for the next message?
Its to receive the next message yes
And so the server ip is the same for you as in the example?
It should be
Its in local ip space
You should know 😄
You could try to use 127.0.0.1 if server and client are the same
I tried setting the IP to localhost, but its still the same result
You sure you got your ports open?
They should be there is no exception thrown when creating the sockets
I've tried now with random port numbers and still no difference in the result
I implemented this in python with socket.sendto and it works.
Its something do with .NET
Everywhere I've seen UdpClient.Receive() used put it in a while(true) loop
🤔
The docks say, it should block
The Receive method is blocking
The code is not falling through to the latter Console.WriteLine calls
So you are using .net 6 in VS or something, not really using unity right now, correct?
Yeah,
I'm just messing around with UDP code to learn for later use
Let me test this real quick
First thing vs tells me is, that the IP should be long, not string
So I need to parse the string
IPAddress.Parse("127.0.0.1")
is what im using
server
int SERVER_PORT = 28000;
UdpClient server = new UdpClient(SERVER_PORT);
while(true)
{
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, SERVER_PORT);
byte[] bytes = server.Receive(ref ipEndPoint);
Console.WriteLine($"[UDP/Server] received message: {Encoding.UTF8.GetString(bytes, 0, bytes.Length)} from {ipEndPoint.Address}:{ipEndPoint.Port}");
}
This script receives when using python
Client
import socket
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
destination = ("127.0.0.1", 28000)
while True:
msg = input("message:")
s.sendto(bytes(msg, "utf-8"), destination)
print(f"[UDP/Client] sent message: {msg}")
s.close()
client()
Nice got it working for the code I was using previously
It had do with how UDP works
You can receive from anything specific using it
Hm, also tried it, seems likes oemthings missing in net to make them receive it
not sure if its just unity or .net in that case, but read the last comment: https://forum.unity.com/threads/client-game-not-receiving-udp-packages-with-client-receive.805329/
Ok, so i'm making a multiplayer digital boardgame, and at first i made all work on the same machine (server and client). Now i'm testing having a...
hmm interesting
I wasnt running it in Unity tho
Just a basic Visual Studio Environment
Thats why I was testing unity to see if there is any difference. But I guess, based on the .net, it might be a limitiation of the same client sending and receiving or what not
good to know thanks for the help
hi guys, do you know if there's a way to spawn different player prefabs on the network manager? I wanted to do it randomly.
Is there any docs?
You can use .SpawnAsPlayerObject() to create a player object. You can also use Connection Approval
https://docs-multiplayer.unity3d.com/netcode/1.9.1/basics/networkobject/#creating-a-playerobject
Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:
Hey in a current Unity 6 Project using Netcode for Enties, MPPM and the Dedicated Server Package I get this error inside Netcode for Entities: Simulator\MultiplayerPlayModePreferences.cs(122,21): error CS0234: The type or namespace name 'EditorMultiplayerManager' does not exist in the namespace 'Unity.Multiplayer.Editor'
"com.unity.dedicated-server": "1.2.0",
"com.unity.multiplayer.playmode": "1.1.0",
"com.unity.netcode": "1.2.3",
This are the package version. No newer Versions are available in the Package manager and it uses the latest Unity 6 preview build, is there any way to fix that?
Anyone know how to use the anticipated network transform, I'm messing around with NGO and can't find any official docs on this component
The docs are here
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/client-anticipation/
Client anticipation is only relevant for games using a client-server topology.
There is also a sample project
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/main/Experimental/Anticipation Sample
thank you kindly stranger
he is not a stranger
he is a mod for unity ngo discord
ok.................
Its easiest to just make the single player connect to local host.
Stupid fuck scammed me. This was for a contract he had with me and he ended up taking my money and not delivering anything in return.
I want to make a multiplayer game in Unity. What should I use? I used proton PUN before, but it was too laggy for the game
is there any better way?
i thought of steamworks, but it was around $100 for a single project, correct me if i am wrong
unity multiplay was also an option, but i have not used it
could you suggest any option?
Steamworks itself is free. the $100 fee to post on Steam in general. But there will always be latency in networked games. You just have to design around it. Photon Fusion has client prediction built in to help with this. Netcode for Gameobjects 1.9.1 has a new Client Anticipation system to help with responsiveness
ohk, thats nice
hey everyone, im using photon pun 2 for an arena shooter, and im having some issues with a playerFiredFrom reference that the bullets should have.
essentially the Shoot() method sets it, but that only happens on the client that is shooting, the reference isnt updated on network
but im not sure how to get it to sync across the game
its better to explain what your gameplay looks like
some netcode may suit some do not
A simple one. Photon quantum is best
But its like learning another engine but 1000% worth the investment
actually i tried this same, but on different laptops
and, it was working rather smoothly
but i wrote this code like, an year ago
so, i am not sure,
i do want to rewrite to whole code....
but i will do that, if that makes a significant difference
so, i have no problem in learning any other service provider
can i use steamwork, for a game that i might upload on itch.io?
could u suggest any other multiplayer service provider?
maybe a server client relation would be better solution?
PUN should works just fine, maybe try
Mirror, Mirage, or NGO or Netick with Unity Relay if you dont want to use steamworks
Otherwise use photon fusion or quantum
All works for your game
ohk... so i am still with PUN
i think i should rewrite the code, because it is very poorly written....
Hey!
Question,
When players connect to my server, and fill in a username,
The username will be added to a TMP_Text field,
This works and display fine for everyone,
But have a problem
Problem
- When user 1 fills in a username, it gets added to the first field,
- When user 2 fills in a username, it gets added to the second field, BUT, the second user, (that connected after the first user) is not able to see the text input field of the first user,
So its not displaying the username if the player that was already connected,
Does someone here know how i can make it, that it will show all the changes made to the scene (text fields in the scene) when a new user is connecting?
Script of thhis function:
[PunRPC]
public void SetNickname(string _name){
if (chatManager.nickname1Text.text == ""){
nickname = _name;
chatManager.nickname1Text.text = nickname;
chatManager.nickname1GameObject.SetActive(true);
} else if (chatManager.nickname2Text.text == ""){
nickname = _name;
chatManager.nickname2Text.text = nickname;
chatManager.nickname2GameObject.SetActive(true);
}
}
How would i handle a failed connection attempt ? im using the default network manager and tried messing around with
The DisconnectTimeoutMS value of the unitytransport component
and the
OnClientDisconnectCallback of the networkmanager
Doesn't seem to work as intended, doesn't get called or anything
i found this but this seems to be outdated
that variable doesn't exist
This is for the old Unet system.
You might be able to us OnTransportFailed
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/api/Unity.Netcode.NetworkManager.html#Unity_Netcode_NetworkManager_OnTransportFailure
also, is there a way to check and avoid multiple people from hosting at the same time in the same network?
or rather if there is a server running on that adress
For a LAN game you would have to use something like Network Discovery
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
I’m not familiar with the library you’re using, but this is just how RPCs work. They are one shot messages sent over the network, and any client that joins after the fact has no knowledge of previous RPCs as they are sent and gone immediately after.
I am trying to build a simple FPS multiplayer game using Photon PUN 2. In my game, there are some targets, and players can raycast at them to change...
This guy here had a similar problem and his solution seems okay
ah thanx! 🙂
I'm not entirely sure how to place cameras in my multiplayer fps game. Like, if the camera is positioned in the head of the player on the client, how would I make bullets come out of the weapon while still being accurate?
Are you using NGO? Client-auth hit detection? PvP?
If so, there are more problems to consider than just accuracy.
The actual "bullet" that will hit other players in FPS games comes out of the camera. The weapon just provides visual effect.
Hey is Photon 2 PUN in maintenance or it is still working to create some multiplayers for a game ?
https://doc.photonengine.com/pun/current/getting-started/pun-intro
PUN Classic (v1), PUN 2 and Bolt are in maintenance mode. PUN 2 will support Unity 2019 to 2022, but no new features will be added. Of course all your PUN & Bolt projects will continue to work and run with the known performance in the future. For any upcoming or new projects: please switch to Photon Fusion or Quantum.
Yeah you're right thanks 
"I like your funny words, magic man"
I'm just using Unity Transport
Yeah, that's what I mean, how do I go about aligning the real bullet with the visuals?
Anyone know any good tutorial about how to open a web page throught a WebGL project? I tried this tutorial ( https://www.youtube.com/watch?v=kWxPZLNVxSU ) , but when I click on something this error appears.
In this video, you will see how you can open links in a new tab in a Unity WebGL build. Normally, Application.OpenURL won't work since it's played on the browser. You may had this issue after publishing your game to itch.io
----------| Related Links 🔗 |----------
✏️ Blog Post: https://HypedCloud.com/blog/how-to-open-links-in-unity-webgl-games...
Solved. I was using this Plugin:
var plugin = {
OpenTab : function(url)
{
url = Pointer_stringify(url);
window.open(url,'_blank');
},
};
mergeInto(LibraryManager.library, plugin);
But it looks that Pointer_stringify has been deleted on the last versions of Emscriptem. Changing Pointer_stringify(url) to UTF8ToString(url) solves the problem
You don’t, you mask the visuals on top of working physics and logic. Look at a game like CSGO. Bullets come straight from the player models head and you pretty much never see them. It’s just paired with visuals like muzzle flash, empty shells coming from the gun, very short bullet tracers, etc.
Muzzle flash and empty shells are easy to do. Bullet tracers you can just simulate a very fast visual effect that goes from the barrel of the gun to the hitpoint of the bullet. It won’t be 1:1 with the real bullet but it doesn’t really matter because bullets travel so fast and in most games tracers are only seen for a frame or two.
Hi, big problem here, I can't build with IL2CPP, the error seem to be linked with Rpcs and NetworkBehavior
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The error message is in french (Don't know why only the error message) but here it is in english:
"No user-defined conversion operator is available to perform this conversion, or the operator cannot be called."
The build work fine with Mono
weird I just got a IL support error as well after 45min compile.
Building E:\dev\Unity\MultiplayerTest\MultiPlayerTest\Builds\MultiPlayerTest_Data\Managed\Unity.Collections.LowLevel.ILSupport.dll failed with output:
Copying the file failed: Access is denied.
I see a lot of issues when googling it stating its a bug.
This collections has to do with Burst compiler, lots of issues with this new burst technology they implemented.
I fixed the issue, I updated the NGO Package to 1.9.1 as in 1.8.1 it fixes the bug:
Fixed a compile error when compiling for IL2CPP targets when using the new [Rpc] attribute. (#2824)
I updated collections and burst, compiling now but another 35min to go lol to see if that fixes the issue.
Not really a burst issue. It's the use of it by relatively new packages like NGO. Burst compiling provides countless performance benefits.
yo guys
i have a problem with Netcode
i want to have two different locations as... scenes for example(Main world and Dungeon or Main world and castle Interior), and let one player be inside the dungeon while another player is in the main world
and also let another player get to the same dungeon so main world is empty
and well, how can i make it so the host player "controls" the NPC's/collisions and stuff inside the dungeon while not being inside it(while being on another scene)
idk if it's even achievable with netcode, or maybe i'm going in a completely wrong direction rn
It's possible within Netcode but your main issue is going to be with the performance implications for the Host.
You can additively load scenes so the Host is able to run logic whenever needed, but then you're adding performance strain for the host player that isn't present for other clients.
well, i probably need a "server" application then
or distribute the loading to all clients
Yeah. Probably the best solution.
but how do i connect the "server" to NavMesh/Colliders and stuff like that
Yeah, depending on the complexity of your NPCs and other things.. clients could probably simulate these things themselves.
what do you mean?
i mean if there is some kind of server, how should it process data from clients and send them data from game
like "YOU CANT MOVE HERE CUZ WALL"
The server is running Unity so it will process all of your physics and navmesh agents if you have any
The server will act the same as a Host. There's just no client connected to the same session and thus no player object.
you can also probably save yourself the trouble of networking stuff like this. If worlds/maps/levels are pretty static in nature, each client can just have the map for the NavMesh and tell itself it can't move any further.
I'm not sure if the nav mesh agents are deterministic. I might be possible for the same agent on different clients to take different paths
Hi, i have this weird error after updating to NGO 1.9.1.
InvalidOperationException: Nullable object must have a value.
System.Nullable`1[T].get_Value () (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0)
Unity.Netcode.NetworkObject.HostCheckForGlobalObjectIdHashOverride () (at
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
That is a known issue with fixedstrings
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/2920
@sharp axle How do I pinpoint where is it from?
Hey im trying to make interract two prefab together, inside the Resources folder so I put them as siblings of a prefab "ball+ui", but when I do .Transform.GetChild(0) and .Transform.GetChild(1) to interract with them, it uses the two prefab that are outside my "ball+ui" it's because photon can only get what is inside the Resources folder, any one would have any idea how to make interact two prefab inside Resources together ?
actually that is something different
Okay, do you know why it is happening
True. Didn’t think of that.
It happen when a client join the game
looks like it might be something with the global object id. try to remove and readd the prefabs from the prefab list
Just an FYO, updated Burst and Collections in the Package manager took care of the IL.Support issue 🙂
@crude peak Im aso about to head into the issue with multiple characters in other loaded scenes. I would guess because each player has a NavMeshAgent they should communicate with the server how to path and collisions. Dont think this would really work good as running a Host though.
I'm downgrading to 1.8.1 to try to know where is came from
well, but how should it treat multiple scenes
Downgrading to 1.8.1 fixed the issue
@crude peak Googles Using Netcode for Asymmetric multiplayer with multiple scenes
They would loaded additively in different locations.
if i spawn them underground like on -1000 will it be alr?
so they are not visible from main world
You can put it wherever but be careful about putting it thousands of units away. You want it as close as possible without being visible.
Hi again, if I Instantiate with Photon a prefab containing 2 prefabs, and I put vanilla Position coords of Unity in the 2 objects will the position of the 2 objects synchonised for 2 players ?
that should be fine. but yea, you will eventually start running into floating point error if it gets too far away
my world is 6k by 6k
so well, will probably put each dungeon somewhere between those values
and on -1k on Y
also since player amount is low, i can have 4 dungeons in total which means i can spawn on like 0 -1000 0, 1000 -1000 0, 1000 -1000 1000 and 0 -1000 1000
to make sure they are far away from each other
@sharp axle wanted to mention you since you've seen this code snipped already, i guess.
I wanted to change my code around a bit so i can treat some special case scenarios when connecting. I came to a conlusion when i use the onClientConnectedCallback in Line 82 , i get the errors below when i try connecting as a client
If i leave out that callback it works fine but i need it to continue the code once connected and just have the Connection timeout coroutine as a backup
Not sure if this will fix anything but you may want to try only subscribing to the callback for clients
Tried this, still the same outcome
Im really confused, was trying to fix this yesterday too.
If i dont subscribe to that callback, and just load the scene manually after that time period in the Timeout Coroutine , it works
Why have you elected to do any scene loading if the scene just gets loaded on connection anyway?
It doesn't load on connection without the callback, that's why i need that callback instead of making the player wait even though he's already connected
Forget the callback and the method OnConnectionSuccessfull(ulong obj),
if i just start the coroutine and don't use the onClientConnectedCallback from the network manager and then do the loadscene command inside that coroutine, it works.
For Reference, this is how i had it before ( Loading done after the timeout time has ran out , which is bad because i don't want the player to wait)
private IEnumerator ConnectionTimeout(float timeout, string mode)
{
yield return new WaitForSeconds(timeout);
if (NetworkManager.Singleton.IsConnectedClient)
{
Debug.Log($"{mode} connected successfully.");
SceneManager.LoadScene(sceneToLoad);
}
else
{
Debug.Log($"{mode} failed to connect within {timeout} seconds.");
networkManager.Shutdown();
SceneManager.sceneLoaded -= OnSceneLoaded;
ConnectionFailed.SetActive(true);
}
connectionTimeoutCoroutine = null;
}
This works, but the downside is that it waits given amount of time until it actually checks if you're connected or not
I more meant why the design choice to load the scene on connection? If you just have a main menu and a game scene, you can just use an overlay canvas for the main menu inside of the game scene. Then there's no scene loading calls.
didn't want everything cramped into one scene
I would personally recommend reworking your event subscriptions and unsubscriptions, because they could be called a little safer IMO. But, if that's too cumbersome you can just try changing yield return new WaitForSeconds(timeout); to yield return new WaitForUntil(() => NetworkManager.Singleton.IsConnectedClient);
If you're going to do that I would make a different coroutine so it doesn't get in the way of your timeout logic.
private IEnumerator WaitForValidConnection()
{
yield return new WaitForUntil(() => NetworkManager.Singleton.IsConnectedClient);
SceneManager.LoadScene(sceneToLoad);
}
and if that gives you issues you could try:
private IEnumerator WaitForValidConnection()
{
yield return new WaitForUntil(() => NetworkManager.Singleton.IsConnectedClient);
yield return new WaitForEndOfFrame();
SceneManager.LoadScene(sceneToLoad);
}
for some added safety
Hello!
I need fresh ideas to fix a problem I have with the multiplayer of my game. Basically when players load a specific scene, the host generates a map procedurally, which is essentially just empty gameobjects with a specific tag across the network. Then the host calls a ClientRpc, which should tell All clients to generate a tilemap by getting all of those empty objects tagged and generating a tilemap on them. Works great on my machine, and in the editor, but in build versions it seems like spawning NetworkObjects takes longer, and on the client it seems that the clientRpc gets executed too early and the Tilemap doesn't generate, because the tagged gameObjects haven't been spawned yet.
Any idea on how to fix that? I tried with a lot of thing, and I'm still running into tricky issues with performance and the Inherent multiplayer delay.
Basically, I would need to detect, on the client side, that all the "spawnpoint" have been instantiated. How could I do that ?
To make your set up easier, I wouldn't even bother doing NetworkObject.Spawn().
But then how can I sync my map, since it is generated randomly?
Just send the position + tag of each GameObject over the Network. Have each client instantiate the tiles based off that info.
Tbh I have no clue how to implement that
This is driving me crazy because I have to send this project by tomorrow 
Do you not already have map gen code that randomly picks the position of GameObjects?
Everything works through those spawnpoint, a spawnpoint contains a prefab and instantiates it at runtime if the scene is single player, otherwise it spawns it across the network if it is a multiplayer scene. I first have spawnpoint that spawn room prefabs which contain more spawnPoints for objects like enemys, coins, chests and spawnpoints that do nothing on their own but are tagged and used to generate the Tilemap.
Tbh I didn't do the levelGeneration, I've been tasked to adapt it to make a multiplayer version of the game and the architecture is garbage but it's too late to change it
@tame slate you're a lifesaver
Coroutine worked?
yeah waituntil was actually a good workaround
can't believe i didn't think about it
It's awesome for Netcode. You almost never want to pick an arbitrary amount of seconds to wait before performing an action based around networking. It's either unsafe or just too long for users.
well now i only really have to handle disconnects, right now i have nothing to handle them, if someone leaves everything breaks, haha
@smoky pilot if you send some of the code I can help you work together something like this. It's not too complicated
What I simply need is to call a function ( the clientRpc which spawns the Tilemap )
when I am sure that all the objects have been properly spawned across the network, and that the clients have received them. If you can help me do that, that'd be amazing.
Usually for procedural generation, the level is generated locally on each client with a shared seed
I haven't worked with NGO in a while. Is there not a callback for when NetworkObjects are spawned?
Because on the host side I call the clientRpc after spawning everything, it breaks down on the client side because he didn't receive the objects yet.
I have no clue, I didn't work with them at all
( callbacks )
I could make an ugly wait for seconds on the host before calling the ClientRpc but that's a shitty fix
Even for my standards
Sadly we didn't think it through enough since it's our first project and now we're basically fucked and stucked with it

Does the map gen code have some sort of variable that tracks how many objects are spawned?
Not at all, it just checks if the path is correct ( if you can go from the first to the last room ) then it instantiates the rooms which make that path, then fills the rest of the map with random rooms
Each object spawned ( the room itself and the objects spawned by the rooms) calls, at start, the function which instantiates a random prefab in their prefab list
So for example a room spawnpoint instantiates a random coin, ennemy or idk
But a room spawnpoint instantiates a random room
I mean you're making an instantiation call.. tracking it is as simple as doing objectsSpawned++;
Yeah this is a shitty architecture
But then how can I use that ?
Procedural generation
@sharp axle ty
Is there a way i can work around this error:
NotServerException: ConnectedClientsList should only be accessed on server.
Making a playerlist so i need this list
tried doing it like this and it didn't work, am i missing something?
[ServerRpc (RequireOwnership =false)] public IReadOnlyList<NetworkClient> GetConnectedClients()
{
if(NetworkManager.Singleton.ConnectedClientsList == null)
{
Debug.Log("Connected clients list is null");
return null;
}
return NetworkManager.Singleton.ConnectedClientsList;
}
You’re just returning the Client List on the server
You’ll need to send the list back through a ClientRpc if you want clients to have it
i tried that aswell, one second
[ServerRpc (RequireOwnership =false)] public void GetConnectedClients()
{
if(NetworkManager.Singleton.ConnectedClientsList == null)
{
Debug.Log("Connected clients list is null");
return;
}
UpdatePlayerListClientRpc();
//return NetworkManager.Singleton.ConnectedClientsList;
}
[ClientRpc] public void UpdatePlayerListClientRpc()
{
connectedPlayers = NetworkManager.Singleton.ConnectedClientsList;
}
not sure if this is correct but i tried this
That wouldn’t work, no
enlighten me
You’re not sending anything with the RPC, you’re sending a void message to tell all clients to access the list
Which is not allowed
Usually just easiest to make your own player list
You just tell a script on your player object to store itself in the list on Start()
by sending , do you mean returning in the client rpc method?
i mean, yeah, i could do that too. Just thought it'd be easier this way but apparently not
As far as I know, RPCs don’t support return values in the way you’re attempting to use them
void MyRpcInvoker()
{
MyRpcWithReturnValueRequestServerRpc(Random.Range(0f, 100f), Random.Range(0f, 100f));
}
[Rpc(SendTo.Server)]
void MyRpcWithReturnValueRequestServerRpc(float x, float y)
{
MyRpcWithReturnValueResponseClientRpc(x * y);
}
[Rpc(SendTo.ClientsAndHost)]
void MyRpcWithReturnValueResponseClientRpc(float result)
{
Debug.LogFormat("The final result was {0}!", result);
}
That’s usually how you “return” values with RPCs
Brooo lmao 
Ahah
Are you using photon?
Rahhh
NGO + relay + lobby
Our multiplayer is basically holding by a thread it's amazing it's even working in the first place
Guys is it possible to synchronize with photon Animations when we do Invoke to activate them ? PhotonAnimationView only propose parameters from the animator
If it works like NGO, you have to call a special method to sync that kind of animation
so are you suggesting a network variable?
For the list?
You could sync it if you wanted to yeah, but it’s not necessary
Each client can just populate their own list
You just have the player script add themselves to the list on Start(), so whenever a client joins and their player objects spawns for all connected clients
The objects Start() runs and the script adds itself to the list
can i even access other networkclients?
from a client
Not sure what you mean
well you said the client should populate the list himself
oh wait actually nvm
i dont need their networkclient
I would just store the player script or the NetworkObject
Whatever needs to be accessed most frequently
Guys, how can I make it so that when the host leaves, the client detects it and simply loads another scene? The callback on client disconnected doesn't seem to work like I want to
What I tried doing was adding a script to the NetworkManager which subscribes it to the event, and calls a function that calls networkManager.shutdown, loads another scene, then destroys the network Manager
What code do you run when the host “leaves”
Seems like the event isn't triggered
The NetworkManager isn't destroyed
The function doesn't seem to be called client side
No I’m asking what code you call when you’re leaving as the Host
And a connected Client doesn’t get OnClientDisconnectedCallback invoked?
Doesn't seem like it no
I’d try OnClientStopped then
OnClientDisconnectCallback may just be invoked for proper disconnections. I’d guess OnClientStopped invokes no matter what when a clients connection is terminated
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback();
NetworkManager.Singleton.OnClientStopped += OnClientStoppedCallback();
}
System.Action<ulong> OnClientDisconnectCallback()
{
NetworkManager.Singleton.Shutdown();
Destroy(NetworkManager.Singleton.gameObject);
return null;
}
System.Action<bool>OnClientStoppedCallback()
{
NetworkManager.Singleton.Shutdown();
Destroy(NetworkManager.Singleton.gameObject);
return null;
}```
i'll try that
nop, doesnt work either
weird
You can also just manually disconnect any connected clients before calling Shutdown on the Host
That should invoke the callback for sure
Ah yes that would seem easier
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;
public class NetworkManagerSetup : NetworkBehaviour
{
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
void Start(){
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback();
NetworkManager.Singleton.OnClientStopped += OnClientStoppedCallback();
}
System.Action<ulong> OnClientDisconnectCallback()
{
NetworkManager.Singleton.Shutdown();
Destroy(NetworkManager.Singleton.gameObject);
Debug.Log("Event Triggered");
return null;
}
System.Action<bool>OnClientStoppedCallback()
{
NetworkManager.Singleton.Shutdown();
Destroy(NetworkManager.Singleton.gameObject);
Debug.Log("Event Triggered");
return null;
}
}```
I am attaching this script to my NetworkManager, but for some reason it seems like the events never trigger, anybody has an idea why?
it should def. be called since i do that if(NetworkManager.Singleton != null) { foreach(var clientId in NetworkManager.Singleton.ConnectedClientsIds) { NetworkManager.Singleton.DisconnectClient(clientId); } NetworkManager.Singleton.Shutdown(); Destroy(NetworkManager.Singleton.gameObject); }
immediately upon pressing a button
ah, i am not assigning an event but calling the method
wtf am i doing lmao
Your event listeners should be void functions
You also might want to wait a couple seconds after Shutdown() before destroying the network manager
private void ShutdownNetworking()
{
StartCoroutine(ShutdownNetworkingRoutine());
}
private IEnumerator ShutdownNetworkingRoutine()
{
NetworkManager.Singleton.Shutdown();
yield return new WaitUntil(() => !NetworkManager.Singleton.ShutdownInProgress);
Destroy(NetworkManager.Singleton.gameObject);
}
so if i set up both events to trigger the first function, it should work when either the client or the host call Shutdown ?
I'd think so
wiat, the one who should call that fucntion is the one disconnecting right ?
i was about to implement it the other way around
hm, fair enough
One is just called manually, the other is just to ensure proper cleanup when force disconnected
What might be causing my InputEvent.IsSet to be true over multipleframes in a Predicted System, but only on the Client? On the Server in triggers once. Here is the code:
Currently trying to learn Netcode for Entities and obviously not understanding something here righ
Are you using the Dots Character Controller?
https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Tutorial/tutorial-netcodecharacters-prediction-thirdperson.md
I'm working on a coop game about completing tasks and defending a train and wondering if I should even bother syncing the train position or find a workaround to move the world around said train, without syncing over the network, and rotating it to match the tracks, the game takes place in a 3D top down perspective so the scenery isn't too important.
Any advice here would be great as I'm really struggling on how to approach my potential solution and can't find many resources on this problem
Guys im trying to synchronize my animation with Photon, PhotonAnimationView only takes parameters from the animation, but im using animation.Play for each animation, some say on Internet that it also synchronize the scenes but I cant figure it out, any ideas?
@tame slate Same issue with the connectedClients IReadOnly collection, now i'd need a network variable to store their name , no?
[ClientRpc] public void ShowNotificationWindowClientRpc(ulong clientId)
{
// get the name of the user that disconnected
string name = NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject.GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();
Debug.Log("Client disconnected " + name);
// get the notification object
GameObject notification = Instantiate(notificationObject, GameObject.Find("UI").transform);
// set the text to the name of the user that disconnected
notification.GetComponent<NotificationUI>().SetText($"{name} has disconnected from the Server.");
}
I just made the Host Subscribe to onClientDisconnected with this function
supposed to show a notification on everyone's screen saying "user has disconnected"
If players are all on the train then I would just move the environment. Syncing players on a moving platform can be tough.
Or yeah i could just save it locally again
You can use the new connection events if you need to know when other clients disconnect
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/connection-events/
When you need to react to connection or disconnection events for yourself or other clients, you can use NetworkManager.OnConnectionEvent as a unified source of information about changes in the network. Connection events are session-mode agnostic and work in both client-server and distributed authority contexts.
I just need access to the name variable located somewhere in the player prefab
OnClientDisconnected works fine for my case , i just need a way to retrieve the network object of the disconnected player
So i can get his name and display a leave message on the ui
Im wondering why OnClientConnected gets called on both host and client
and Disconnected doesnt
i wanna make a local player list like this:
public Dictionary<ulong, string> players = new Dictionary<ulong, string>();
void Start()
{
// get all players in the scene
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
// loop through all players
foreach (GameObject player in players)
{
// get the player object
PlayerObject playerObject = player.GetComponent<PlayerObject>();
// add the player to the dictionary
this.players.Add(playerObject.OwnerClientId, playerObject.GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString());
}
}
``` gets all players and saves their names and id's locally
I just need a way to handle newly joined players
i was figuring sending a client rpc from onClientConnected would work but since it also gets executed on the client it doesnt seem to work
I would use the player's OnNetworkSpawn to save the player name to the players dictionary
yeah im doing that
AFAIK even if you could access this, it'll be null anyway
public override void OnNetworkSpawn()
{
if (!IsServer)
{
ulong clientId = OwnerClientId;
string name = GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();
SendUpdateServerRpc(clientId,name);
}
if (OwnerClientId == NetworkManager.ServerClientId)
{
NetworkManager.Singleton.OnClientDisconnectCallback += (clientId) =>
{
ShowNotificationWindowClientRpc(clientId);
};
}
if (!IsOwner)
{
enabled = false;
return;
}
// get the maincamera
Camera mainCamera = Camera.main;
Camera_Controller controller = mainCamera.GetComponent<Camera_Controller>();
float zAxis = gameObject.GetComponent<PlayerMovement>().zAxis;
controller.CustomStart(transform);
transform.position = new Vector3(transform.position.x, transform.position.y, zAxis);
if (!IsHost)
{
GetComponent<Spawn>().TeleportPlayerToSpawn(gameObject);
}
}
[ServerRpc(RequireOwnership = false)]public void SendUpdateServerRpc(ulong clientId, string name)
{
Debug.Log("server rpc");
UpdatePlayerListClientRpc(clientId,name);
}
[ClientRpc] public void UpdatePlayerListClientRpc(ulong clientId, string name)
{
// check if this is the new user
if (clientId == OwnerClientId)
{
return;
}
Debug.Log("client rpc");
Debug.Log("over if statement");
// get the name of the user that connected
PlayerList playerList = GameObject.Find("Core").GetComponent<PlayerList>();
playerList.players.Add(clientId, name);
Debug.Log("Client connected " + name);
Debug.Log("end");
}
So whenever a client joins i send out a server rpc and then a client rpc so that every client updates their list accordingly, i don't want the rpc to be executed on the user that just joined because the Start script of the Playerlist would already add him to the dictionary, How come it doesn't get past that if statement if (clientId == OwnerClientId)
{
return;
}
Yeah im doing it locally rn but im having some issues rn, ^
So for some reason that statement is true, even though it shouldn't be on other client's
If you are doing this then you don't need an RPC at all
How else could i do it?
The dictionary is already updated. the ConnectionEventData from OnConnectionEvent will give you the client id of the player that disconencted
it's not the disconnect part that doesn't work, it's the connection part
telling all clients to locally add the new player to their player list dictionary
That should be done in the player object's OnNetworkSpawn()
Yes, this is the player object
i'll send you the full script
using Player;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerObject : Unity.Netcode.NetworkBehaviour
{
[SerializeField] public Sprite thumbnail;
[SerializeField] private GameObject notificationObject;
public override void OnNetworkSpawn()
{
if (!IsServer)
{
ulong clientId = OwnerClientId;
string name = GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();
SendUpdateServerRpc(clientId,name);
}
if (OwnerClientId == NetworkManager.ServerClientId)
{
NetworkManager.Singleton.OnClientDisconnectCallback += (clientId) =>
{
ShowNotificationWindowClientRpc(clientId);
};
}
if (!IsOwner)
{
enabled = false;
return;
}
// get the maincamera
Camera mainCamera = Camera.main;
Camera_Controller controller = mainCamera.GetComponent<Camera_Controller>();
float zAxis = gameObject.GetComponent<PlayerMovement>().zAxis;
controller.CustomStart(transform);
transform.position = new Vector3(transform.position.x, transform.position.y, zAxis);
if (!IsHost)
{
GetComponent<Spawn>().TeleportPlayerToSpawn(gameObject);
}
}
[ServerRpc(RequireOwnership = false)]public void SendUpdateServerRpc(ulong clientId, string name)
{
Debug.Log("server rpc");
UpdatePlayerListClientRpc(clientId,name);
}
[ClientRpc] public void UpdatePlayerListClientRpc(ulong clientId, string name)
{
// check if this is the new user
if (clientId == OwnerClientId)
{
return;
}
Debug.Log("client rpc");
Debug.Log("over if statement");
// get the name of the user that connected
PlayerList playerList = GameObject.Find("Core").GetComponent<PlayerList>();
playerList.players.Add(clientId, name);
Debug.Log("Client connected " + name);
Debug.Log("end");
}
[ClientRpc] public void ShowNotificationWindowClientRpc(ulong clientId)
{
// get the name of the user that disconnected
//string name = NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject.GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();
PlayerList playerList = GameObject.Find("Core").GetComponent<PlayerList>();
string name = playerList.players[clientId];
playerList.players.Remove(clientId);
// client cannot access ConnectedClients, use another way to get the name
Debug.Log("Client disconnected " + name);
// get the notification object
GameObject notification = Instantiate(notificationObject, GameObject.Find("UI").transform);
// set the text to the name of the user that disconnected
notification.GetComponent<NotificationUI>().SetText($"{name} has disconnected from the Server.");
}
}
I think you're over complicating the connection logic, if a player object's OnNetworkSpawn is called -> that means they joined
so you can just directly add the object to the list in OnNetworkSpawn
playerList.players.Add(clientId, name); is what you need in the onNetworkSpawn()
i indeed am
christ
NetworkObjects and NetworkVariables go a long way, it's always best to think about what synced data you already have access to before trying to add additional networking logic
damn i feel stupid
Don't lol, player objects are annoying to deal with
if you've got 4 players, that's 16 instances to worry about lol
and you're doing it all in a single script
it's hard to visualize sometimes
for some reason netcode will just not work on andriod for me. it works fine when i test it on my pc but when i build a apk file to test it on my phone it just wont work. my phone dose not want to connect as a host or client. anyone got a idea why this might be happning?
My netcode seems to work fine when testing locally but just now i asked a buddy of mine to test it over radmin/hamachi
and it seems to behave completely different for him
The Stuff that i choose (Name, Player prefab etc) gets selected and properly instantiated
but for some reason if he chooses something it just takes all of the settings from my client on my computer
could this be an issue with the firewall or something?
So our test scenario:
I had 4 instances of my game open, my friend also did,
I can choose my player name and prefab, connect to the server and it will use all my selected stuff
( this works for all of my clients on my own computer)
But whenever my friend tries connecting, it will connect him ( had to allow an inbound rule on the firewall)
but it won't take the stuff he selected, instead ( for some reason) it will just take the name , prefab etc of the last client i connected from my computer
hey guys, while having Netcode for gameobjects v1.6.0 i added it again using add package by name. And got 1.9.1 which I wanted.
Problem is that now my Player prefab is breaking because it doesn't have NetworkObject. When I check then it is there but with a wrong icon and when I remove it and try to add it manually in the inspector by Add Component then there is not Network Obejct (but manager or transform are).
I tried to remove whole package and re-addd it but with no success.
When I leave prefab with this weird "NetworkObject" then when I get back to the prefab it breaks again that it tried to access a script that is missing etc\
Try removing the package, closing Unity, reopening and adding Netcode through the Unity Registry
Check the console for compiler errors. You might need to delete the Library folder and reimport
websocket works on webgl build?
Yes, but only as a client. It will need either a relay service or a dedicated server
Im booking for a solution, o got oit of memory when i tried connect tô the server