#archived-networking
1 messages · Page 35 of 1
the positions of player 1 (the host) sync with the view of the 2nd player
the 2nd player just has no input
You'll need to make sure there is only one active camera in the scene
I have a camera as child of the player
shouldn't I?
was unsure if i had to have one Main camera attached to each player or just have a child camera for each player
You can do it that way, just have the camera disabled by default. also disable the character controller on the remote players
I understand but the issue is only session owner moves, the second player does not move at all
do i have to change the ownership of something?
add client authoritative movement? I don't really get it
The network transform can be set to Owner Authority. Clients should already have ownership of their Player Objects
first player, session player has client and local id of 0
does the 2nd player should have client id 1 and localid of 0 too?
or should it be 1
depends on where you reading it from. The local ID of the host/session owner will always be 0
Client ID should increment by 1 with each new connection
Any idea why I would be getting error during runtime on a Dedicated Server platform build but not on my normal builds?
The line throwing a NullReference exception is just accessing a gameobject through a Singleton patter
GameObject faceoffPosition = GameServer.Instance.GameState.GetFaceoffPosition(Team, Position);
When/where is this executing in script?
I'm using LiteNetLib and it's technically happening when the packet comes in.
Behind the scenes that might be on a difference thread, but I guess the focus is that this code works perfectly fine when I run the server in normal Windows platform mode
If I compile to default, it works. If I compile to Dedicated Server, it doesn't
@tame slate tagging since I forgot to reply
I didn't mean that low level, even if I could point to the issue at that level I probably couldn't tell you why. I just meant where are you trying to access the Singleton instance in your C# script?
I'm not sure how the answer then question then haha
I'm calling it from a function?
It's on another MonoBehaviour
Both of them are in the scene from launch
Awake, Start, an event callback?
Unity tends to execute with slightly different timings on different platforms, sometimes just switching up the order you initialize and access things can fix issues like this.
The singleton is initilized during startup
and the function call happens from a network receive event
So timing wouldn't make sense at all here
I can wait however long I want before I trigger this
Post the entire script. I tend to avoid Singletons out of principle. But there is no obvious reason it wouldn't work on a dedicated server. Unless it's getting stripped out in the build process for some reason
Does anyone have a example for using this type of RPC?
[Rpc(SendTo.SpecifiedInParams)]
What is a BaseRpcTarget, how do i use it
I currently have the following function i want to call:
[Rpc(SendTo.SpecifiedInParams)]
private void AttackRpc(RpcParams rpcParams = default)
{
var sender = rpcParams.Receive.SenderClientId;
var senderObject = NetworkManager.Singleton.ConnectedClients[sender];
Debug.Log($"AttackRPC");
var direction = (transform.position - senderObject.PlayerObject.transform.position).normalized;
_components.Movement.AddVelocity(direction * 10f);
}
How would i call this RPC to a specified target, it asks for a LocalDeferMode and a BaseRpcTarget
Can't find a example in the docs or google
trying to use photon fusion 2 to make a 1v1 fps game, im currently making my movement script work with fusion 2, but when i try to jump, it doesnt work more than half of the time. the grounded check works fine, its just the input isnt right.
player control script: https://pastebin.com/WfTu1Jq2
input handler script: https://pastebin.com/5ZQD81Xg
could someone please help me with this?
Can anyone please link to a guide on using the NetworkManager, but specifically with a dedicated server that exists separately to the client?
All I've been able to find are tutorials where they'll add a "start server" button and have all the logic exist within one scene
I'm looking to have a dedicated server build that can be distributed separately and works by itself
You can find an example here
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/#completing-the-ping-example
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
You can make a build that takes in command line arguments , you can listen for like a -server tag or something to start as server directly
This is part one of the Porting from client-hosted to dedicated server-hosted series.
thanks guys
Any of you guys doing XR ?
Important: You should never have more than one active XR Origin in a scene
https://docs.unity3d.com/6000.2/Documentation/Manual/xr-origin.html
Im using fusion framework in shared mode so the first thing I did was to spawn a XR origin every time someone joins, so I have multiple XR origins in my scene and the game behaves weirdly
I think I have to do something about the main camera that is coupled with the Move locomotion controller, but I wonder if there is a more simple solution
SO far I have added this to my XR origin prefab
public override void Spawned()
{
if (HasStateAuthority)
{
GetComponent<XROrigin>().enabled = true;
}
}
Like only the local guy enables the XR origin component that manages the MainCamera thing, but then other guys on the scene are still coupled to that one main camera, so I guess I have to unlink my rig from the main camera, but again am I doing it wrong
Ty
I think i was looking into the older NGO docs
The XR Rig should not be networked. Keep that local. The VR Avatar can be your spawned player object.
Check out how the VR Template does it
So I add a networked object and transform on each separate hand mesh and head, instead of one networked object on the xr origin mesh and networked transform on hand and head?
As long as I dont have the full hierarchy of the xr origin prefab I shouldnt have any oddities and conflicts between maincameeras and xr origins right
In netcode for GameObjects is there any way to spawn a Player in DontDestroyOnLoad?
Would be the same as doing it with any GameObject. Put a script on it that puts it in DontDestroyOnLoad on Awake/Start
i mean i did that before and got these errors so thats why im asking
Player Objects already will migrate to the active scene automatically, so DDOL shouldn't be needed.
My player object dont migrate maybe becouse i have scene management/syncing disabled
I've got a syntax question.
Here is my code:
// PlayerController inherits from NetworkBehaviour
var player = collision.GetComponent<PlayerController>();
if (player?.NetworkObjectId == shooterID) return;
However, chatgpt keeps changing my code from that to this:
var player = collision.GetComponent<PlayerController>();
// Ignore the collision if it's the player who shot the bullet
if (player != null && player.NetworkOjbectID == shooterId) return;
I don't see anything wrong with my syntax
Nothing wrong with either of them. The 2nd one is more explicit in what is being tested
Hi!
I have a problem: for late-joining clients, OnValueChanged event doesn't trigger (for other players' GOs whose value have changed) upon connecting (value itself is synced).
Upon connection I expect all of the local GameObjects to receive updated values of their NetworkVariable and thus call OnValueChanged but it doesn't seem to work.
Here's the relevant code.
public NetworkVariable<int> coin_count = new NetworkVariable<int>(0);
public override void OnNetworkSpawn()
{
coin_count.OnValueChanged += OnCoinCountChanged;
// OnCoinCountChanged(0, coin_count.Value); # this works but i dont like it. Think I'm missing something
}
public void OnCoinCountChanged(int previous, int current)
{
int interface_coin_count = CountChildrenWithName(coin_panel, "Coin(Clone)", 0);
int change = current - interface_coin_count;
for (int i = 0; i < change; i++)
{
Instantiate(coin_prefab, coin_panel);
}
}
I found the solution of manually calling callback function but i believe there has to be a better approach.
Any knowers?
Also when debugging networked games, scripts dont pause on breakpoints for every instance of the script. I would expect every instance of a script to pause first on server, then - on clients. Is there settings/documentation regarding this?
Hey i need some guidance...
Goal: I want to create multiplayer game where players interact only via chat and they can just see each other characters but thats it... no other interaction. every one have its own mobs spawned, item dropped etc. + i want to make it little bit harder to cheat thanks to server authority.
My Current Idea is to handle server with dots and netcode for entities but i want client side to avoid dots where possible. I want game to build for dedicated server and dont support host as client at all.
I have some problems finding some nice and not outdated examples or good guides how to handle netcode like that :/
i wanna start with implementing some basic core feature: Mob spawning!
Idea: On servers there are placed entities that are templates for spawned mobs. for individual players it pools mob from pool with reset stats. when player defeat a mob than template on server will count down respawn time for it.
i am not sure how to handle pooling in this mixed dots/gameobject & server/client context
This is is the way I do it. Seems the most straightforward to me
If you want to simulate individual client worlds on the server, that aren’t shared, that’s going to be a lot of simulations to run in parallel.
I would maybe consider splitting them up into two instances- One server instance that only syncs chat and player transforms, and one per-client instance that is in charge of world simulation / gameplay. The latter could be made with DOTS, and the former in something like Go, since you wouldn’t need the overhead of Unity to simply sync transforms and chat.
It doesn't sound like you need Netcode at all. I would use Unity Cloud Code for any server logic you need to be cheat resistant.
Personally, I wouldn't try to mix Entities and Gameobject logic. The server could definitely use the job system with gameobjects if you have loads of NPCs
i was thinking something like:
on server entities: templated mobs. while on clinet side it's just a prefab. and maybe i could just handle it with RCP like sending them when mob dies and somehow receive it on server entity side where it cold be consumed in bathes.
I will check out Unity cloud Code, but also i am obsessed with control so kinda just wanna handle my servers by my self :/
Anyone have any idea why my packets sent sometimes spikes to 1k/s when connecting to the host on the second window?
I only have some small codes going, movement, 4 slot inventory and pickupable objects
If you are using NGO, they you can use the Network Profiler to see where the messages are coming from. Could be from Network Transforms.
Ah thanks, will take a look at that later. Do you by any chance known how much data and packets is normal for a small co op game?
That depends completely on your game.
Is there any way to know if I’m implementing things in a wrong way that uses way too much bandwidth? It’s my first time doing multiplayer so the numbers don’t say much to me atp
You'll get warning when the Send Message Queue gets full. Just keep an eye on the Network Profiler
Usually you'd calculate the size of the data types you're sending to get a feel for what range you expect your bandwidth usage to be in, based on what you believe you are sending.
https://learn.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-170
(and strings are usually int (count) + number of characters (char).
Depending on the framework or library you use, the documentation will often times mention the base size of your packets. Some frameworks will tack on player ids, packet sequence numbers, network time etc, before you've added any data at all yourself.
Well yeah that’s the warning I’ve been getting when the packets spike (max queue is set at 128, no idea of that’s good)
Will look into this as well, thanks!
If you get queue warnings on connect it almost sounds as though you're trying to send data before the connection is fully established. This could be a non-issue if your queue gets full and then on connection established it's flushed back to the client- since it's a one-time purge of the built up queue (I'm not sure what framework we're talking about here so keeping it general)
I'd only worry if the warnings were continuous
I’m using Netcode for game objects. That could be the case, I’m early in the development stage so I only have a host and client button that instantly spawns the player prefab with all the scripts on when connected.
As far as I’m aware the packets drop after the spikes, which can range from 200 packets/s to 1k packets/s. but I’ve not tested that much so far.
It also varied who got the warning messages, sometimes the host and sometimes the client got them.
Are you sending RPCs in Update()?
I would expect the bundled components (NetworkTransform, NetworkAnimator etc) to only send after a connection has been properly established (but they might not)-
but could it be that you have custom send logic that's sending data without checking the connection, when perhaps it should? (Although again I'd expect NGO to not let you send to an unresponsive client)
Although I suppose the queue might just be for that- letting you queue up messages in case the client is momentarily unresponsive
No, all rpc’s are outside of update methods
The only network transform I use so far is a client network transform on the player
But assuming you have a tick rate of 20hz, and you peak at 1k/s,
that's still only 50 bytes per tick, which is hardly a lot all things considered.
Yeah it’s not a lot after all, the data getting sent so far doesn’t exceed 3kb. But I still got unsure due to the warning messages I get
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Hello, I am in the process of discovering NGO. I've been following the CodeMonkey tutorial (https://www.youtube.com/watch?v=3yuBOB3VrCk) and I pretty much understand how setting up NGO works. But I'm running into a silly problem. I can't spawn an object and make it the child of another.
I've created a GameObject called NetworkObjectSpawner. I've associated it with a script called NetworkSpawner, which is as follows:
https://codefile.io/f/BKIUa3ETRt
It takes as parameters the transforms of 3 prefabs. "Player" representing the player, "spawnedSword" representing a sword and "swordContainer" representing the location where the sword is contained in relation to the player.
When I run it and I'm in host, the player, the spawnedSword and the swordContainer objects appear correctly in the scene, but swordContainer doesn't become the child of player. I know this because parentResult returns false.
To make things clearer, here are some screenshots to give you an idea of the architecture of my project:
The first represents my project when it's not running with the NetworkManager next to it.
The second shows it when it's running as a host. You can see that both the sword and the players appear. The swordContainer also but only visible in the hierarchy since it is empty.
Could someone please help me?
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=YmUnXsOp_t0
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubre...
I want to create a multiplayer game but when I use the Competitive Action Multiplayer I get a whole bunch of errors
Just a guess, but you may not want to make the parenting call right after the spawning of the sword. I would try the parenting inside the OnNetworkSpawn of the sword.
For a simple Peer to Peer (I am not doing a server, the scope is a simple Peer to Peer Multiplayer game, maybe Steam if that is free) game what Multiplayer framework is the simplest?
I'm not doing anything competitive, Co-Op PvE is the ultimate goal with this.
Pretty much all solutions are mid-to-high level or high level, so they all are relatively simple. I would just watch some basic introductory tutorials and go with what seems most comfortable for you as that is what is most important, IMO.
That being said, I would personally recommend NGO. Staying within Unity's ecosystem can be a good thing simplicity wise, especially if you end up using other UGS packages to pair with NGO
I have a class that contains all the players stats and is a networkvariable in another script that is attached to each player. It seems to correctly synch names and the health changes when they take damage, but it seems to get de-sync'd and will show different health values for different players if the test damage object is touched. Is there a trick to keep a NetworkVariables variables better synced?
Network Variables are sent reliably so they are guaranteed to be updated at some point. I would send your code surrounding the NetworkVariable
This is the RPC I used to set the variables I feel like I'm missing something for sure
`[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
SetCurrentAttributes(attributes.Value);
}
public void SetCurrentAttributes(AttributeContainer attri)
{
attributes.Value = attri;
}`
I think this is just a typo
Should be
[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
SetCurrentAttributes(attri)
}
Currently you're just ignoring the value sent through the RPC and setting the NetworkValue to its existing value
I changed it to `[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
SetCurrentAttributes(attributes);
}
public void SetCurrentAttributes(NetworkVariable<AttributeContainer> attri)
{
attributes = attri;
}`
but it still seems to get desynced with a spammy damage thing
Hello, thank you for your reply. This was indeed one of the reasons why it wasn't working. Eliminating it has partly helped me solve my problem. Thanks a lot!
You're still ignoring the value sent through the RPC. All you should be doing is this
[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
attributes.Value = attri
}
- Send the value to the server with an RPC
- Take that value and apply it to the NetworkVariable by setting .Value
I understand now, it seems to be working. I did get an issue sometimes where the clines health would flicker between two numbers for all players but the numbers are synced ... even the new bug is sync'd, which is a mixed bag.
Thank you for your help
What version of Unity are you on?
Thanks!
6000
Make sure it's 6.0.28 or higher
How should I be using object pooling, specifically the Despawn() method?
I copied this object pooling code off github. It was originally for the boss room game.
I have a player, who is shooting bullets.
This is how I'm currently spawing the bullets from the pool:
void ShootServerRPC(shootDirection)
{
var net_Obj = NetworkObjectPool.Singleton.GetNetworkObject(BulletPrefab, transform.position, CalculateRotation(shootDirection));
if (!net_Obj.IsSpawned)
net_Obj.Spawn(true);
Bullet bullet = net_Obj.GetComponent<Bullet>();
bullet.Initialize(NetworkObjectId, shootDirection); // Provide the bullet with the id of the person that shot it.
}
And when I want to return the object to the pool, I use NetworkObject.Despawn(), and the code looks like this:
// this is in the bullet class
private void OnTriggerEnter2D(Collider2D collision)
{
if (!IsServer)
return;
// Some logic
NetworkObject.Despawn()
}
Does this return the object to the pool, or just delete it?
--- Other things I'm still debugging but would appreaciate help on ---
I don't really understand inferfaces, so I'm a bit confused on how everything works.
I do also have another error, when I try to despawn the network object, saying this [Netcode-Server Sender=0] Object is not spawned!. This happens even with the IsSpawned check.
Why might player and camera movement not be working on connected clients in my game? (netcode for gameobjects)
I have an owner-authoritative network transform component on the player.
Everything works perfect on the server, but on the client, the player cant move their cinemachine freelook camera or move around
The cinemachine camera is inside the player prefab which should be owned by the client
Does anyone know of a good Tutorial over NGO? Preferably one that either does Peer to Peer or goes through Steam (I am not going to run my own / cloud servers / whatever Unity offers unless it is completely free of charge.)
Most NGO tutorials just cover NGO itself and test locally, or they cover NGO with Unity Relay. There are probably a few tutorials here and there for Steam integration.
Unity Relay's free tier is very generous, and you wouldn't pay a cent until you have a player-base in the thousands (most likely).
Also worth noting that while Steam Relay/P2P may be "free", you are paying $100 to publish your game on Steam and they take 30% of your game sales.
Epic Online Services 
Steam is fine.
Talking with people who do play a lot of Indie games, they discover them mostly on Steam. Steam is a necessary cost in the grand scheme of things.
Hence the I'm fine with going through Steam, since any release will be on steam.
Steam is 👍
I guess it doesn't have to be NGO as well. Any framework works.
FishNet is supposed to be pretty neat. But I'd go with NGO - It's quite robust.
Is there any way i can sync the player Object in netcode for GameObjects other than Scene managment or dontDestroyOnLoad?
What exactly are you trying to sync? You choices for sending data are RPCs, NetworkVariables, or CustomMessages
I need to sync whole player's game object
Dynamically spawned objects are already synced to all clients
I mean when i change the scene, player just get deleted
Without Scene Management then you'll have to respawn the player when you change scenes
Can you give me any way how i can do it please?
Here is how you spawn player objects
https://docs-multiplayer.unity3d.com/netcode/current/basics/playerobjects/#spawning-playerobjects
PlayerObjects are an optional feature in Netcode for GameObjects that you can use to assign a NetworkObject to a specific client. A client can only have one PlayerObject.
ty
Does anyone know what kind of error is this? I have no dictionary, and if I remember correctly, a pretty similar error pops out when you use a NetworkBehaviour without a NetworkObject, but its not the case here.
KeyNotFoundException: The given key 'BombAbility' was not present in the dictionary.
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <8ce0bd04a7a04b4b9395538239d3fdd8>:0)
Unity.Netcode.NetworkBehaviour.__endSendServerRpc (Unity.Netcode.FastBufferWriter& bufferWriter, System.UInt32 rpcMethodId, Unity.Netcode.ServerRpcParams serverRpcParams, Unity.Netcode.RpcDelivery rpcDelivery```
Just means it can't find the NetworkBehaviour BombAbility when trying to receive an RPC.
Alright, then its because I only enable that GO in the client and not in the server, thanks mate!
I have a bullet, which I want to sync the fire direction once upon firing, but not the transfrom.
Will it be easier to use NGO, or just use MonoBehaviour?
Only network behaviours will sync over the network. Usually shooting is done with RPCs
Hi gang anyone know of some tutorial / resources I can look into to making client hosted lobbies in N4E
or just point me in the right direction of how to start
its annoying that the n4go docs are so incredibly elite and then n4e is like pretty mid
is the session workflow for both the same?
this is just about basic setup of n4e and dots its not really anything to do with lobbies and remote connection
Sessions are built with Lobbies and Relay
does anybody know about a netcode for entities tutorial that is good for making a first person shooter??
Check out the new template
https://docs.unity3d.com/Packages/com.unity.template.multiplayer-netcode-for-entities@1.0/manual/index.html
thanks but I actually used it but really understood all of it that's why I'm seeking a tutorial so I can learn how to create my own stuff
There are not a whole lot of DOTS tutorials in general
yea Ik😔 but I've seen others create an fps game in dots so I gussed there must be a tutorial out there
Does anyonwe know how to enable Distributed authority withour losing access to server rpc?
[RPC] will still work. But there is no central Server, so (SendTo.Server) will not work. You'll want to use HasAuthority instead of IsServer
So I will need to change everythin right? I cannot use both server auth and client auth at once
If you are using the old [ServerRpc] yea, those will need to change
And if I use RPC with sendTo.Server?
Change it to SendTo.Authority
One last thing, [ServerRpc] works the same as SendTo.Server?
Yes, they are identical
When i join the server with the first client its ok but when i join on next the second client cant see the first player. (The player get added into the DontDestroyOnLoad at the start of PlayerController script) any solution please? (I just need the way to transport the player object through the scenes)
Or is there any way i can use the scene management without the server's scene sync?
You can use Scene Validation to stop certain scenes from syncing
Netcode for GameObjects Integrated Scene Management
Yo @sharp axle sorry to bother you again, but is it possible to use Distributed Auth below Unity 6?
The last UNET package availiable in my editor is 1.11.0 and Distributed auth comes with 2.2.0 with seems to be only present in Unity 6
DA is Unity 6 and NGO 2.0+ only. If certain versions don't appear in your package manager, you can add NGO by name and specify the version number.
How to install Unity Netcode for GameObjects (NGO).
Is it safe to update or can it break stuff since is not really a compatible editor version?
NGO 2.2.0 is an official release, it will not break anything if installed on Unity 6.
thats the issue, im not using Unity 6 XD
Then you will not be able to use NGO 2.0.0 or higher and Distributed Authority. There's really not much reason to not upgrade to Unity 6 unless you are using really old packages that no longer have support.
Maybe I should
Thank you 🫡
Hey, I have a Network Transform on my player prefabs with Server Authoritative Mode and synchronized position and rotation axis. I now implemented an aiming mode where the player can cast a spell to a target area and the hero´s rotation follows the mouse cursor. this works fine on a host but does not work an a client as the rotation from my code is immediately overwritten by the server authoritative network transform. I have tried implementing a rpc call but its still the same. Is there an easy solution to this problem?
if (!IsAiming) return;
if (!aimingHero.IsOwner) return; // Ensure we’re the local owner
[...other code...]
Ray ray = Camera.main.ScreenPointToRay(PlayerInputManager.Instance.MousePosition);
if (Physics.Raycast(ray, out RaycastHit hit)) {
Vector3 targetPos = hit.point;
Vector3 lookDirection = targetPos - aimingHero.transform.position;
lookDirection.y = 0f; // Only horizontal rotation
if (lookDirection.sqrMagnitude > 0.001f) {
// Compute the target rotation based on the mouse position.
Quaternion targetRotation = Quaternion.LookRotation(lookDirection);
// Store the current rotation.
Quaternion currentRotation = aimingHero.transform.rotation;
// Smoothly interpolate locally.
Quaternion newLocalRotation = Quaternion.Slerp(currentRotation, targetRotation, Time.deltaTime * heroRotationSpeed);
// Determine the angle difference between the current rotation and the new rotation.
float angleDifference = Quaternion.Angle(currentRotation, newLocalRotation);
// Update the hero's rotation locally.
aimingHero.transform.rotation = newLocalRotation;
// Only send an RPC if the difference is above a threshold (e.g., 5 degrees)
if (angleDifference > 5f) {
RequestRotationServerRpc(newLocalRotation);
}
[...other code...]
}```
[ServerRpc(RequireOwnership = true)]
private void RequestRotationServerRpc(Quaternion newRotation) {
// Update the hero's rotation on the server.
if (aimingHero != null) {
aimingHero.transform.rotation = newRotation;
}
// Broadcast the updated rotation to all clients.
UpdateRotationClientRpc(newRotation);
}
// Called on all clients to update the hero's rotation.
[ClientRpc]
private void UpdateRotationClientRpc(Quaternion newRotation) {
if (aimingHero != null) {
aimingHero.transform.rotation = newRotation;
}
}```
@bitter rune
Is this a Monobehaviour or NetworkBehaviour? Monobehaviours shouldn't have a network transfrom.
If you are intending to use the NetworkBehaviour class, do not use RPCs for rotation. It will sync automatically (Do it through one of the network components).
If you are using MonoBehaviours, you shouldn't have a network Transform.
As for which to use, I think Monobehaviours will be easier to reduce latency, but I'm not too sure myself.
Quick note: You should add the word "csharp" after the triple backticks. That gives your code some color.
like this:
if (someStatement)
{
// Do something
}
is there a mirror server link somewhere in this server?
Do you mean the networking Mirror? 
yes
i can't send invite links here
send me in pm if you want?
In my case, it is a NetworkBehaviour script, attached to my hero prefab. Without that rpc, my issue was that on a client the hero did not rotate at all.
Check that your network transform is syncing rotation
That might be this issue
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/3205
does anybody know about a netcode for entities video tutorial that is good for making a first person shooter??
There aren't many videos for DOTS and NfE as they are pretty new, but Unity has some good templates and samples that give more than enough to get started and build off of.
I tried to learn from these templates
but it's impossible jk it's just really hard for me
Idk where to start
and I wanna build of it after I understand all of it
Then personally, I wouldn't be looking for tutorials specifically about NfE for making an FPS game. Start smaller, as there a a handful of tutorials that go over the basic of DOTS and NfE. Spending some time on those first might give you a better shot at going through the templates and samples.
Ok I'll try thanks
I'm using Unity Netcode for Gameobjects and Steamworks.NET. Is it worth to make a Custom SteamTransport with Steamworks.NET or is there someone who has already done so?
NFG is for small co-op games
Is there a unique player ID that is persistent across sessions, or does that need something like Steam APIs?
I believe this is the most popular choice amongst people who use NGO and Steamworks
It depends on what level of persistence you want. If you want a more reliable, secure and multi-device level of persistence, you'd have to use some sort of authentication service like Unity Authentication.
Something simpler would be just using something like device ID to recognize repeat players
It's mostly just to know which save to load for a player when they are connecting so the device ID might be fine
Does anyone know how to make a client network animator stop animating to allow a ragdoll to happen without rpc?
Tried disabling it with _animator.enabled = false but that doest sync
If I transition to a emtpy state with no motion I will just stay in the base position, but not really stop animating.
I would just hide the object with the NetworkAnimator and locally create a dummy copy of the animated object on each client to do the ragdoll
Yea. I usually just swap out the animated object for the ragdoll
But that would require to use a RPC to tell the network to perform the swap
In that case Id rather just use the rpc no disable the animator in the network too
Thats why Im asking if is it possible just by calling the animator or something similar
In terms of design and structiure Id prefer not to use a RPC here
You can do it locally if the same event happens on all clients. Like the health reaching 0. But some sort of data has to keep the state in sync. Either sent by network variable or RPC.
The player itself is the one who manages its death locally unsynced, but I got an idea
I can add a listener to the animator so check wheter a state is active or not right?
So if the animator transitions to the death state I jut disable it locally
wouldnt that work?
I suppose it could. I personally wouldn't trust the clients to manage their own death state. But no reason it can't technically be done
We are 2 guys doing an online moba from 0 with no experience, its not a "real" game so giving authority to clients is not a security issue for us, there is not gonna be hackers
Thanks tho 
Im coding a netcode game but my player object falls through the floor on the other players screen , I have my network transform y syncrinzation on but the player still falls through
Make sure you aren't disabling any colliders on the client side. The network rigidbody should be setting it to kinematic though
Hi, shouldn't a network variable be automatically synced with late-joiners?
I have a problem where my late-joining clients are not seeing player skins, even tho i'm subscribing to the OnValueChanged event on OnNetworkSpawn/Despawn as in the docs
The only way i got it to work is by calling the callback manually before registering to this event, which looks odd
The network variable is already synced at that point so onValueChange doesn't get called in OnNetworkSpawn
I had the same issue once, I solved with a server authoritative animator instead of a client authoritative animator
Hey
Can I temporarily disable the rotation sync in a network transform component by code?
As long as you do it on the authoritative instance, yes
yes, I found a way of doing this. But when I re-enable the rotation sync in that component, the character "snaps back" into its original rotation position. How could I properly hand-over the last rotation before re-enabling the network transform rotation sync?
SetState() might work
you are my personal mvp for today. I was able to fix it with SetState. Thanks a ton!
guys is comparing tags diffrent in network bc host and client don't detect the tag they collided with pls help me
If you are using NGO, then by default physics collisions will only fire on the server. Triggers will fire on all clients however.
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.
thanks
making a first person shooter multiplayer game, i cant figure out why players arent moving across servers. i've tried countless different things and i have no clue why it isnt working
input handler script: https://pastebin.com/hBuKFKmS, player control script: https://pastebin.com/9BA7wGyM
could someone help me try to solve this issue?
anyone else encounter an issue where if you play an animation on the client, the whole clip plays but on the other client's side, only the later part of the clip plays.
player 1 |-----------| full clip
player 2 |xxxx------| only the end part of the clip plays to maintain the sync
was tryna get a player to punch another player but realized that the later half of the swing gets shown so that they end at the same time
nvm clearly my dumbass didn't read this section
I'm using Networking.Transport for my multiplayer game and I got it working correctly on my local machine, but how would I get it working online?
Like, how do I figure out which IP address to connect to?
I'm currently using doing this for the server:
NetworkEndpoint endpoint = NetworkEndpoint.AnyIpv4;
```and this for the client:
```cs
NetworkEndpoint endpoint = NetworkEndpoint.Parse("127.0.0.1", port);
endpoint.Port = port;
You need to point to the public IP address of the host/server. Normally you would use a Relay Service like Unity Relay or Steam P2P
Generally you have fixed URLs/IPs which handle matchmaking and communicating IPs of game servers.
Hi. I'm receiving an HttpException1: (429) HTTP/1.1 429 Too Many Requests error very rarely when periodicly calling GetLobbyAsync. I have a RateLimits Class in-place to mimic the actual rate limits set out at https://docs.unity.com/ugs/manual/lobby/manual/rate-limits. I can't see how my implementation could cause too many requests. I suspect an obvious mistake 🤨 . The console logs show the printed time for each request. Here is my code (Class shortened) http://paste.mod.gg/cvetgxbogyvg/0
A tool for sharing your source code with the world!
Seems like you are within the rate limits, albeit only slightly. I would personally just give yourself more of a cushion with the interval times and not push so close to the rate limits.
I would also recommend implementing Lobby Events instead of manually updating lobbies every x seconds.
That's a good idea. I do plan on optimizing data transfer more. The Serverless multiplayer sample is where that code is from and that ran a 1.5s delay. Events sound far more efficient. Thanks
hi all, I am using relay and lobbies in unity and wondering how I can detect when the lobby the player is in is closed (for example the host quits), so I can make the main menu canvas active. any ideas?
There's a LobbyDeleted Event
You'll also get a ClientDisconnect ConnectionEvent when the host leaves
I can listen for that with something like LobbyManager.ClientDisconnect += OnClientDisconnect; right?
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.
NetworkManager.OnConnectionEvent
That did it, thanks!
how do i implement prediction smoothing in Netcode for Entities? The documentation is lacking: https://docs.unity3d.com/Packages/com.unity.netcode@1.4/manual/prediction-smoothing.html
What would you guys suggest for networking I've checked out Netcode for Entities but it seems new so im not sure if theres a whole lot of resources on it, and that i havent worked with ECS before
I would recommended learning ECS first then when your comfortable learn NetCode for entities
yeah i'd guess but theres also netcode for gameobjects but i've heard its not very good
What game are you making?
a small extraction shooter
NetCode for entities has client prediction which prevents people using teleport hacks
Which it’s important for an extraction shooter
yeah thats my main consideration
Unless your just doing coop then it’s not important
Alright ill look into learning ECS
Learning ecs is gonna take a bit of time but trying to implement your own client prediction I think will take even more time so using NetCode for entities might be quicker if you need client prediction.
Also then you get the benefits of better performance
Once you get the hang of ecs it’s just as easy to implement features compared to game objects
ive already been messing around with ECS just to try out netcode for entities but sometimes i get stuck and there arent enough resources i can find
i can get a entity set up as a ghost but then i cant figure out why it wont visually replicate
i can find it on the hierachy and see its values changing but it wont appear
is the movement logic inside "PredictedSimulationSystemGroup" ?
or is it just running on the client
just on the client
That’s why it’s not replicating to other clients
i have the client as "inGame" so i thought it would automatically replicate it
still cant figure it out
im just gonna fully learn ECS first then tackle networking
Hey everyone! 👋
I’m Nonso, a full-stack dev & smart contract engineer looking for a game dev to team up for a Web3 hackathon! I’ll handle smart contracts (EVM), backend, and Web3 integration—you bring the game to life.
If you’re into Web3 gaming and want to build something awesome, let’s team up! 🚀🎮
How would one implement a hit stop in a co-op game? Can’t simply slow down the game on the client, can I?
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Your options I’d say are a: slow the clients game down but then quickly catch them back up to the server/other clients time or b: slow down all clients/ server. I’m not sure these will work but something else might work these are just ideas
For example boomerang foo: where it slows down all players when someone dies
Hmm that seems a bit risky since I should also consider lag compensation. Making it a lot harder to manage. Maybe I can just stop the animation?
It should only occur on the client that does the damage, no need to sync it across the network anyways
Rubberduck moment
Thanks for the options tho
private void FireWeapon()
{
...
RequestFireWeaponServerRpc(hitPoint, hitNormal, didHitProp);
...
}
[ServerRpc]
private void RequestFireWeaponServerRpc(Vector3 _hitPoint, Vector3 _hitNormal, bool _hitProp) {
FireWeaponClientRPC(_hitPoint, _hitNormal, _hitProp);
}
[ClientRpc]
private void FireWeaponClientRPC(Vector3 ___hitPoint, Vector3 ___hitNormal, bool __hitProp) {
...
// Apply force if the object has a Rigidbody
if (shotObjectRb != null)
{
// Direction = from shooter (gun position) to the hit point
Vector3 direction = (___hitPoint - transform.position).normalized;
// Apply force in the correct direction (use Impulse for an instant effect)
shotObjectRb.AddForce(direction * 3f, ForceMode.Impulse);
}
...
}
The issue is that the gameobject containing the rigidbody only moves on the host. The object that gets shot has a rigidbody, network object, network transform and a network rigidbody.
I realize that the rb is kinematic on clients, and can only be moved by the server and then synced to all clients. But this is what I am currently doing, no?
Kinda stuck here
clientRPCs only run on the clients. AddForce() needs to run in the ServerRPC
Ah, that's where I screwed up.
The components on the objects that gets shot in the scene are correct at least?
as long as the Network Transform is set to Server Auth
I am using client auth on my players
these objects in the scene however are normal network transforms
still only get the movement on the host.. The rigidbody addforce is in the serverrpc @sharp axle
So annoying since everything has been going great until this part lol
You won't be able to move other players that way. Only the object owner would be able AddForce()
These are in-scene objects, not owned by any players. Am I thinking entirely wrong with my implementation in that case?
In scene objects are owned by the server so adding force in a ServerRPC will work. If the transforms are not syncing then something else is wrong
Noted, I'll look at the other stuff then, cheers bud
Does anyone else have the issue of prediction smoothing (NetCode for entities) working in play mode but not in a build?
I've been having an issue where the health value for the client flickers between two numbers. I have a network variable containing a custom class that has a health value inside of it. Has anyone encountered this before and know some fix? Everything seems to work most of the time it's just if the value tries to change very fast it seems to get confused.
I've seen people use NetworkVariable in update, so I doubt that's the issue. Send how you're setting the variable and how you're reading the value.
Looked at this earlier:
`[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
attributes.Value = attri;
//SetCurrentAttributes(attributes);
}
public void SetCurrentAttributes(AttributeContainer attri)
{
SetCurrentAttributesRPC(attributes.Value, NetworkObjectId);
}`
And this is where it sets the health/does damage:
[Rpc(SendTo.ClientsAndHost)] public void DamageRPC(int damage) { int HP = attributes.Value.Health; HP = HP - damage; attributes.Value.Health = HP; UpdateHUDDisplay(); SetCurrentAttributesRPC(attributes.Value, NetworkObjectId); }
oh I'm not pasting that correctly
hey does anyone know a tutorial or anything that could show how to set up photon fusion 2 dedicated servers? Ive been looking into it and I cant find any specific help for dedicated servers and it would be really appreciated if u could let me know
I have a question if i want to link a command drom discord to my unity can i make it or not ? I'll probably need to use an API ? or having a server to send the instruction ?
Discord has a Game SDK that works with Unity
Ohh that’s game changer
What sort of problems are you having?
Hey!
When I create a new lobby this error pops up hundreds of times, what should I do? I tried reinstalling NGO as well
Not knowing at which step you struggle, I could recommend these two docs.
From the BR200 sample: Game Server Hosting and the Dedicated Servers doc for Fusion.
In doubt, please join the Photon Discord and ask there for more details on a specific step.
hi, im in the process of creating a multiplayer mobile game, and have gone through the Unity Dashboard for multiplayer hosting and set up a matchmaker for it, but im not sure I set everything up correctly. I have 2 phones im testing it out on and have installed the apk file on both, I was able to create a session to host on one and used the created code to join on the other, and the visuals are there but I cant move either player at all. Also the analytics don't show anyone being in the server, they just say theyre available. Ive created fleets and all that and just followed the process the Unity site laid out for me. Any suggestions ?
ooh update: so i closed the game on the hosting phone, and the player (players? cant confirm since I cant move them and theyre overlapping atm), they despawned. So its just the background.
I would update to the latest version of NGO. 1.9.1 is very old at this point. even if you're not on Unity 6 you can upgrade to 1.12
Matchmaking doesn't use join codes. Do your players move when run in the editor?
It still gives me the same error, can it be because I setup lobby wrong?
Yes the movement works in the editor and even on mobile with the Unity Remote app. As for the join codes, I used sessions to match up players for now, although would I have to change up from sessions to something else for the built in matchmaking to work ?
the networking topo is client hosted btw
https://docs.unity.com/ugs/en-us/manual/matchmaker/manual/get-started
I was reading this but i think this is server hosted ?
not sure if theres a different approach with client hosted
Maybe. I've moved to using the new Sessions SDK that handles Lobbies for you
You can setup your matchmaking queues to match into p2p. Session matchmaking works fine for client hosts.
I don't know why your players don't move on device
Im a little confused by the difference in Sessions and Matchmaking then. Is there a difference? I want to be able for players to "quick match" join, and also being able to create individual matches. Would Matchmaking be for the quick play and Sessions for individual matches ?
Also, yea I just checked and the matchmaking > queue > pool is set up alrdy to client to client
Sessions can use matchmaking withRelayNetwork()
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session#Find_a_session_using_Unity_Matchmaker_service
hey, does anyone know any good tutorials for unity 6 multiplayer w/ netcode?
ones that explain it very well and are relatively recent?
nvm i'll go with codemonkey's network for entities
thankyou so much i fount the b200 sample and its perfect for what im doing. Thankyou
Make sure your VR Rig is not being spawned as a player. There should only be one camera in the scene.
Check out the VR Multiplayer Template
@misty tendon !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
So synchronizing a rigidbody based playermovement system is horrible as I've understood it..
Created a quick test and the host can move it, and it gets synced to clients instantly, but clients are not allowed to move their rigidbodies, which is quite annoying. Can I just change some small thing to allow clients to do this?
The player has the rigidbody in question as a child of themself. It moves and syncs if the host does it, whilst the client is not allowed to move it by adding force. Is this because the ownership is not setup right?
Synchronizing the movement and interactions of two rigidbodies, owned by two different players seems awful as well haha
Network Rigidbody sets non owners rigidbody to be kinematic. If you set the network transform to owner auth then the owning player should be able to add force on themselves
Yup, that was the issue. Sorry for even posting the question before testing my theory.
For anyone wondering, this solved it:
[ServerRpc]
private void SetParentAndOwnerShipServerRpc(NetworkObjectReference propReference, ulong clientID)
{
if (propReference.TryGet(out NetworkObject prop, NetworkManager))
{
prop.TrySetParent(NetworkObject, true);
}
prop.GetComponent<NetworkObject>().ChangeOwnership(clientID); // Give ownership to the player
}
This sets the networkobject as a child of the transform (needed for my game) and then changes ownership
soo just an open question if anyone's willing to answer, how come the Create Sessions.cs script that im assuming comes from some multiplayer package in the package manager is using old input system code if in Unity 6 forward it seems theyre trying to have the "new" input system be the default ?
public override void OnServicesInitialized()
{
m_InputField.onEndEdit.AddListener(value =>
{
if (Input.GetKeyDown(KeyCode.Return) && !string.IsNullOrEmpty(value))
{
EnterSession();
}
});
m_InputField.onValueChanged.AddListener(value =>
{
m_EnterSessionButton.interactable = !string.IsNullOrEmpty(value) && Session == null;
});
}
Im basically doing a double whammy with both mobile and a networked game and running into issues in the backend from some of these things
atm running into an issue where the keyboard doesnt open when I switch to the old input system if I wanna type something in the APK build but the networking stuff is using that old input system but if I stick to both in the player settings' input handling then it talks about potential performance issues and possible lack of input. Just been circling around basically
i think you need to check which package haha
i've never used that package but it looks like it's meant for testing only, if it's not intended to be production ready code i imagine upgrading it is a low priority if it works fine with the old system
quick question, do I need to rewrite all my lobby code or can I just remove the lobby package entirely?
Change any usage of Lobbies.Instance to LobbyService.Instance is the only step besides switching packages, basically
thank you!
why do u say it looks like its meant for testing only ?
Says so in the description of the package
well snap, I missed that in this sessions link : https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-your-first-session
So if it's for testing purposes, is that supposed to only work on the editor? It makes sense that the keyboard doesnt pop up with the build on my phone.
So currently to my understanding, Id have to use these code snippets the docs provide to manually create a menu myself instead of the one that the widgets one provides ? : https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session#Find_a_session_using_Unity_Matchmaker_service
is that supposed to only work on the editor?
I would assume so. They kind of released it inline with Sessions and MPPM, advertising how quickly you can get a basic multiplayer setup going and test it.
The specific docs link you sent is for pairing Sessions with the Matchmaking service. The only two sections you really need to worry about to start are Create a session and Join a session
hi, i have the code
private async void CreateRelay()
{
await RelayService.Instance.CreateAllocationAsync(3);
}
which spits out the error: error CS0433: The type 'RelayService' exists in both 'Unity.Services.Multiplayer, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Unity.Services.Relay, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
can anyone please tell me what this means and how i may be able to fix this?
V: Unity 6 (6.000.0.32f1)
Visual studio 2019 (if it's important)
I added csharp Using Unity.Services.Relay at the top too and it still throws the error.
Any advice?
Thanks in advance.
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/migration-path#Migrate_from_Relay
Follow these steps. Looks like you have the standalone Relay package and the new Multiplayer Services package both installed.
Don't think I've ever seen that. Would just try restarting.
I just started with setting up the Unity matchmaking and using the Unity cloud server stuff, so I was wondering how that widget just automatically "networked" it. But it looks like its not, you have to manually use these "StartSessionAsHost()" and "CreateOrJoinSessionAsync()" and set up a menu and network it urself. thank you! This makes a lot more sense, i was curious how I was gonna get to editing that widget menu but I guess I gotta make it myself!
thanks!
Widgets are great for rapid prototyping and they will work outside the editor, but they are not customizable out of the box just yet. The devs have said it's something they are looking into though,
I have a networked propertie in Photon Fusion 2, even minutes after spawned still display "Networked properties can only be accessed when Spawned() has been called." This is called inside the public override void Spawned() method also! WEIRD!!!
hello all, i have come with yet another query,
is there a way to get all the users in one relay lobby and put them all into a different scene at the same time?
thank you,
Nate
nvm i think i know how
If you are using NGO, then the Relay Host is the one that has to call NetworkManager.SceneManager.LoadScene() and the other clients will automatically sync
thanks!!
Does anyone know why I need to set the compiler flag UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT to work with native lists for serialization? Like, whats the logic for not including it in the base netcode? Is there some downside (Aside from possibly crashing your game if you use them wrong) for enabling this flag?
Explained here:
NGO v1.9.1 Unity 2022.3.22f1 as release blog says, NetworkVariable now includes built-in support for NativeHashMap by #2813 , but how to use it? Here is my NetworkBehaviour code: public class Netwo...
Ah, for dependencies. That makes sense
And for clarity, the restriction of no nested native containers applies even if the containers are wrapped in another class? For example, I have a 'Geometry' object that has a native list / array of network serializable coordinates. If I was to put these Geometry objects into a native list/array, say a GeometryCollection, it would kill the netcode serializer right?
Anyone who can help me adjust my FishNet settings for my game? It's a semi-fast paced top down 2d rpg
I've just added basic movement, copying most of the prediction docs they have.
It works really smooth on the client itself, but looks jumpy when watching from another client.
So far the only way I've been able to fix it is setting my tick rate to 128, but I'd prefer to keep it at 64.
It's not extremely jumpy, but noticable.
Here's my full movement code:
https://paste.mod.gg/lkwzdvgcextp/0
I've tried adjusting all the settings mentioned in the docs, but nothing completely fixes it.
Prediction Manager: State Interpolation, tried everything from 1-5, both inserted and appended.
Time Manager: Tick Rate: 64 - Allow Tick Dropping is on - Update Order: before tick
Player Network Object: Enable Prediction is on, type Rigidbody 2D, enable state forwarding is on, graphical object, tried to add/remove it and change all the settings, but it's always better without a graphics object set.
you guys recommend learning mirror for learning multiplayer
depends on the type of game you're making, but I've heard all the major tools (like mirror) are good
allright because i have been doing some reseasrch on what networking solution to use but i really cant figure it out
hehe yeah same, I went with fishnet, it has some ok-ish beginner tutorials and pretty easy to use
but again, it really depends on what type of game you want to make
allright thanks maybe i will also look into fishnet
get the pro version from their github, it's only $10
I would recommend Netcode for Gameobjects, but Mirror, Fishnet, and Photon are all fine options.
Photon has literally 0 documentation
The docs seem quite decent https://doc.photonengine.com/fusion/current/fusion-intro
I tried the Quantum tutorial, it had several parts missing or just plain wrong, making it very hard to complete and after that you're just left in the dark.
Maybe if you're a senior dev with tons of experience in multiplayer those docs are sufficient.
But for someone coming here asking what engine to use, it's horrible, at least that was my experience with Quantum.
Their business plan literally seems not providing tutorials/documentation and then sell support packs
I can imagine Quantum docs being a bit more rough at some point considering the complexity of the product. I haven't used Quantum, so hard to comment.
They look pretty solid and standard to me. To me anything that's additional to an API Reference web page is above and beyond. They hit the mark in that regard, even for Quantum, which as you said is new and complex relative to other popular solutions.
Hi! I was just wondering, are there any significant disadvantages using a velocity setting movement system for networking? I was wondering if I should be swapping to a different style of movement such as AddForce and I was wondering if certain ones were more suitable and easier to work with when it comes to networking.
Even outside of networking, it's generally recommended to use AddForce instead of setting velocity directly.
Gotcha tyty ^^
In terms of networking, most of the popular Unity solutions and their components disable physics components for non-authorities/owners. So the authority does the physics simulation, and the resulting position change is just synced to everyone else.
That may be different for certain solutions, especially with more complex systems.
Ahhh I see, so I would want to disable the rigidbodies, etc. on the connected client side and then just have an rpc sync up the objects' position rather than having it relay the force to add on the client side?
Right. Unity's out of box physics is non-deterministic, if everyone is running their own simulation it may end of being slightly different for everyone.
I believe NGO just sets non-authoritative instances of Rigidbody to Kinematic.
Gotcha gotcha, using FishNet so I shall see what their equivalent would be. Thank you so much for the help ^^
there is no such thing as "when it comes to networking", networking is a huge subject, many different systems and architectures
networked physics is not easy, especially when using a broken networking solution
I'm using client side prediction for my player movement.
Should I also use it for player attacks?
It would feel really bad if you didnt
Hello here's my portfolio for game design. I would really appreciate any feed back: https://lenardclarke22.wixsite.com/portfolio
how do I connect the Unity multiplayer hosting and relaying services into my project? I was using sessions before but was told it was for testing purposes only and doesnt actually connect anything but im not sure how to set that up. I starting looking through this: https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo
It did mention about linking the project in the unity editor to the actual server stuff I set up on the unity cloud site but is this done automatically? I dont need to add the specific server IPs or IDs that were made ?
Sessions is not for testing purposes only.
All you have to do for Relay really is activate it on your Unity Dashboard, make sure the project is linked in editor and then follow the sample code in that link.
If you're using Multiplay Hosting, you would not use Relay. You would use one or the other.
oops meant widgets. Whats the difference between the two ? Relay is for client hosting vs multiplay would be for server hosting ?
Unity Relay exposes a way for game developers to securely offer increased connectivity between players by using a join code style workflow without needing to invest in a third-party solution, maintain dedicated game servers (DGS), or worry about the network complexities of a peer-to-peer game. Instead of using DGS, the Relay service provides connectivity through a universal Relay server acting as a proxy.
Multiplay Hosting would be dedicated game servers.
Widgets are just prebuilt UI. Sessions are perfectly fine to use in production.
There are some scenarios where might want to use Relay with Multiplay Servers like if your client is webgl
[Multiplayer] Is there a "Relevancy" system in Unity like in Unreal Engine ?
Coming from Unreal, is there any equivalent to the "Relevancy" setting where synced data is sent only to relevant players (a.k.a players being close to the object having that data being updated to not spend bandwith for players that aren't close to where the change happened) ? Or does it send the synced data to everyone everyone it changes even if the players are far away (aren't relevant) ? 🤔
Please ping me if any answer 🙂
You could mimic that using Object Visibility.
Netcode for Entities has Relevancy and Importance systems
https://docs.unity3d.com/Packages/com.unity.netcode@1.5/manual/optimizations.html#relevancy
what's the difference between NGO and NGE ?
But sometimes you can have objects being far away still being visible but have the lowest quality of LOD so it shouldn't really still replicate, so why did they choose the visibility as the argument to handle that part instead of the relevancy depending on a relevancy distance setting that each replicated object should have ? 🤔
Netcode for Entities uses the DOTS stack and not the usual gameobject workflows
Because NGO is designed for small scale co-op games.
Thanks 🙂
Oh ok, thanks 🙂
I found this tut from the unity docs for setting up lobbies but im getting an error on some lines regarding lobbies. I tried installing the package (which is deprecated ?)
var lobby = await Lobbies.Instance.QuickJoinLobbyAsync();
Doesnt recognize Lobbies.instance , And its sprinkled throughout the script
oh yea doc link: https://docs.unity.com/ugs/manual/relay/manual/introduction
is there some sort of migration with using Unity6 and the new multiplayer packages in the package manager
I have another question :
[Multiplayer] Can we not mix server and client code in the same script (NGO) ?
I keep seeing most of the tutorials mix server and client stuff in the same script, is it possible to put client stuff together in a script and server stuff together in another script for organization purposes ?
Because I find it hard sometimes to know where the code is executed when mixing both client and server stuff in the same script 😄
If you're using the Lobbies package directly, you use Lobbies.Instance.
If you're using Lobbies through the Multiplayer Services package, you use LobbyService.Instance
You'll want to use Multiplayer Services SDK
ppreciate it
You can do that. The Dedicated Server Package will help you strip components from server/client builds
Awesome thank you 🙂 Wait I'm a beginner at multiplayer, so what does that mean for the second part of your answer ? 🤔
You can mark components and object as client or server only
https://docs.unity3d.com/Packages/com.unity.dedicated-server@1.4/manual/content-selection.html
Is that equivalent to Ownership or is it something else ? Because I still struggle to understand ownership in multiplayer 😬
No ownership is during runtime. This strips out things during the build
oh I see
I have another question :
What does it mean to own an object ?
All spawned network objects have an owner. Owners can have permission to write to Network Variables and call RPCs on those objects.
Like how could owners be different than the server itself ? Because only server should write on those objects otherwise cheating would be possible 🤔
You can create your game to be client authoritative if you want.
But each object can only have one owner. either a single client or the server
but that wouldn't make sense to do that isn't it ? As it's prone to cheating if I do that
co op games don't care about cheating
true, but are there real cases where there's no way around than giving the ownership to someone else than the server ?
You can make it 100% server-authoritative if you want. You'll just have to mitigate the lag
But that doesn't answer my question 😛
Not really. It's a design/architecture choice.
the answer is no
@tame slate @sharp axle Thank you 🙂
I know I'm doing something dumb here... But why isn't this changing the text for everyone and is only doing it for the peron who makes the call?
[Rpc(SendTo.Everyone)]
public void SendYesVoteRpc()
{
yesVotes++;
// Update text
mainNavUiYesText.text = "<u>Y</u>es - {" + yesVotes + "}";
miniNavUiYesText.text = "<u>Y</u>es - {" + yesVotes + "}";
}
The text elements are assigned in the playerp prefab's inspector and spawned in at the start
The method is part of a local method that is called off a button press (code of which I can provide if you'd like)
Are you grabbing a reference to the UI in OnNetworkSpawn? Scene object references will get lost on spawn
The UI is actually connected to each player. With it being referenced in the inspector, I'd assume it always references its local UI
Is this a world space UI? Having multiple cameras and canvases might mess things up.
Nope it's a Screen Space - Overlay UI
I figured out that I needed to find a way to grab the local instance of my player UI and call that not from itself. I don't fully understand it, but it works 😄
Looking into adding sound fx to my net code for game objects game. Can't find many tutorials out there, only tutorials for single player games. for multiplayer would I take a similar approach to a single player game, but make the audio manager live in the player prefabs?
she's alive!!!
There's not much extra consideration in terms of Sound and Multiplayer. You've likely already done all the work needed by syncing position, animation and other types of events/actions. Your SFX should just piggyback off of those things.
I guess my main question then would be should my sound manager live in the scene, or in the player game object?
also maybe I am over complicating it in my head lol
That's up to you and is completely a design choice IMO. The right answer is to go with whatever you find easiest to manage.
I personally like to have a single audio manager object/script and have it subscribe to events throughout my game to know when to play certain sounds.
you would still need clientrpc and serverrpc method for that solution right?
That goes back to my first reply. You may need extra networking communication depending on what exactly the sound is. But generally speaking, what is already networked can just be used to play SFX at the appropriate time.
Examples:
- NetworkAnimator that's on another players object syncs their footsteps for me, and I can use that already synced information to play a footstep sound.
- A NetworkVariable boolean that tells me whether or not a door is opened or closed. I can play the door SFX inside of that NetworkVariables OnValueChanged
- An RPC that plays a particle effect for smoke coming out of a gun that just shot can double as a spot that I can play a gunshot sound.
Thats good info, I will continue looking into my options. Thank you!
I have a bit of an odd one. I have a tool that lets players create objects in the multiplayer scene. Part of this is I have a network variable that stores the recipe for each object, as they're pretty dynamic. I want to allow the users to set the model that the object will have. I already have all the models loaded into the projects addressable system. Do you think it would be efficient to build some direct serialization of AssetReference? Or should I just have a lookup table that maps a primative uuid to the asset?
Ah, looking closer, Ill have to do the lookup table. For some reason I though AssetReference was a GUID of some kind, rather than a raw string
Hi there guys! I've recently been working with Netcode for GameObjects using the Steamworks package via the facepunch transport system. I've set everything up now and I have working connection between two different steam accounts that can join the same game. However now that I have the basics done, I need to check things like a friends list of lobbies for example. I've run into an issue where I can't actually check if one of my friends is currently in a lobby and then get the lobby data. Instead the only workaround I've seen is to request every single lobby and then check each lobby to see if any contain my steam friends.
That solution cannot possibly be sustainable or the best way to handle such a thing. Is there any way to check my friends list directly for if they have a lobby and subsequently retrieve the lobby data?
Update: Found out I can use SetRichPresence and GetRichPresence to store data when I create lobbies - this has solved my issue!
when instantiating a prefab such as a bullet projectile, is there a way to get the object that instantiated? Im spawning from a script attached to the player prefab that gets instantiated so I can have the projectile spawn in from that player's transform.position:
public void Fireball()
{
GameObject spawnedFireball = Instantiate(fireballPrebab);
spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
}
I would send the player object transform in Fireball()
smort
sooo i might have done it wrong but I updated the button that calls the Fireball() to:
public void Fireball()
{
GameObject spawnedFireball = Instantiate(fireballPrebab);
spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
spawnedFireball.GetComponent<SpellbookScript>().SetSpawnPoint(transform.position);
}
And have SetSpawnPoint on a script on the prefab that initializes that provided transform.position from the player and set it on start() (I also tried OnNetworkSpawn() since the start() didnt work):
void Start()
{
transform.position = finalPosition;
}
public override void OnNetworkSpawn()
{
transform.position = finalPosition;
}
// Update is called once per frame
void Update()
{
transform.position += transform.up;
}
public void SetSpawnPoint(Vector3 pos)
{
finalPosition = pos;
}
But the projectile is still spawning from the center of the screen instead of where the player was every time
I'm assuming Fireball() is getting called on the server. Is this on the player object?
It is on the player object, although this is p2p, I don't actually have like a server class
Movement itself has been working fine without something like that so I assumed i could keep working building the "client script(s)" until I ran into a snag... which would this be it? Lol
anyways I think its because of the order of when it spawns that it didnt read the transform.position of the player correctly so i edited the instantiate() with that player position but it still going to 0,0,0:
GameObject spawnedFireball = Instantiate(fireballPrebab, transform.position, Quaternion.identity);
One of the clients (the host) still acts as the server. Object spawning is a server only capability.
well the spawning works for projectile prefab, just not the position. It doesnt spawn from the player, it spawns at 0, 0, 0
The host has to instantiate it in the correct position. By default everything gets instantiated at the origin.
You should have the clients send an RPC to the host in order to cast the fireball
Clients can't spawn anything only instantiate
🫡
You can try using InstantiateAndSpawn, you might find it easier/cleaner for instantiating, spawning and setting position
Just make sure that only the host/server is calling it
about that... since its p2p thats confusing me. How do I seperate these restrictions from clients and hosts if its all run on the same project ? Im assuming if I dont restrict to only the host/server it will spawn multiple prefabs? Or a prefab per client even though only one client pressed the fire button ?
im assuming this still has to be an RPC right ? Also, for some reason VSC doesnt recognize InstantiateAndSpawn() but i have using netcode namespace so not sure what thats about
[RPC(SendTo.Server)] will only ever run on the server/host. You can also call if(IsServer) to check if you are calling a function from an event or something
i see. Project structure wise though, would having a dedicated script "acting as a server", such as keeping track of player stats like health, to simulate some sort of server authority, be the best / usual approach then ?
for p2p
cuz I see a lot of tutorials having like a game manager script and object itself on projects that arent networked. So having this game manager act as a server almost
It can be done, but I find that to be more trouble than its actually worth. I do most things through Network Variables with Server write permissions and RPCs for commands from the clients
hello im using fishnet and relay system for p2p hosting however it lets me host the server but when i go on my other game build and type the code it wont let me in.
I have an in scene placed network object and I am using the NetworkObject.Despawn() method on server to destroy it. This object also gets destroyed on connected clients but if a client joins the game after the despawn call, the object still appears in the scene. This is what unity netcode should have handled itself
Unless IsSpawned is true on that NetworkObject, they've handled about all they can.
All you would have to do is disable the visuals of the object in the inspector, and reenable them in OnNetworkSpawn of the object.
You could also just spawn this object at runtime as well.
Thanks for the info! I appreciate the help
Hi, I'm in process developing backend for my chess game, currently I have client part where game is board of tiles and lists of balck and white pieces. Should I simulate the game on the sever each time new game started or just store last position? The simulation will allow to validate moves but it can take more of server performance and maybe I will need to refactor my game logic to make it run without visual part (visual part is to heavy for server if many games will be played same time).
Check out the cloud code chess sample
@sharp axle thank you I think they use fen notation to store position on server, I was thinking about this option too. I'm try to use low level but this example contain a good example of net messages(Requests/Responds).
Hello, what is the best network solution for a fast game racing top-down ?
Photon Fusion 2 Shared mode is not fit for that (cf video)
Does the official Unity networking system allow this to be done at best ? or Mirror is fit for that ? or Photon Quantum ? or another ?
i need to be sure this time, i just lost one month of full development to try to make this game in Shared mode (it was advice to me...)
They all work equally well. There is no ‘best’ framework. All require you to do lots of work yourself.
Did you check if Fusion kart samples have a solution for this?
You need to identify what you need out of the networking solution to make an educated decision. Doing the same thing in different networking frameworks is unlikely to solve your problem.
Do you know a fast racing game made with all solutions or you just say something randomly ?
Yes , all the samples, and Tanknarok Fusion 2 have the same issues :
Yes and its why im here for ask that, what i identify is what i mentionned and showed in the video : fast movements and collisions need to be the "same" (as close as possible) for all players
Even the racing sample?
That is the goal, sure, but you need to figure out why this is happening and what changes need to happen to achieve that goal.
I don't know what is already going under the hood with these samples, but I imagine you can do better with more aggressive prediction and/or input lag on the client
I gonna try to change the view to top down for to be sure and i comeback to you for show you the synchronization difference between two players
This is my point in the sense that for me a solution must precisely propose this kind of settings by itself to respond to this kind of problem.
I mean that they are made for non "network gurus", who do not necessarily have this kind of skill otherwise they would not call on their services but would have created their own network system
But I note that, in this case "Photon 2 Shared Mode" has nothing like that
I dare to hope that Quantum or other (hence my initial question) has this kind of "dev friendly" features
We can imporve the setting to a maximum of the paradigm we use, for now i need to know which is the best paradigm
I think to kind of summarize the advice you’ve been given thus far:
Any of the handful of commonly used networking solutions are capable of running the game you’re describing. It more so falls on the advanced topics that you have to implement to create the game you’re describing. Switching networking solutions isn’t just going to flip a switch and solve your issue.
Of course some solutions offer things like client-side prediction out of the box, but even with those solutions you’re still going to have to do the heavy lifting to implement what is needed specifically for your game.
I understand every solution are not ready to use, there are need to be setting specificly for the respective project, but somes are more fit for somes project.
Seriously you think a game like Rocket League ( fast movement and collisions and very fast ball movments and collisions) could be are made in every solution ?
I think your answers are tot generic and you had not really works on this problematics, seems more like you would like less more facts/concrets
Im seriously curious if you have an exemple of a fast racing game made with PUN 2, Fusion 2 Shared or Host mode , or anything else Quantum or Dedicated server
Its ok but i think its the work to this service to have enough documentation/sample/tutorial for we can fix/set it
But they dont
Seriously you think a game like Rocket League ( fast movement and collisions and very fast ball movments and collisions) could be are made in every solution ?
I think you could make it with a wide variety of solutions. And even with the ones you couldn't, you could make something very close.
But I don't really want to go down that rabbit hole. I'd rather try and answer your original question.
I think Fusion is a suitable choice for your game, but you'd want to be using dedicated servers. Not Client-Host or Shared Mode.
So I guess that's more my point, it's really more about the Network Topology in the solution that you choose, rather than the solution itself.
You can see here that Shared is not really what you'd want to choose for your game.
So I think Fusion (Dedicated Servers) and Quantum are both suitable options. However, I saw you mentioned wanting things to be "dev friendly" and I wouldn't say Quantum really fits that bill.
I understand how netcode works and that all libraries do effectively the same (dealing with exactly the same limitations and having the same set of solutions available) so there is no reason to assume any would be better over another. But I suppose you are asking whether one of those frameworks includes a readymade solution for exactly your game. That I don’t know but would guess, none does. Maybe one has a similar example or a bit of code that saves you a week of DIY. Regardless, if you understand anything about netcode it is that the library doesn’t matter once the fundamentals are in order. Which they are in all frameworks you mentioned. The genre of the game is largely irrelevant.
Thank you , i think Dedicated Server seems more complicated than Quantum but not sure, i gonna restart my project on Quantum, that seems the better solution for what i need
Just a fair warning - Quantum requires you to use their physics system, as Unity's built in physics is not deterministic. There's also not much in terms of resources for it outside of their own samples/documentation.
Dedicated Server is still Fusion, so it would be very similar to what you've been doing - just some differences in ownership and a pivot to server authoritative movement would be required changing from Shared Mode.
I think that these solutions can help any type of developer to implement a multiplayer system, so without having to be a network expert, it would be a shame if you had to be a network guru to use them, that wouldn't be many people
Even if obviously you have to scale your skills on this subject to best adjust your project in terms of synchronization
Yes i started to look the tutorial https://www.youtube.com/watch?v=uRKrryg-fVU&list=PLyDa4NP_nvPdMnNr34LjHL_6D3KyXxGTR&index=20&t=967s , i will look the entire series and judge after that
But yes the documentation/support are very poor.. :/
Download complete Unity project 👉 https://www.patreon.com/posts/tutorial-photon-94186666
📍 Support us on Patreon and help us make more videos like this one ⏩ https://www.patreon.com/prettyflygames
This is a new tutorial series were we will cover Photon Quantum 2 which is used by Stumble Guys, Battlelands Royale, LEGO Brawls, LEGO Star Wars Ba...
But its not more expensive ?
Oh, it will be for sure. But that's kind of a reality with the type of game you're wanting to make.
following issue
i made a custom service called SessionService which has 2 methods JoinGame and HostGame
the issue lies inside the HostGame method, where im trying to load a scene
im injecting this service later into a monobehaviour and calling the StartHost method but it logs a not set to an instance of an object error at the CustomManager.Instance line
does scene management just not work with dependency injection or does it lie on the actual networking part?
so the NetworkManager.Instance.SceneManager is null, no matter where i call it from
Network Manager Scene Manager should only be called after the Host has connected not before
oh, wow, thanks, i didnt pay attention to the order of execution
the bit that is "optional" when it comes to understanding is solved by all libraries, anything on top of that is, in most cases, not generalizable and expecting a framework to enable a non-expert to make a (release worthy) multiplayer game is a fantasy. There are many frameworks that promise to "abstract" networking away from the game-dev-team an just give you options to "toggle which parameters to sync" in some inspector... all of those eventually break down and you have a crappy system that half uses the library and half uses some awkward shims the team made themselves to solve problems that the "neat architecture of the library" couldn't solve (surprise).
How does this actually work cant other players just decompile the code and remove the isMine part?
If players hack the client then all bets are off. Only a dedicated server can potentially validate client inputs. Cheat/Anti Cheat is an entire industry.
hi chat
this is not true at all, plus your other statement about all networking solutions being equally capable of doing the same things
it looks like you haven't touched any of the new libs in the last 6 years
photon fusion/quantum can easily enable average devs to make games with networked physics and whatnot easily without having solid networking knowledge, which are considered the holy grail of multiplayer games
I've not run across any feature in one library that was impossible in any of the others. Photon might more built in features but those can be replicated elsewhere. I'm not saying it would be easy but it's doable.
Hi all, I'm running into some trouble hitting my server from local (using fishnet)
My error: Unable to lookup LocalConnection for 1 as host.
What I've tried:
Set up an ubuntu vps and ran a headless server. Seems to be running properly
Set up network manager with tugboat component (pointing to my server address)
Verified I can ping my server on the correct port with tcp and udp
I'm new to unity but it seems like my client address isn't configured correctly. Just not sure where to look
the number in the error also iterates each time I run eg. 1 as host, 2 as host...
edit: I had client and server addys mixed up lmao
hii trying to spawn a projectile on the scene and have a function set up to fire when a button is pressed which calls the RPC that spawns the object:
public void Fireball()
{
SpawnFireballRPC(finalPosition.x, finalPosition.y);
}
[Rpc(SendTo.Server)]
public void SpawnFireballRPC(float x, float y)
{
Debug.Log("Fire");
GameObject spawnedFireball = Instantiate(fireballPrebab, new Vector2(x, y), Quaternion.identity);
spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
}
Im getting a null exception tho on a networking script:
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.NetworkMetrics.GetObjectIdentifier (Unity.Netcode.NetworkObject networkObject) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Metrics/NetworkMetrics.cs:527)
I have the script inhereting from Networkbehaviour and the button has a network object attached to it since thats what code monkey said!
How to get mac address of the laptop using my software on windows? I know SystemInfo helps you achieve most of the related information but no clue about Mac address. Help me out if anyone can
i'll say what i said in the other room, after directing you here:
'although, that is usually not something you would need, so may be shyed away from telling you how. it sounds 'hackerish' '
so i suppose the first question is Why do you want the MAC address?
@alpine mauve ^
So basically I am using this approach instead of proper licensing. Fetching the device hash and adding that in my json file which will then allow that device to open my app. So i'll get information about the device trying to open my software without permission.
Do you want more clarity?
@rapid crater ^
It's okk if you can't help
and how would you intend to handle hardware changes?
no, i mean the users hash would change, if they changed any hardware in their machine.
Why do you need the mac address specifically?
SystemInfo.deviceUniqueIdentifier doesn't work?
I am a begginner, I was using deviceName, model and such basic things. I wasn't aware about this UniqueIdentifier. I was not aware that getting Mac is such a big thing, I'll refrain from doing so
Also just fyi
https://en.m.wikipedia.org/wiki/MAC_spoofing
MAC spoofing is a technique for changing a factory-assigned Media Access Control (MAC) address of a network interface on a networked device. The MAC address that is hard-coded on a network interface controller (NIC) cannot be changed. However, many drivers allow the MAC address to be changed. Additionally, there are tools which can make an opera...
Yo is it somehow possible to network serialize classes instead of structs?
like, this actually works
but his doesnt
everything else in the code is the same, but I need it to be a class to use inheritance and having unique hashes
I don't think so
damn 😔, thanks tho
You can send classes in RPCs but network variables are more strict
Hello, I'm not sure what I'm doing wrong. I have a simple netcode for entities with unity physics scene set up. And I am trying to spawn a number of simple prefab cubes into the scene. This prefab has both a Physics Body and a Physics Shape authoring component. I also set Physics World index to use 1(not the predicted world), However, when the netcode package is installed Unity Physics seems to either break, or I have not setup the packages correctly. Physics Body does not seem to be authored on the resulting entity, and the cubes are marked as static. Does anyone know why this is happening?
You might find it useful to add a GameObject property in a NetworkBehaviour-derived component to use when assigning a network prefab instance for dynamically spawning. You need to make sure to instantiate a new instance prior to spawning. If you attempt to just spawn the actual network prefab instance it can result in unexpected results.
https://docs-multiplayer.unity3d.com/netcode/current/basics/object-spawning/
What's this excerpt mean? Have an empty GO with a sole network object component be the parent with the prefab being a child of this GO ?
In Unity, you typically create a new game object using the Instantiate function. Creating a game object with Instantiate will only create that object on the local machine. Spawning in Netcode for GameObjects (Netcode) means to instantiate and/or spawn the object that is synchronized between all clients by the server.
If you use Rigidbody and a Collider on the prefab then it should convert as long as the prefab is in a sub scene. Netcoe for entities automatically moved the physics systems into Predicted Physics Systems, not sure if that will cause you issues or not
This just means that if you are spawning an prefab then you need to Instantiate() it first before calling .Spawn()
It converts the collider, but doesn't convert the rigidbody. I'm also spawning the entity on the server(and it shows the ghost entities in the server hierarchy), but they're not sent to the client either.
i see, im alrdy doing that then. I tried using an RPC to spawn my fireball like u suggested the other day but for some reason im getting a null exception (using a button to trigger the fireball() which then calls the rpc:
public void Fireball()
{
SpawnFireballRPC(finalPosition.x, finalPosition.y);
}
[Rpc(SendTo.Server)]
public void SpawnFireballRPC(float x, float y)
{
Debug.Log("Fire");
GameObject spawnedFireball = Instantiate(fireballPrebab, new Vector2(x, y), Quaternion.identity);
spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
}
the player prefab, projectile prefab, and even the UI button that just calls fireball() has a network object though
these functions are on the player's script
Question; Lets say two games are synced, to players in the scene. I as a player spawn a blue cube which is synced > the other player sees it. Now, as the other player lets say my game unlocks a new red ball and I spawn it > will the other player see it or will it be invisible? Does the red ball prefab need to be a object installed on the other clients game build?
The use case is the fact that I have TONS of DLC, which I dont want to be installed on all of the game builds, but such models and textures need to be seen by other players who dont have the DLC
The other clients have to have some sort of reference to the DLC or they don’t know what to display.
If there’s not reference built directly in to the game build, you would need to use Addressables. Those are just about your only two options.
So it’s better if all the dlc content is just hidden inside the game build? It’s like a 50gb difference lol
It's not "better". It's one of your only options. If it's 50GB worth of content, I would make it addressable.
I’ve done assetbundles but it required loading in stuff each time.
For addressable, does it require loading the downloaded content? Or is it more like a built into the game thing after it’s downloaded
Once you download something from addressables, it should be cached on the device so that next time you try to fetch it, it will pull it from the cache instead of downloading it.
Hello! When loading scenes in a networked game, is there any way to "grab" the loading progress and display it in a progress bar? I have not found any exposed values regarding the actual loading progress of the scene transition.
NetworkManager.Singleton.SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
When not using networked code, I could typically load scenes asynchronously using Unity’s SceneManager.LoadSceneAsync This returns an AsyncOperation object that provides a "real" progress value (between 0 and 0.9 during loading, and 1.0 when the scene has been fully loaded). I could use this value to update a real progress bar. However, I have not found any way of doing this using the Networked Scene Manager.
there's NetworkSceneManager.OnSceneEvent which you can listen to for scene updates, certain events will have a reference to the current async operation with a progress value iirc
The Load and Unload SceneEventType both have AsyncOperation
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events/#sceneevent-properties
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
private void interactCheck()
{
foreach(KeyValuePair<ulong, NetworkClient> clientInfo in NetworkManager.Singleton.ConnectedClients)
{
NetworkObject p = clientInfo.Value.PlayerObject;
if(Vector3.Distance(transform.position, p.transform.position) < interactionRange)
{
print("In range!");
if(Physics.Raycast(transform.position, (p.transform.position - transform.position), out RaycastHit hit, interactionRange))
{
if (hit.transform == p.transform)
{
print("hit a player");
p.GetComponent<Player>().showInteractionButton();
return;
}
}
}
p.GetComponent<Player>().hideInteractionButton();
}
}
im trying to check if another player is close enough to interact with another, how should i go about this? since connectedclients is apparently server only? im very new to this
I usually keep a list of player objects stored on each client so they can referenced when needed.
Some people do the same with the IDs and use the ID to get the player objects when needed - either works.
how would i do that when i cant check the connectedclients?
I use OnNetworkSpawn on my player object to add to the list
When a player spawns on the client in its OnNetworkSpawn() add it to a dictionary/list
and then i just make a gameobject playermanager in the scene which holds a list of the players?
Yeah. Some sort of manager object is what I use usually.
Yes. Awake will run before the object is spawned on the network.
You can see a timing chart here
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior/#spawning
so the gameobject gets spawned on the client, then awake calls, then it gets spawned on the network and then networkspawn calls
Roughly, yeah
Do you guys know if something changed from Unity version 6000.0.23 to 6000.0.38? The automatic scene migration isn't working for my clients that connect after a game has started. It previously brought them to the correct scene that the host was in, but now it doesn't.
The editor version wouldn't have changed anything with NGO. But nothing has changed recently with NGO versions either
private void interactCheck()
{
foreach (NetworkClient client in PlayerManager.playerClients)
{
NetworkObject p = client.PlayerObject;
//nullreferencerror next line
if(Vector3.Distance(transform.position, p.transform.position) < interactionRange)
{
if(Physics.Raycast(transform.position, (p.transform.position - transform.position), out RaycastHit hit, interactionRange))
{
if (hit.transform == p.transform)
{
p.GetComponent<Player>().showInteractionButton();
return;
}
}
}
p.GetComponent<Player>().hideInteractionButton();
}
}```
```cs
public class PlayerManager : MonoBehaviour
{
public static List<NetworkClient> playerClients = new List<NetworkClient>();
}
public override void OnNetworkSpawn()
{
PlayerManager.playerClients.Add(NetworkManager.Singleton.LocalClient);
print(PlayerManager.playerClients.ToString());
base.OnNetworkSpawn();
}
i now have this, but it gives a null error
for p.transform.position
I did a git revert to before the change to make sure I wasn't crazy, and it worked. Then when I reapplied my changes, it stopped working again. I can see from my logs that the player joins the lobby. They just aren't redirected back to the host's active scene. 🤔
I personally wouldn't store NetworkClient. If you have a script on your player object, I would store that.
aight
Then you can also expose that list to inspector to find your player objects easily when testing as well
i was bummed i couldnt see the list in inspector, but i can? ill look into that as well thanks for the help
This is the code I'm using for the button to start the game from the lobby.. Nothing wrong with this, correct? Also, I have "Enable Scene Management" checked in my network manager.
public void StartGame(UnityEditor.SceneAsset scene)
{
NetworkManager.Singleton.SceneManager.LoadScene(scene.name, UnityEngine.SceneManagement.LoadSceneMode.Single);
}
as long as only the host is calling this after StartHost() has been called it should be fine
I would open a Github issue on this then. a minor editor version update really shouldn't have any effect on Netcode
Yeah it's definitely after start host. The start host is on a "Host game" button and then they have to press "Ready" and then "Start Game". The start game is where the scene load is. I'm just confused how we upgraded our Unity version and it stops working, then when we revert it starts working again.
And like I said, it works for everyone on the initial load.. It's just when a client disconnects and reconnects that it has this issue.
hello chat, I have questions on how to structure combat in my game
(I want it to be peer to peer pretty much, don't care about hacking or nothing, I rather want it to feel responsive for the player)
so running everything locally as much as possible~
so I have 2 functions, one to apply damage and one to receive damage
I wanted to know if I should make them (and which)
[Rpc(SendTo.Everyone)] or [ServerRpc]
[ Thread to not flood this chat ]
what reads as false
oh but you're only setting that on the host
you could maybe put that on StartClient / JoinGame or whatever your function is
hope this helps, if not I hope someone comes in for help
void UpdatePing()
{
if (_networkManager.IsClient && _transport != null)
{
ulong serverId = NetworkManager.ServerClientId; // Get Server ID
_currentPing = (int)_transport.GetCurrentRtt(serverId); // Get RTT in milliseconds
_pingText.text = $"{_currentPing} ms";
_pingIcon.sprite = PingIcon(_currentPing);
}
else
{
_pingText.text = "N/A";
_pingIcon.sprite = PingIcon();
}
}```
is that the current ping? or should I split it in half (_currentPing/2)
RTT stands for Round-trip time
If that's what you wish to display, yeah - although the ping you usually see displayed in games is RTT
oh yeah? hmm
is that true? 🤔
in League, Counter Strike, GunZ I get like 20-50ms I would be surprised if that's RTT
and not (RTT / 2)
those times are likely to be RTT.
Multiplayer games operating over the internet have to manage adverse network factors that don't affect single-player or LAN-only multiplayer games, most notably network latency. Latency (also known as lag) is the delay between a user taking an action and seeing the expected result. When latency is too high, a game feels unresponsive and slow.
or do I really have 70ms with my friend that lives close to me 🤔
which is not much, that's like 2 frames or less
Those are all server authoritative games, where you send a request to the server (to shoot your gun in CS) and it sends a response back (to actually fire the bullet) making RTT the most relevant thing to display
would have to disagree with ChatGPT on this one lol
especially since I can get it to say the exact opposite of what you just sent 😛
🤔
well
whatever it is
void UpdatePing()
{
if (_networkManager.IsClient && _transport != null)
{
ulong serverId = NetworkManager.ServerClientId; // Get Server ID
_currentPing = (int)(_transport.GetCurrentRtt(serverId) / 2); // Get RTT in milliseconds
_pingText.text = $"{_currentPing} ms";
_pingIcon.sprite = PingIcon(_currentPing);
}
else
{
_pingText.text = "N/A";
_pingIcon.sprite = PingIcon();
}
}```
do you guys think it's bad if I put it in half?
It's not bad perse, I just don't think it's relevant.
Because if those games do display one-way latency, I would guess that number isn't calculated by taking RTT/2
I would use the Ping Tool
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/tree/develop-2.0.0/Examples/PingTool
nice wth
i probably already asked but forgor,
if i want to have a list with 2 ints (dictionary/keyvalue pair)
there is no networkdictionary or smth, right? (rpc's are problematic, if someone joins, the inventory of, for example a chest is not synced)
You can make a NetworkVariable<Dictionary<int,int>>
hmmm ok, and if i want to add a default value (set this one from another dictionary from start) i can't because unity cant't serialize dictionaries T-T (and the packages in the asset store don't actually do that, they create a new type)
You can set the default value when you initialize it. If you make changes after that you need to be sure to call .CheckDirtyState() on it after making any changes to the collection
So uuuh it wouldn't be great for inventory systems I guess?
Hi gang getting this error in n4e
[ClientWorld] RpcSystem received non-approval RPC Rpc[15394532049276111354, GoInGameRequestRPC] while in the Handshake connection state, from NetworkConnection[id0,v1]. Make sure you only send non-approval RPCs once the connection is approved. Disconnecting.
I was under the impression connection approval was an optional feature, which I have not knowingly enabled; is this not the case?
Also this only occurs when playing properly online to another pc
Multiplayer play mode is fine
Could work perfectly fine for an inventory system. However unless you have a specific reason for using a Dictionary, I would say a NetworkList<> or a NetworkVariable<List<>> makes more sense for an inventory.
I mean I need the itemid and the amount (so two values) I tried a network list but I can't store 648184 pieces of metal in it by filling the list with the equal amount of int entries lol
Use a struct
public struct InventoryItem
{
public int ItemId;
public int Amount;
}
Oh, so that does work with networklists? Ok I'll try that later
Sounds like the server is sending the GoInGameRequestRPC which is the wrong way around
For a NetworkList it would also need to implement INetworkSerializable, IEquatable<InventoryItem>
Kk!
hello chat
so I have a damage cube for testing
[ Script here ]
and I was wondering how I could make it sync between all players... actually nvm
I can just turn this into an rpc function I assume
would it be like this?
seems like it works, thx!
Triggers will also get called locally on the clients. If players are applying their own damage then there is no need for RPCs there
no i dont think so
there are 3 references to goingamerequestrpc in my entire solution
once in the declaration
once in the server simulation foreach
and once in the client simulation to send it
damage is applied on the server
took me some time to figure it out but
this is what I ended up for my apply damage and receive damage
[ Script here ]
that is for my players, now for entities and environment hazards
the server will calculate the damage
This is on my environmental damage test cube
public void ApplyDamage(IReceiveDamage hit, IBlock block = null, IParry parry = null)
{
if (!NetworkManager.Singleton.IsServer) return;
float damage = Random.Range(1f, 5f); // Monster attack power
bool wasBlocked = block != null && block.IsBlocking();
bool wasParried = parry != null && parry.IsParrying();
DamageData damageData = new()
{
DamageAmount = Random.Range(1f, 3f),
Knockback = 1f,
HitStun = 2f,
DamageSource = transform.position
};
// Send damage to all clients
hit.ReceiveDamageRpc(damageData, wasBlocked, wasParried);
}```
Might want to triple check you world filters. For whatever reason your client world is also receiving that RPC
yeah i tried running again and im getting the same error but says server world
not sure wtf happened tbh
but i get that error on the host
and this error on the client trying to connect
[ClientWorld] RpcSystem failed to deserialize RPC 'Rpc[10468798105839974107, Unity.NetCode.ServerRequestApprovalAfterHandshake]', as bits read (0 [0B] did not match expected (136 [17B])! Be aware that the incorrectly deserialized RPC may have still executed, but this connection will soon be closed.
Looking at the scripting api i can find no Unity.NetCode.ServerRequestApprovalAfterHandshake idk dafuq is happening and idk how to find out
Hi all - asking a probably very common question but is mirror or photon best for my project? (multiplayer online card game) Does it matter? If not I'd probably go with Mirror but just wanted to get the feb 2025 opinion from ppl (or if theres a better 3rd option pls let me know)
mirror is fine
or unity gaming services
better pricing and no need for Photon features,
except you could get practice using photon if you wanna make other games that could be better with it
TL:DR; Mirror imo is better for that project
I used Unity's Gaming Services to make mine, and felt super comfortable with good results
Any of the handful of popular solutions will be able to make a card game easily.
If you're serious about being able to scale your game cheaply and efficiently, consider not even using one of the popular Unity networking solutions and just use a backend service like Unity Cloud Code.
What's everyone's thoughts on supporting optimistic updates in a mobile game?
I think in web dev it's the norm, but all the mobile games I've tried out doesn't seem to utilize optimistic updates (e.g. Archero and Pokemon Go) -- for things like equipping items, leveling up items, consuming items, I see there's always a slight delay which indicates it waits for the server response and not doing any optimistic update.
I don't know if the added complexity/work of having to keep server logic and client optimistic logic in sync is worth it, and it also sort of removes the possibility of doing quick backend adjustments to logic, as the client will also need to be updated to change the optimistic update logic accordingly.
Is it common practice/industry standard for mobile games? I feel it isn't as I haven't seen many mobile games before that have optimistic updates.
(Talking about like "main menu" interactions, such as inventory management, etc, not real-time gameplay.)
This sounds kinda like client prediction. It doesn't really seem worth it for menu items that have to be validated by the server in any case. But for your game it might well be worth implementing.
I think client prediction is another term (but more-so I think for real-time context). Optimistic updates are common in web dev, for example pressing "like button", immediately shows the button is liked and the like count is increased, before the server actually processes the request.
When optimistic updates fail, it will cause a rubber-band or roll-back effect, for example "like button" will revert to the state before you tried to like it.
Or if the backend logic and client prediction logic is not correctly aligned, it will cause a brief strange effect since the client expects something different then what the server does in the end.
I'm wondering if it's popular at all for games. I haven't played many mobile games, but from what I can tell, majority of them don't do optimistic updates. (again talking about UI/menu interactions and not real-time gameplay).
Hey guys, I'm having a little issue with Relay Services when using Unity Netcode for Entities. I've thrown together a small demo where I'm attempting to connect 4+ players to the same relay. I start the lobby, populate say 4 players, then set one client as the host and join the relay, then all other clients connect to the relay using the relay join code. All is well, it works great with 2 or 3 players ... but when I use 4 or more, the 4th client and any other client beyond that, fail to connect and I receive a Relay Allocation not found error. It works fine, the other two clients connect to the host, but the fourth onwards do not ... is this a limitation in Unity Relay or can anyone shed any light on why this might be happening?
Here's the output from the 4th client, the other 3 are working fine, no errors (host, client 1, client2) ... client 3 (4th player), gets this message. All other players beyond player 3 get this message too if they try to connect. The relay and lobby are both set to 4 players in this example.
TIA for your help.
What did you set the max connections to? And have you tried using the Multiplayer Services SDK?
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-with-netcode-for-entities
what do people use for servers usually with unity is it aws?
Ok thanks appreciate it, I will be using AWS to host - I noticed they have a product called Gamelift - do you know if Mirror / others are perfectly compatible with Amazon Gamelift?
I am making a multiplayer game and i would like to use both a model for client side (for example just arms and legs) and a server side what other players will see so (the full body) what would be best way to tackle this just make two gameobjects under the player and make one visible for server and one for client or is there another way?
yep that's pretty much it
allright so actually nothing to complicated?
easier way to think of it is having a togglable first person / third person view. It's exactly the same
yes allright thanks
Hello
You can use any cloud vps service. DigitalOcean has some of the cheaper options depending on your game
Can i just delete the component from the game object if it isnt the owner instead of adding !IsHost on the code?
network objects needs to have the same components on client and server usually
if you're on NGO, iirc the index of the component within the gameobject is part of how it identifies which component an RPC is sent to, so if you remove one that won't match
Disabling should be fine
Ok thank you
İt gives 400 bad request error when joining lobbies?
Figured it out, turns out I was erroneously setting the allocation size for the relay to 3 instead of passing my global NUM_PLAYERS_FOR_START_GAME. Thanks for your response ❤️
I personally use Azure Playfab. There's a cool little package in Unity called CBS Cross-Platform Backend System which has a pretty comprehensive RPG example attached to it which uses Azure Playfab and Azure Functions to offer things like battle pass, inventory management, prize systems, authentication, cloud data and so much more ..... it's abcsolutely awesome. Even if you dont use the whole system, it's completely modular so take the parts you want, and negate those you dont.
This is exactly how you'd do it. Just reference them and run a client/server check and disable the parts you dont want to see.
All my UI acts this way in my Multiplayer projects. 9 times out of 10 you never need to rollback, because I design it in a way that the client should know already if it's actionable, then I allow it, and if for whatever reason there's a sync issue and it isn't allowed, the server will revert back to the correct state.
Hi there, new to unity and trying to make 3d card game but for some reason trySetParent doesn't work and card instantiates in main scene rather than in hand anchor:
[SerializeField] GameObject cardPrefab;
[SerializeField] Transform handAnchor;
[ServerRpc]
void DrawCardServerRpc()
{
if (!IsServer) return;
GameObject newCard = Instantiate(cardPrefab);
NetworkObject netObj = newCard.GetComponent<NetworkObject>();
netObj.Spawn();
netObj.TrySetParent(handAnchor)
Are you setting the parent AFTER spawning the card?
[ServerRpc]
void DrawCardServerRpc()
{
if (!IsServer) return;
GameObject newCard = Instantiate(cardPrefab);
NetworkObject netObj = newCard.GetComponent<NetworkObject>();
netObj.Spawn(true); // Ensure the object is spawned properly before parenting
// Attempt to set the parent
if (!netObj.TrySetParent(handAnchor.GetComponent<NetworkObject>()))
{
Debug.LogError("Failed to set parent!");
}
}```
let me try it
Network Object parenting has some rules. I personally try to avoid parenting.
Just use child objects
I handle cards data as a network variable List and then instantiate the visuals locally
Or create an object which holds all references already and then just SetActive the child object that holds that image you want to show.
yeah i have something similar in the code, but hand anchor is nice so that you can do card fanning around 0 0 0 rather than global coordinates and you can move all of the card at once too
{
[Header("Fan Settings")]
[SerializeField] float maxArcAngle = 60f;
[SerializeField] float radius = 1f;
[SerializeField] float cardSpacing = 0.5f;
private List<Card> cards = new List<Card>();
public void AddCard(Card card)
{
if (card == null)
{
Debug.LogError("Tried to add null card to hand");
return;
}
cards.Add(card);
UpdateCardPositions();
}
public void RemoveCard(Card card)
{
cards.Remove(card);
UpdateCardPositions();
}
private void UpdateCardPositions()
{
float totalWidth = (cards.Count - 1) * cardSpacing;
float actualArcAngle = Mathf.Min(maxArcAngle, totalWidth * 2f);
float startX = -totalWidth / 2f;
if (cards.Count == 0)
{
Debug.Log("No cards to position");
}
else if (cards.Count == 1)
{
cards[0].MoveToPosition(new Vector3(0, 0, 0), Quaternion.Euler(0, 0, 0));
} else {
for (int i = 0; i < cards.Count; i++)
{
float xPos = startX + i * cardSpacing;
float angle = Mathf.Lerp(-actualArcAngle / 2f, actualArcAngle / 2f, i / (float)(cards.Count - 1));
Vector3 pos = new Vector3(xPos, 0, 0);
Quaternion rot = Quaternion.Euler(0, angle, 0);
pos.z = -Mathf.Abs(Mathf.Cos(angle * Mathf.Deg2Rad)) * radius;
pos.y = Mathf.Sin(angle * Mathf.Deg2Rad) * radius;
cards[i].MoveToPosition(pos, rot);
}
}
}
i have this code for hand management, so should i just make it networkBehaviour
and sync only list of card?
Card would also need to implement INetoworkSerializable. I usually just will sync a list a Card Ids. I can use a list of all cards in the game in a CardPool list/dictionary for lookups
yeah i have it
i have smth like this for cardManager
{
if (_cardDatabase.TryGetValue(cardID, out CardData data))
{
return data;
}
Debug.LogError($"CardID {cardID} not found!");
return null;
}
and network Serializable:
public class NetworkCard : NetworkBehaviour
{
public NetworkVariable<NetworkString> CardID = new NetworkVariable<NetworkString>();
public override void OnNetworkSpawn()
{
if (!IsServer) CardID.Value = "default_card";
}
}
thank you for help
Is your backend also written in C#? I suppose its more of a no-brainer in that case, but in my case the backend is in TypeScript, so I feel it might add extra work porting over code to optimistic version in Unity client.
I think I got a pretty easy problem to fix for you guys. I'm making a game with mirror & fizzysteamworks. If I play the game inside unity I can host a lobby when I got my steam open and start the game. However, I then send a copy of the game to my friend to test the lobby. He can open the game but can't click the host a lobby button. If he joins my lobby the spacewars games opens for him and he joins in a lobby there. Can someone help me with this?
what do you guys think would be best for my enemies HP, I switch scenes and they respawn if I come back to the room where they are, like in old castlevania games and probably even mario lol
HP as a network variable, or syncronize the hp by the server to all players
as a local variable
Sound like your build is still using the the test Steam App Id
Really depends on your game. I don't usually expect enemy HP or positions to persist after a scene change
networkvariables = persist?
No, unless you have the network objects set to Do Not Destroy On Load. Then they will move to the new scene
^ cool!
so using networkvariable sounds like a good option
if one player gets in the scene, I want the scene and all enemies to load, so if another player also enters that room things are synchronized~
now if no player is in the room, I want to unload the scene and all enemies can respawn if I re-enter that room~
Network variable, floats are the way then?
Just keep in mind that by default the server/host is syncing all loaded scenes to all clients. Your added scenes will need to be loaded additively
any example to that?
this is in my old project
so I would put LoadSceneMode.Additive
and that will only switch the scene to my current player?
No, that will load the "Game" scene on top of the current scene. For all the clients. Having different clients in different scenes is way more complicated.
big oof
so I would be better off making all clients be in the same scene?
that would sacrifice my gameplay a lot but it's doable if needed
It would be way easier to load your rooms as prefabs
so all in the same scene
Right. Then you could use network objects visibility if you need to hide rooms from other players
thanks evilotaku
Isn't that normal if you're still in the testing fase and don't have your own App id?
There should be something called "steam_appID.txt" with the steam app id 480 in it for replacing spacewars when testing
I think the problem is that I can't find that
Sure but the test app is Space War
It used to work fine tho, a player could join me in my lobby with the that app ID
The fizzysteamworks just changed, the appID used to be in the fizzysteamworks script and you could change it in the inspector in the script
now it is supposed to be in a text file
but I can't find the text file
Dunno anything about that. Might have to find the Fizzysteamworks discord server
Depending on what he's trying to achieve, have a preset number of subscenes and indexing them, then just putting players into groups, he can push players into specific subscenes via group index. Or am I missing the point?
You could use something like this example which would take groups of 'x' amount of players (I used 10 for this example), and when they connect they're assigned a group ID. These groups of players are then allocated a specific subscene to view when they are playing the game. This helps avoid the cost of 100+ players all interacting or instantiating projectiles etc, within the same scene, and instead creates multiple instances of the same subscene (or other subscenes if you wish), and then allocates them accordingly. Was this what you were looking for? Example below.
Matchmaker:
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MatchmakingManager : NetworkBehaviour
{
private static MatchmakingManager instance;
public static MatchmakingManager Instance => instance;
private void Awake()
{
if (instance == null) instance = this;
}
private List<ulong> unassignedPlayers = new();
private Dictionary<int, List<ulong>> groups = new();
private int groupCounter = 0;
public void AssignPlayerToGroup(ulong clientId)
{
unassignedPlayers.Add(clientId);
if (unassignedPlayers.Count >= 10)
{
// Create a new group of 10 players
List<ulong> newGroup = new List<ulong>(unassignedPlayers.GetRange(0, 10));
unassignedPlayers.RemoveRange(0, 10);
// Store the group
groups[groupCounter] = newGroup;
LoadSubsceneForGroup(groupCounter, newGroup);
groupCounter++;
}
}
private void LoadSubsceneForGroup(int groupId, List<ulong> groupPlayers)
{
string subsceneName = $"GameSubscene_{groupId}"; // Unique scene name
SceneManager.LoadSceneAsync("GameSubscene", LoadSceneMode.Additive).completed += operation =>
{
Scene loadedScene = SceneManager.GetSceneByName("GameSubscene");
if (loadedScene.IsValid())
{
foreach (ulong playerId in groupPlayers)
{
MovePlayerToSceneClientRpc(playerId, loadedScene.name);
}
}
};
}
[ClientRpc]
private void MovePlayerToSceneClientRpc(ulong playerId, string sceneName)
{
if (NetworkManager.Singleton.LocalClientId == playerId)
{
SceneManager.MoveGameObjectToScene(NetworkManager.Singleton.LocalClient.PlayerObject.gameObject, SceneManager.GetSceneByName(sceneName));
}
}
}
Modify the player connection handler
void Start()
{
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
}
private void OnClientConnected(ulong clientId)
{
if (IsServer)
{
MatchmakingManager.Instance.AssignPlayerToGroup(clientId);
}
}
Depends on the game. If you are treating each sub scene as a separate match, this could work fine. But if it's like a dungeon with people moving freely between rooms the it will cause problems.
Kind of sounds more like he's designing the dungeon scenario. And unless these rooms are massive in file size and complexity, there's no reason to have them as scenes instead of prefabs.
Hi, does anyone know this error when I'm trying to StartHost using Netcode + Facepunch? The scene only has 1 NetworkManager
Post your code here
Will do when I get home
has anybody dealt with this error?
Happens when you create a lobby
Hello
I don't know where to put this question
but anyone here know how to apply unity editor personal license headless in unix?
post your code here. That is usually when you are using a string in a Network Variable
you shouldn't have to.
FixedStrings
I use them
How can i get relay player from lobby player or thr opposite
İ have set the allocation id on the lobby player but what do i do next
You'll need to create a list or a dictionary to map the playerId to the clientID
Ye but how do i do it
İn order to do that i have to get the relay player from lobby player
I usually save the PlayerId as a Network Variable on the Player Object. Then when the player spawns I use its OnNetworkSpawn() to save itself to the Dictionary<clientID,PlayerID>
Ok thank you
Well, then you're looking at a very different requirement. You can't achieve that on a relay system, that's going to require multiple servers with some sort of seemless connection migration solution.
sup chat
I'm trying to use Unity Transport for my player connection
and the host starts fine, however when I try to join I get this error
DisplayLobbyCode ~ means the player joined the session fine,
and it is displaying the code on both players
however, the player doesn't spawn, and in my unity client I'm getting that on the console
[tried with a friend also same issue]
tried all ways,
Unity to Client
Client to Client
Both ways in the same computer, as well as my firend in his computer and me in mine
[Thread with the whole script]
I tried making it where it only uses Relay when needed
but I get that error in the thread (only on the client, as a host it will start fine)
I went back to relay, like I had before, but this approach is somethiing I would love to have...
- I'm not forwarding ports, maybe I have to?
For P2P direct connect will need port forwarding
my code uses directconnect?
TryDirectP2P()
hahahahah
I thought I was NAT holepunching
which is a term I heard that can be done
That is what relay is for
Im trying to connect to the league API
Theyre telling me to add --insecure to it. But how does that translate to unity code?
There are relays out there like Steam P2P and Epic Online Services. But you are very unlikely to go beyond the free tier of Unity Relay
I'm at 7ccu already, maybe I'm doing something wrong lol
Oh, steam p2p interesting
Epic online services, would only work if I put my game in epic I assume
Which, I would only change the way a player create and join the lobby, everything else would stay the same?
You're probably just looking at CCU for a recent time period - UGS pricing is based off of Average monthly CCU.
👀 oh
I have another game up on steam
I think the ccu comes from that one
But if I get close to the limit, and still can't afford it with my games generated income
Switching to steam p2p shouldn't be too hard, I hope
Relay: First 50 Average monthly CCU (approximately 2,160,000 connectivity minutes)
Averaging 50 people being on your game concurrently for a whole month means you likely have a player base that's at least 1,000+ if not more.
And you can see from the connectivity minutes that that's a lot of people playing your game for a considerable amount of time
👀
1,000 playing for 36 hours a month on average
Yeah that's a lot lmao
Okay maybe relay is okay
So 1 ccu equals
720 hours of playtime pretty much?
1 monthly average CCU, yeah
Yea. they really need to change those docs
I've got this code in a ability base class being inherited for each ability, but it's only running for the last ability instead of each attached to the character, I'm using mirror, does anyone know how to fix this?
the StartCooldown runs ok, but everything involved in TurnSystem_OnDecisionTurn only runs for the loast ability
Why does the networked code need to be on each ability? Can't you have a single networked object to manage all the abilities?
I've only used Mirror some but it's been a few years
I'm new to networking so You're probably right
It's a good choice to use Mirror though. It's a good setup. I remember discovering them when the old netcode system was getting deprecated and we were all waiting for the new net code system and the DOTS networking implementation.
I would recommend abstracting your code to work for all abilities at once instead of being run on each individual ability.
Do you mean as in having an ability manager, or a base class which I Implement from to make each ability?
An ability manager, from which you do the networked code. You can still have abilities implement their own functionality though.
can you just have colliders and some logic on the server
Hello! I might need a bit of help I am having trouble wrapping my head around some logic (Netcode for GameObjects):
- I have a game where players can have cosmetics
- Theses cosmetics need to be networkobjects because some of them have transform that I want synched (like bones)
- The way I was thinking about it was that the player instantiate their own skin, and it is reflected on other clients (like spawning a hat child of a head gameobject)
- But you can only spawn network prefab on the server
I am stuck there, is there a best practice for this type of need ?
The concept of instantiating your own skin sounds rather macabre
I wouldn’t recommend making the cosmetics have a NetworkObject on them. You can probably get away with using NetworkVariables to store cosmetics by ID or index and then use that instantiate the necessary cosmetics locally on each client.
Alright, sounds better indeed, I will try that, thank you !
If you're working with Skinned Mesh Renderers, you can set the bones of the cosmetic to the respective bones on the skeleton of the player at runtime. That way all you have to do is sync the player's animation/skeleton and the cosmetics will follow suit
Yeah your are absolutely correct, I just did a quick first test of that and it is working wonder!
anyone got a link to NGO networkbehaviour . This one I think is for an older version since it says its unsupported : https://docs.unity3d.com/2020.1/Documentation/Manual/class-NetworkBehaviour.html
love u
public PlayerController GetPlayer(ulong? clientId = null)
{
PlayerController[] players = FindObjectsByType<PlayerController>(FindObjectsSortMode.None);
foreach (var player in players)
{
if (player.IsClient && !player.IsHost)
return player;
if (player.IsHost)
return player;
}
return null; // No matching player found
}
Im having trouble with getting the correct player for a networked object to follow. It always seems to follow the host despite the client spawning the GO:
[ServerRpc]
public void SpawnShieldRPCServerRpc(ulong clientId, Vector2 spawnPosition)
{
if (shieldPrefab == null)
{
Debug.LogError("shield prefab is not assigned!");
return;
}
GameObject spawnedShield = Instantiate(shieldPrefab, spawnPosition, Quaternion.identity);
NetworkObject networkObject = spawnedShield.GetComponent<NetworkObject>();
if (networkObject == null)
{
Debug.LogError("Spawned shield is missing a NetworkObject component!");
return;
}
PlayerController player = GetPlayer(clientId);
networkObject.SpawnWithOwnership(clientId);
// Assign the shield to the player
ShieldScript shieldScript = spawnedShield.GetComponent<ShieldScript>();
if (shieldScript != null)
{
shieldScript.SetOwner(player);
}
}
GetPlayer() will probably always return the host since the host will be your first spawned player. You aren't doing anyone with the passed in clientId. You should check if player.OwnerId == clientId then return that player.
it's kinda crazy I'm getting 134ms (RTT)
on the same computer
should I look into something to improve this?
Relay?
That's not the craziest RTT for Relay, but could be better. Have you checked where QoS is assigning your Relay server?
who
https://docs.unity.com/ugs/manual/relay/manual/locations-and-regions
You can specify specific regions and check the RTT to make sure QoS is doing its job correctly. Usually it does, but I've seen it have issues on occasion.
First link
yeah, I was looking at that one XDDDDDDDDD
but still don't know how to change it... 90% of the time I don't understand documentation, even if I read it 3 times
I see
I'm putting all the regions in, then I will test
thanks Dylarno
well that seemed to work nicely, thanks a lot 😄 let me test the ping now
XDDDDDDDDDDDDDDDDDDDD
I don't think so. I thought QoS logged it somewhere when it does the autoselect, but I guess not?
before, there was a reference to that in the RelayService
on the allocation of the relay server
but after the big multiplayer update I don't see it
well it does work, tried with Europe region~
That is odd. Relay should be choosing the region with the best ping for you already
its not too crazy to be honest. even on the same PC, both clients have to go through the relay server
I thought relay was like this
both players will cross the relay bridge
to be on the same island
and then the bridge will be of no use anymore
Not really, the relay server is across the bridge. both players are send packets across the bridge and back again
Its actually really good for testing real world condition of your game
wym
I guess... that's fine... 100ms is not even noticeable in my game so far
Internet Service in the US is all over the place. A lot of folks on wifi only setups. If you are going to release it, the game needs to function at 200+ms pings
Not so much a bridge as a man in the middle
Hi, what's the best way to handle syncing projectiles between host and client? Currently, my client sees the projectile vanish mid-air while traveling to the target. In the meantime, the host has already seen the projectile hit and removed it. I guess that's why the client sees the projectile disappear
You'll want to look into Distributed Authority and Deferred Despawning
Deferred despawning is only available for games using a distributed authority topology.
welp, I will put half the rtt
cause it's alarming seeing 130 ms in a game, when it feels fine
thoughts on that?
honestly, you don't have to list the ping times at all. Just make it 1-3 bars or whatever
okay, that makes sense
this would be super bad, right?
reading a NetworkVariable float like that on update
cause I don't remember how to do it xd
nvm, okayyy I see
documentation is a lot better now for multiplayer
compared to 2 years ago
So basically, deferred despawning makes the client projectile get destroyed a few frames after the server projectile, right? I see that in the documentation, there's a despawnTick. This is manually set, but I think there must be a way to determine the lag in milliseconds or something like that to pass into the deferringDespawn method. Manually setting a value doesn’t seem like the right approach because what if the client lags behind by 200ms, 500ms, or something like that? If I understand correctly
And using Distributed Authority will require Unity Gaming Services, right? My original idea is to use a client-host model so that players can host their own games without relying on any services. The only exception is Steamworks, which is used to create lobbies for players to join
Yea. Its a UGS. Its pretty neat with automated host migration
I see it's trying to start host twice
which... I don't see where that happens in my code 🤔
is it because it's inside "try"?
Yeah, but I mean it's only free for now. Are there any other ways to solve the problem above
async void Start()
{
await UnityServices.InitializeAsync();
if (!Unity.Services.Authentication.AuthenticationService.Instance.IsSignedIn)
{
await Unity.Services.Authentication.AuthenticationService.Instance.SignInAnonymouslyAsync();
Debug.Log("Signed in successfully!");
}
_createLobbyButton.onClick.AddListener(OnCreateLobby);
_joinLobbyButton.onClick.AddListener(OnJoinLobby);
_openLobbyMenuButton.onClick.AddListener(OpenLobbyMenu);
}```
```csharp
public async void OnCreateLobby()
{
CloseLobbyMenu(true);
_connectionTypeText.text = "";
_connectionTypeText.color = new(1f, 0.5f, 0f);
var selectedRegion = RelayRegions[_selectedRegionIndex];
try
{
var options = new SessionOptions
{
MaxPlayers = 4,
}.WithRelayNetwork(selectedRegion); // DEVOUR
var session = await MultiplayerService.Instance.CreateSessionAsync(options);
_currentSession = session;
NetworkManager.Singleton.StartHost();
DisplayLobbyCode(session.Code);
CloseLobbyMenu(true);
}
catch (System.Exception e)
{
Debug.LogError($"Error creating room: {e.Message}");
}
}```
All UGS packages are priced with the same general model. Just about all of them have very generous free tiers that 99% of indie developers won't hit. If you are to surpass the limits of the free tier, you will have a big enough player base to be making money from your game.
You can disable the bullet renderer instead of despawning it
Your OnCreateLobby might be getting called twice. Be sure you unsubscribe from any events that call it
Only if this object is getting disabled and re enabled.
Crap wait. You're using sessions. You shouldn't be calling StartHost() at all. Multiplayer Services handles all that for you
do NetworkVariables have a different naming convention?
I heard events are EXAMPLE_EVENT
which I find crazy and ugly so I don't use it
_privateVariable
localVariable
PublicVariable
^ those are the conventions I know and use so far
i've never seen those conventions 😨 i don't see why you wouldn't just use the normal conventions for fields and properties for network vars and events
I'd recommend checking out Rider over Visual Studio. It will auto correct to follow naming conventions for you out of the box
You can use any convention you want. Only RPCs have a required naming convention
Hi, guys. Using PUN. Have a problem loading level on other than master client. Other players can connect, spawn in the same room where the master client is. Everyone sees each other. But, during loading the level, others cant see the progress bar. It is just skipped as the logic is in OnJoinedRoom(). But, it simply not triggered on other clients while connecting. What can be the problem? Here is the code, and it is called only on master client:
public override void OnJoinedRoom()
{
if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
{
Debug.Log("We load the 'Room for 1' ");
PhotonNetwork.LoadLevel("Room for 1");
}
connectingLabel.SetActive(false);
loadingLevelLabel.SetActive(true);
loadingScreen.SetActive(true);
progressBar.gameObject.SetActive(true);
Coroutine loadLevelCor = StartCoroutine(LoadLevelAsync());
}
Goated VS background
@sharp axle you were mentioning, putting everything on the same scene and switching the visibility
would be the most logical approach for multiplayer, but wouldn't it be rough having a complete game in the same scene?
wouldn't all objects in it have to be loaded? 🤔
Depends on the game. The host/server can completely unload any objects not visible by any player. This could be done with addressables if you have memory concerns
well...
do you have maybe an example script for that? not sure if you have done it before
I would love to start testing that out
I assume putting areas/rooms as prefabs is one thing, but I wouldn't know how to load it and unload it when no players are in that area xD
what should I put here, let's say I destroy an object and a player joins
for that player to have that object destroyed as well
I don't have any specific examples. But you can check network observers with GetObservers()
or I assume, I should not destroy breakables and enemies, but rather disable them
so I can enable for them to respawn (?)
I would use Triggers if you when you need to load new rooms
I would give each room a manager script that would keep track of everything in it. I don't know how big your rooms are but that script could also be used to call NetworkHide/Show() on all the network objects in it if there are any
Hi. I have car that i want to be able to enter / exit with host player and client player (peer to peer, netcode for gameobjects). I'm having problem where i can't detect car with raycast with the client player. For host everything works, but client is not detecting car at all with the raycast. Do i need to do this some other way? Code for raycast is after if (!IsOwner) return;
post your code here so we can see what's up
I got it fixed like this, but now i kinda want to know does this approach make sense? So this script is PlayerInteraction.cs and player prefab has it so all players that join the game are running this.
im having trouble syncing a spawnedPrefab to position itself on top of its parent's position. I thought the Instantiate()'s spawnPosition parameter would be out of sync when actually spawning in the prefab so I tried resetting its localPosition to 0 after setting it as a child of the player but as the image shows, there's still some offset. The parenting works and the prefab does move with the player, however.
[ServerRpc(RequireOwnership = false)]
public void SpawnShieldServerRpc(ulong clientId, Vector3 spawnPosition)
{
if (!IsServer) return; // Ensure only host executes
GameObject spawnedShield = Instantiate(shieldPrefab, spawnPosition, Quaternion.identity); // the prefab to spawn
NetworkObject shieldNetObj = spawnedShield.GetComponent<NetworkObject>(); // the spawned Prefab's networkobjct component for logic (movement)
NetworkObject owner = GetPlayer(clientId); // the player that requested this
// reposition (potential network delay from Instantiate(spawnposition)
Vector3 playerPosition = owner.transform.position;
spawnedShield.transform.position = playerPosition;
// Spawn with ownership to the client who requested the shield
shieldNetObj.SpawnWithOwnership(clientId);
// Parent to the player, to always stay on top of the parent
shieldNetObj.TrySetParent(owner, false);
// Reset localposition if there's an offset due to network delay
spawnedShield.transform.localPosition = Vector3.zero;
StartCoroutine(DespawnSpell(shieldNetObj, shieldLifeSpan));
}
