#archived-networking
1 messages · Page 22 of 1
in the network manager you have the scene management toggle. on = soft sync, off = prefab sync
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.
Right, so that’s new since last I used NGO, from the docs, if you don’t know why you’d need prefab sync for your specific project, then don’t use it. It’ll just cause extra work.
that said I could imagine situations where you need to break away from simple ‘everyone sees everyone’ model that’s the default in simple arena-style games or when you may need to worry about exploits.
thanks that's good advice. i will just use it for now
anyone? thanks in advance
How can I prior set variables in NGO at server side to ensure they are accessible in OnNetworkSpawn at Client side?
Cool, what other free versions and resources are there?
Not that one ready for multiplayer support yet, I’m mostly curious
In particular at some point a game of mine will have online and I’ll need the help of my friends to debug online issues. Any advice for how to do that?
FYI I know absolutely nothing about this kinda thing
Any advice should be “networking for dummies levele”😂
Check the pinned message here for resources. All the solutions will have their own discord servers as well. You will need to decide on multiplayer from the very beginning or you are going to be rewriting all your code. You'll be using a Relay service to connect over the internet. Unity, Steam, Epic, and Photon all have their own services you can use for varying cost.
Yikes glad I got the memo first about code. I haven’t thankfully done much of anything yet in that department. Still testing out things with free assets
Glad I asked this now rather than waiting till the end like I had planned. Idk why but I thought that would be the hardest thing to implement. That would a set me back majorly.
Is there anything else like that that I need to be careful of?
I know it’s probably hard to answer considering you don’t know what I’m making . But Do randomly generated levels mess with online functions? Would I need to make keys and seeds as identifiers or something for each character?
My brain thinks that if it’s all random other player might load into the void or in the wrong place😅
Also I’m reading through it all. Does the “multiplayer play mode” not exist anymore? The page is missing
How can I set the Tag of each player to "Enemy" unless its the local player? Using Pun 2/ Photon
It got moved to it's own page
https://docs-multiplayer.unity3d.com/mppm/current/about/
Overview of Multiplayer Play Mode
Your procedural generation will be deterministic so as long as everyone is sharing the same seed values then everything will be identical on all clients
Phew thx for the link, gonna add that to my notes
That’s also good to know.
Are seeds the only way to make identifiers fire greater worlds. Or is that the best used method?
It seems like it would be the simplest and best option, but I’m not sure what others exist and how or when they’d be chosen
If the game is Minecraft it’s probably the best use. But what about other games like animal crossing, spelunky and so on.
Usually you would loop through all the players and check for IsOwner or whatever photon uses them set the tag appropriately
What do you mean by identifiers?
Like checking to make sure the player loading into the world is your friend and not some random who accidentally joined
If in testing among friends I meet I make sure I have a way to identify them and make sure no one else can get in.
Idk how games and networks do this other than with spending of number or password/key to identify “friends vs !friends”
I think that means I have to make some kind of friends list option or room codes like among us and animal crossing dodo codes
Unless I’m overthinking things again
Would you do this Inside a OnJoinedRoom function?
Ag I think I found a page 📄relevant.
Man in the middle attacks and security is my concern when testing with friends
How do I keep us all safe and ensure only a select specific few can test with me?
Unity Lobbies can have passwords. There is also a Friends system you can use
I haven’t found the friends system page about it but that’s good to know this
I’ll do some research and experiment with multiplayer first and make sure I get it safe before I start doing adding features.
“I’ll be back”😎
At some point eventually
hey, i have a place in my multiplayer game where when you go there another scene loads additively normally when there are more than 1 player and someone goes there the new scene only loads for the player that entered that area.
but if the host enters the area before the others join. when they join the scene loads for everyone that joins after the host entered the area.
how do i fix that ?
You need to disable scene management and do custom, location based loading and spawning for everything on clients
so you mean instead of loading another scene i should just take everything in the scene and make it a gameobject that i turn on and off when the player enters the area ?
Not necessarily, you can load scenes on demand on clients. You just have to do it manually and everything networked needs to be a prefab
It’s certainly easier to not load scenes asnyc and do what you said.
what do you mean by manully loading a scene ?
Not having it done automatically by the network manager
I'm currently looking at https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Get.html
this is the code:
public class Example : MonoBehaviour
{
void Start()
{
// A correct website page.
StartCoroutine(GetRequest("https://www.example.com"));
// A non-existing page.
StartCoroutine(GetRequest("https://error.html"));
}
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
Debug.LogError(pages[page] + ": Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError(pages[page] + ": HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
break;
}
}
}
}
I would like to add a interface function to the IEnumerate:
public string GetRequest(string uri)
{
string response = StartCoroutine(GetRequest(uri));
return response;
}
But I can't figure out how to get a return value from IEnumerate, any advice?
you can't do it directly, one common way is to add a callback with the result eg IEnumerator GetRequest(string uri, Action<string> onComplete)
aha okey ill check it out
I have the following scenario, which I don't know how to handle:
Context:
- I am using Kinematic Character Controller from the asset store to move my client authoritative players around, as well as plaltforms.
- In order to move the platforms, and the players be able to be moved by them, I need to do the platform movement on the client side as well.
Let's say I have a platform that I need to move around the map, that needs to be able to move all players around (host + clients).
What I've tried:
- If I only move the platform on the server, and add a network transform to the platform, the client players will not get moved by it, since the physics mover also has to be ran on the client side.
- Have a network variable on the platform which the server updates. Lerp towards that from the current position on each client. Problem with this is that since the client has quite the delay like this, For the server it will appear that the client stands on thin air because the client thinks the platform is further back in time. And the client sees the server standing in thin air as well but ahead in time.
How do I fix this? Any ideas are much appreciated. Thanks!
oh wow, i didnt know scenes had to be prefabs, i havn't finished reading all the documentation yet. does that apply to all scenes? even ones multiplayer clients wouldnt access?
like the home menu scene or some cutscenes?
I have a question for the pros , I have a trivia game I wanna add networking , I was close to completeing my task once with netcode for gameobjects but I also know that NGO is "overpowered" for a trivia game. my question is what is a more simple solution for making a trivia game multiplayer?
i believe what they're referring to is that if you don't turn on NGO scene management, you can load whatever levels but objects within the scenes won't be spawned as network objects automatically, they have to be prefabs you spawn in yourself or NGO won't know about them
NGO is fine for that, wdym
You could also use Cloud Code if you don't need the real time communication of NGO.
i think i understood part of that. meaning it has to be the right format for objects to spawn and and you have to tell NGO whatever that is what prefasb specifically need to be loaded where
kinda like that conversation example where someone tells someone to come here, but they dont know where here is
Im trying to build a Unity Netcode app through XCode to my phone, but when I try to deploy with XCode, I get a few errors like:
/Users/sanderschulhoff/Unity/builds/Il2CppOutputProject/Source/il2cppOutput/Assembly-CSharp.cpp:4688:9 no matching function for call to 'NetworkBehaviour___beginSendRpc_mD9AE8C915F9ECD278DAF43F4A0FA318DEE1851D1'
I have tried 3 different unity versions and 2 different XCode versions, but can't figure it out. The app works fine if being deployed to desktop, and I havent found this error on the Internet. Any ideas?
I have found that removing all [Rpc(SendTo.Server)] fixes it, but I need these Rpc calls.
There is a github issue on this. Changing back to ServerRPC seems to be a workaround
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/2817
ooo tysm!
Im not sure I can do ServerRPC unless I downgrade netcode
reading issue now
the old RPCs will continue to work
I have spent days looking at these errors and scratching my head
Thanks again for pointing me here
does some1 know how to make a seprate ui for each player? i am using netcode
is this related to this thread?
no
just a question
ah, if you just have regular UI elements that you dont add networking stuff to, the players will have separate uis
is that same for changing ui? health, inv etc
Assuming the server is sending an RPC to the client, yes, it should “just work”.
why did u "just work"
u mean like work like normal?
Yes
oh oke
I said it like that bc it should just work as you expect it to
and player is a prefab soo anything for that
Wdym?
u need to make the player a prefab to put in manager
so u cant asign ui to it that easy right?
u get like a type mismatch
Hmm, I dont quite understand (also I have minimal Unity experience)
The UI itself should be local and not networked unless its something like a name tag that you spawn with the player
okey kinda logic thx
do u know how i update the ui bc i just cant
not on the single player way tho
https://hastebin.com/share/eraheluhaj.csharp tried to make this very simple but idk just not updating made the text a prefab added it also to the canvas before game just nothing
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
If you need the text synced to all clients then you would need to make the string a network variable. If this script is on an in scene o ject, then you can set the text in OnNetworkSpawn() but you all need to find the reference to the UI there too
I'm still learning but it might have to do with the networkTransform
well duh
but im not sure which one
or why its even causng it
cuz i didnt modify anything at all in the network transform, and yet its saying Object reference is null?
Does it have a network object
yes
[Rpc(SendTo.SpecifiedInParams)]
private void ApplyGlassRpc(RpcParams rpcParams)
{
Debug.Log(IsServer);
foreach (NetworkObject obj in chosen)
{
obj.gameObject.AddComponent<GlassPart>().glassBreak = glassBreak;
}
}```
why does isServer = true here, but then when i add the component and in the script in start function itry to print isServer, it's false
```cs
void Start()
{
GetComponent<Collider>().isTrigger = true;
Debug.Log(IsServer);
}```
Start is called before the object is connected to the network. You should check Networkmanager.Singleton.IsServer as long as it's being called after the server has started
Interesting, that worked
But the same issue happens in here:
private void OnTriggerEnter(Collider other)
{
Debug.Log(IsServer);
if (IsServer && other.gameObject.GetComponent<Player>() && GetComponent<MeshRenderer>().enabled)
{
DestroyGlassRpc();
}
}```
Even tho this isnt run on start
It's when its triggered
Trigger events should happen on both server and clients.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/
There are many different ways to do physics 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.
I'm trying to only detect it on the server tho
But the IsServer varaible is false there as well...
Dunno. As long as this in on a network object and this is a network behaviour and the server has started then IsServer should be true
I have it a feeling it has something to do with the fact I'm putting this component script onto an object that already has an network object placed on it in the scene
Oh yea. that's not gonna work
Oh, how am I supposed to add a component like script onto a network object on all clients/server then?
You are not. they are supposed to be prefabs. You can disable components with a clientRPC if you don't always need them
Is it a bad idea to just set maxPlayers for a new allocation for Relay to 100 so that I don't have to update the limit if needed?
And updating would be stopping the Relay and then creating a new one with the updated number I guess right?
Can someone explain to me how it's possible in Unity Netcode (or in mirror) to have the server host multiple game instances (e.g. matches)?
Run multiple server processes that respond on different ports
You probably need to configure your servers via command line args or a config file to inject that port
Alternatively you can use a hypervisor to run virtual hosts or run each server inside a
(docker) container
is that really the only option? isn't that brutally wasteful of resources?
That’s the only practical option that doesn’t involve building a completely custom netcode library. It’s also not particularly wasteful. You run each process on dedicated cores and memory, it’s probably even better for utilizing system resources than constantly coordinating through a shared thread&memory
It’s also how everyone from indie to AAA do it.l, meaning it scales excellently.
Only MMOs with large persistent shared worlds really need anything else
I see it working for indies, and most genres, but e.g. for an FPS where you have ~ players / 10 matches i can see issues with scaling
since my primary objective is to learn, i'll write my own netcode
You need to make sure it's an actual problem before you waste a bunch of time trying to solve it.
i just use third party server providers since im lazy and kinda stupid
to be honest that's the most mature choice, especially if you're not a fortune 500 game substudio
it also makes the most sense, people always complain about usually having to pay after a certain point but whats the big deal in that
i use playfab and photon, which both have a 100k player limit before you have to pay
and you especially don't have to worry about optimization because it's already implemented, "bug free" for you
but tbh i'm convinced, i'm not going to write my own netcode in Go xD I mean if I had 2000 concurrent players, that's 200 processes, I'd argue that my game is already a blazing success, but in a much more realistic scenario I'd call myself lucky if i have monthly 200 players
Also just putting it out there that if you have less than 50 concurrent players 24/7 then the Relay service is completely free. Steam and Epics relay services are also free
How i can instantiate from client to client?
I have are server and two clients connect to him.
I don't understand how to make it possible for a client to create an object on a second client. If they are connected to the same server
A client can not do this. It will have to be done with a ServerRPC like you have there. But you can't spawn a child object. The root object is what needs to be spawned
I didn't understand the second part of the message, i.e. I can't create it in something? And if so, the problem is that (error)
Parenting a network object is kind of complicated
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/
ServerRPCs will only get run on the server so you shouldn't be seeing that error. Make sure that this in on a Network Behavior.
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
even if me remove the second parameter, the error remains the same
post the full code here. something is very wrong if clients are trying run a serverRPC. Do you have the [ServerRPC] attribute?
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/serverrpc/
ClientRpc and ServerRpc are legacy features of Netcode for GameObjects and have been replaced with the universal RPC attribute. This documentation is for legacy use. For current projects, use Rpc instead.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ok right. that is a monobehavior. It needs to be a Networkbehavior
now a new error
it needs to be on a network object for RPCs to work
I have
is it already in the scene? or was it instantiated after the game started?
If you mean player prefab, I don't have it
I mean the chat manager.
Dunno. that message usually means the chat network behavior is not on a spawned object
so lets say i have a gameobject that i disable across the host/clients and then enable it 15 sec later via a coroutine. how do i sync this to new players joining? because if they join after i send the rpc to disable the gameobject, it will still be visually enabled on their screen
You should be using NetworkHide()/NetworkShow()
I should clarify that actually the gameobject itself is not getting disabled, but its mesh renderer componenet is
Oh, in that case use a Network Variable bool
But how would I know for how long to keep it disabled for to be in sync with other clients?
This is what my current script for the object looks like
void Start()
{
GetComponent<Collider>().isTrigger = true;
}
private void OnTriggerEnter(Collider other)
{
if (IsServer && other.gameObject.GetComponent<Player>() && GetComponent<MeshRenderer>().enabled)
{
DestroyGlassRpc();
}
}
[Rpc(SendTo.ClientsAndHost)]
private void DestroyGlassRpc()
{
GetComponent<MeshRenderer>().enabled = false;
GetComponent<AudioSource>().Play();
StartCoroutine(RespawnGlass());
}
private IEnumerator RespawnGlass()
{
yield return new WaitForSeconds(15);
GetComponent<MeshRenderer>().enabled = true;
}```
I would use a NetworkVariable<bool> IsDestroyed
then the server/owner can set IsDestroyed.Value in a coroutine if you need to.
The clients can sub to IsDestroyed.OnValueChange in order to set the renderer
When I send a message, a strange error pops up, I don't understand why I want to change the msg variable
does anyone have a simple rigidbody2d prediction script that I can add to my game (i'm using NGO). I'm trying to make a quick demo and don't really have the time to research my own. I know it would just be a component extending the networkrigidbody2d component.
Network Variable can not use strings. You will need to use one of the FixedString types
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#strings
Introduction
You are not going to find a simple prediction script. A whole system needs to be created to handle the client prediction and server reconciliation.
If you just need it client authoritative, then you can add a client network transform to it
Is it a guarantee that network variables will eventually be synced?
in my game a network variable int for health sometimes stays at 1 even though on the server the value is less than zero
so the death action on the client doesn't trigger
and even after a while the value never updates to the server value
like this
Yea, they sync automatically. It may be delayed by lag but network variables are sent reliably. Just make sure the object isn't getting destroyed or disabled
The gameobject only gets teleported to a different place
and even when i wait 10 + seconds the value of health stays at 1 despite the value on the server definately being less than 1
wait
nvm
I'm pretty sure the value does change to 0
If I have a gameobject that is disabled in a scene by default is there an easy way to enable it across all clients/server when needed?
How are you teleporting it? The one client on the left is not
Regular game objects or network object?
public void OnHealthChanged(int previous, int current)
{
HealthBarText.text = current.ToString() + " / " + MaxHealth.ToString();
if (current <= 0)
{
Dead = true;
transform.position = GameManager.Singleton.GetGraveyardLocation();
if (!IsServer)
{
return;
}
Invoke(nameof(Respawn), 7);
return;
}
if(previous <= 0 && current > 0)
{
Dead = false;
transform.position = GameManager.Singleton.GetSpawnLocation(Team);
}
}
It has a networkobject componenet on it
this is the onrep for the health network variable
Enabling/disabling a network object is effectively the same as spawning/despawning it
But im wondering how it would work, since the gameobject is disabled by default so won't the networkobject not work?
It can't be disabled by default. You should use networkHide() or Despawn()
Hmm. I think I migth just make it a prefab and spawn it into the scene whenever I need it
Yea. In scene objects are not meant to be despawned dynamically anyways.
You can implement a custom spawner if you really need to keep the instance loaded for performance reasons
I don't, I just thought it would be easier, but a prefab system for this might be cleaner anyway
Wait if I want to spawn a prefab do I have to add it to some kind of list? Or can I just do it with the instantiateandspawn function?
I think that was added in the latest version
Oh shoot
How am I supposed to have another script thats meant to handle networking things on my networkmanager gameobject?
Add it to the list in OnNetworkSpawn()
Use a separate object
can i just add it here?
Looks like one of these was already created
Oh yes. To spawn it needs to be added to the network prefab list.
If you are adding a prefab at runtime then that's a bit more complicated
Wdym adding at runtime?
After the game has been built. For something like DLC content
Oh
Anyway why can't add I add variables to my custom network manager that appear in the inspector?
Wait, how are making a custom network manager? You should be accessing NetworkManager.Singelton
I inherited networkmanager
Whatever, I just made a game manager network object and now that's fine
But I try to spawn my prefab and I get this error
Spawning NetworkObjects with nested NetworkObjects is only supported for scene objects. Child NetworkObjects will not be spawned over the network!
And
ArgumentException: NetworkObjectReference can only be created from spawned NetworkObjects.
Can I just loop through all of the network objects and spawn them?
Yea. Like it says only the root object is supposed to have a network object. And you can only use network object reference from a spawned object.
You can loop through the network prefab list if you really need to.
Crap
Idk how I can make there only be a root object for the network object
I have like a million network objects
So I have the root which has a network object and script, but then I have a bunch of the same parts as children with a network object and script
The root script requires network object references for the children with the script
And the script on the children also requires network object
Looks like the scripts on the children themseleves don't need objects
A NetworkBehaviour requires a NetworkObject component on the same relative GameObject or on a parent of the GameObject with the NetworkBehaviour component assigned to it.
But how am I supposed to pass references to the children? Rn I use networkobject reference
What exactly are you trying to do? I'm assuming GetComponentInChildren() won't work?
So like I used to have networkobjects on the child
and in an RPC I would pass the networkobject reference as a parameter because I wanted server/clients to be able to modify the same gameobject
now If I remove the network object from the child
The networkobject refernece doesn't work
and I can't use gameobject as a paramter in rpc
network object references wouldn't have worked in the first place because child objects don't get spawned. You could index the children i suppose and then send the index of the object in your RPC
They worked before i switched to a prefab spawning system
Like when they were in the scene when building
Why?
i solve it
What's the differences between FixedString types? Which one should I use? I'm having a similar issue as the person above lol
The only difference is their size. ASCII is one byte per character so that limits how long the strings can be
Is there a reason why u wouldnt want the biggest one?
bandwidth gets expensive
basically, yea. You can technically use different encoding or use compression
Got it
Also, do you know of any other way that I can send references to gameobjects via rpc or network variable/list without like an index?
That's the main thing I'm struggling with right now
I saw that unity has some kind of instance id for gameobjects, but idk if those are the same across all clients
And how I could find gameobjecgs based on it
quick (stupid) question, when dealing damage to another player i always call a serverrpc, is that correct? it feels kind of wrong calling the server every time to deal damage to any player
Normally, I'll just use a List with all the items I want to track. EquipmentList, CardList, AbilityList, ect.
So those are regular gameobject lists?
All data has to go through the server in any case. You can make it client authoritative by using Network Variables, but you are trusting clients to apply their own damage then.
Some times, yes. Most of the time is a list of scriptable objects
I see
Btw, is there a list or something of all players with prefabs?
Because rn to get the player with their associated gameobject prefab based on their client ID, i have a dictionary of clientid and gameobjects that i add to when a player prefab is created and delete from when a player leaves
public Dictionary<ulong, Player> players = new Dictionary<ulong, Player>();```
im wondering if theres a better way to do this
The server has access to a list. but the clients do not
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/#finding-playerobjects
Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:
Ah okay thats fine
I only need it on server anyway
One more thing, I've noticed that even tho my network manager is a singleton, it doesn't have a feature built in that will make it delete other network managers if i go back to a scene where it was created. is this on purpose or a bug?
since if i dont have an if statement to check if the singleton variable was already assinged, there would be 2 network managers
i have to manually delete if the singleton variable was already assigned
"You can make it client authoritative by using Network Variables" what do you mean by that? am i not supposed to use network variables for health and stuff? also how can i allow clients to change them (i always get an error)
Yea. its a bit tricky. The network manager is set to Do not Destroy on Load. The standard way seems to be to have a setup scene where you have the initial Network Manager then switch scenes immediately to the main menu. Then you can always go back to the main menu without issues.
You can set the Health network variable to Owner Write Permission.
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#write-permissions
Introduction
another quick question: i want to send a server rpc to spawn an object, but i want to set the "spawned" object to the spawned object variable on the client and not the server (same with the isSpawned bool) how can i do that?
[ServerRpc(RequireOwnership = false)]
void SpawnServerRpc(int PrefabId)
{
GameObject prefab = NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs[PrefabId].Prefab;
spawned = Instantiate(prefab , spawn.position, spawn.rotation);
spawned.GetComponent<NetworkObject>().Spawn();
spawned.GetComponent<Health>().Team.Value = Team.Value;
isSpawned = true;
}
You can send an Network Object Reference back to the client if you need to. But if this object is going to be owned by the player then you should probably use SpawnWithOwnership()
Also, the Network Object already has a .IsSpawned field you can use
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
what is the difference if a player has ownership or not? just so i completely understand
with ownership, you can use Network Variable Owner write permissions and client network transforms. as well as checks for IsOwner in network hehaviors
what i meant by simple was just some thing that would interpolate the transform's position based on its velocity until it recieves and update from the server, where it then snaps to that position
the reason why i am asking is, that in all strategy games i have played, your allied players /team always had their own troops and not shared ones, so i was wondering why... but i guess that was just for gameplay purpose and not networking xD
is that possible or would that require implementing an entire client prediction system like u mentioned
i just completed all the steps on here and got it to do the circular spinny thing its supposed to do when its done correctly. https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo/
i have no idea what to do next tho, the next pages don't seem like anything i need to do just more generalized advice for things i can do.
Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).
i'm not sure where to go from here. but i'd like to add my player prefab thing onto an actual model i've rigged. is it too soon for that?
Its possible But its not really a one script solution. Honestly just using a client network transform is probably enough for you.
I would go through Code Monkey's Netcode tutorials after the Getting Started guide
what even is client side prediction? just calculating where the player would be without a delay/latency?
Its anticipating where the other players will be in next update. then correcting that prediction if its turns out wrong.
aaaah , i understand. thx.
uh wait by code monkey do you mean this one? https://www.codemonkey.com/
or this one https://unitycodemonkey.com/index.php
Unity Code Monkey, Learn Game Development with Unity and C# taught by a Professional Indie Game Developer
bruh what is the first one xD (it's the 2.)
when i googled code monkey the first one popped up
so i was a bit confused at first
same
last question for today, i promise xD so, in my strategy game, shouldn't i just disable the code on the clients? for example the ship movement is simulated on the server and has network transforms, so no need to also run it on the client right? just sync the waypoints and targets that the players set?
Depends on how sensitive your movement is to lag. if its turn based then it probably wont be an issue. But if APM is super important then the lag of an RPC might be unacceptable.
i mean if i give a spaceship a waypoint/target and it will move there in one click, not an fps if you mean that- i am a bit confused xD
If you are micro managing units like in competitive Starcraft or a MOBA, then latency is something you are going to have to manage somehow
so what could i do?
That's where a client prediction system is used. something like Rollback. Though Stormgate is the only RTS i know of that using rollback netcode
https://stormgatehub.com/stormgate-rollback-netcode-monumental-technical-leap-rts/
uh i don't think i could do that tho
if older rts didn't use that and worked fine then what have they done
(the game my game is inspired of is from 2006)
Lockstep has lost! The Client-Server network model has won and has become the standard for pretty much all games. RTS games were the last…
isn't that already what i am doing? everything is on the server in unity or am i wrong xD
sure maybe lag isn't a problem for your game
i really want to know what the original game did
because it worked fine
it used lockstep tho
i know that because i got so much desyncs
i think just to set targets/waypoint will have a delay in my game... but idk how to do that rollback stuff so ... yeah
i have no money for a server so the problem will be it's just players as the server/host
Good morning, I'm trying to connect my firebase realtime database to my Unity project but I'm getting this error:
I even tried to add reference to my db using GetInstance and a url still didn't work, here's how I reference the db:
FirebaseDatabase.GetInstance("url");
dbRef = FirebaseDatabase.DefaultInstance.RootReference;
I got it fixed, had to go to my google-services.json file and add the following: "firebase_url": "my url", dependency
idk if this is a noob question or not, but after i get the netcode all set up can i export all that, like the scene settings and scripts so i can just re-import that into future multiplayer games i make?
and if so is it as simple as just ziping it all up or do i have to build it?
is there a reason that only my host player gets moved to the new spawn position and not the client?
foreach (ulong id in CustomNetworkManager.Singleton.ConnectedClientsIds)
{
Transform spawn = GetRandomSpawnPoint("GamePoint");
GameObject plr = CustomNetworkManager.Singleton.ConnectedClients[id].PlayerObject.gameObject;
plr.transform.position = spawn.position;
plr.transform.rotation = spawn.rotation;
}```
You can export whatever you want as a unitypackage
Are you using client network transform?
Yes
Only the owner can move the player in that case. So you would need to either change ownership temporarily or send an RPC
Even if I'm the server?
Yep. Server is the owner of the host so it can only move the host
How do I change ownership temporarily?
I assume its osmething like
GetComponent<NetworkObject>().RemoveOwnership();
move to position
GetComponent<NetworkObject>().ChangeOwnership(clientId);
Basically. You might have wait a tick for the owner to change on the client side. I usually use a clientRPC if I need to force a move client side.
You can use a coroutine in fixed update() and in it use yield return null to wait a frame
Ah
Im using the Simple FPS template in Photon, when i run it, it says i need to have a connection plugin assigned. Where do i find that? I dont see a connection plugin to assign
hello again,
so in my fps, if i hit an enemy i run code to deal damage (ifServer local, if not send a serverrpc)
if the health is 0 i want to run Kill() on the player, but how do i do that? if i do it like the damage dealing it doesn't work.
my brain can't just not think that far yet i guess 💀
(the server can't kill clients i think.. it's just not working.. maybe the damage code is wrong too idk)
public void GetDamage(int damage)
{
if (health.Value >= 0)
{
if(IsServer)
{
health.Value -= damage;
}
else
{
GetDamageServerRpc(damage);
}
}
else if(health.Value <= 0)
{
if(IsServer)
{
Kill();
}
else
{
KillServerRpc();
}
}
UpdateHealthBar();
}
[ServerRpc(RequireOwnership = false)]
void GetDamageServerRpc(int damage)
{
health.Value -= damage;
}
[ServerRpc(RequireOwnership = false)]
void AddHealthServerRpc(int healing)
{
health.Value += healing;
}
[ServerRpc(RequireOwnership = false)]
void KillServerRpc()
{
health.Value = maxHealth;
Respawn();
}
void Kill()
{
health.Value = maxHealth;
Respawn();
}
hey i just switched my NGO game to webgl, and after updating the transport and my code to use wss, i'm getting a bunch of wierd errors in relation to some jobs:
System.IndexOutOfRangeException: Index 0 is out of range of '-1' Length.
This Exception was thrown from a job compiled with Burst, which has limited exception support.
0x00007fff34dfc9a9 (cc720dfe2700bd1c79b2915b24328f8) Unity.Collections.NativeArray`1<long>.FailOutOfRangeError (at G:/Unity/NGODemo/Library/PackageCache/com.unity.burst@1.8.11/.Runtime/unknown/unknown:0)
0x00007fff34e0d9d3 (cc720dfe2700bd1c79b2915b24328f8) Unity.Networking.Transport.NetworkDriver.InternalUpdate (at G:/Unity/NGODemo/Library/PackageCache/com.unity.burst@1.8.11/.Runtime/Library/PackageCache/com.unity.transport@1.4.0/Runtime/NetworkDriver.cs:914)
0x00007fff34e0af36 (cc720dfe2700bd1c79b2915b24328f8) f00744ec48cd0864aed85ed9873e2356
0x00007ffe9ed45545 (Unity) ExecuteJob
0x00007ffe9ed46890 (Unity) ForwardJobToManaged
0x00007ffe9ed4290b (Unity) ujob_execute_job
0x00007ffe9ed41ec1 (Unity) lane_guts
0x00007ffe9ed44864 (Unity) worker_thread_routine
0x00007ffe9ef03e25 (Unity) Thread::RunThreadWrapper
0x00007fff657b257d (KERNEL32) BaseThreadInitThunk
0x00007fff67a8aa58 (ntdll) RtlUserThreadStart
theres a few others, but im just wondering what this is. my project seems to work fine but is there something i forgot to do after switching to webgl?
Can you not do private NetworkList<int> chosen = new NetworkList<int>();? I'm reading it will lead to memory leaks apparently?
Instead your apparently supposed to only initiliaze it in awake?
That's right. in Start() or Awake()
WebGL can only work using Unity Relay or connecting to a dedicated server
thanks. that just reminded me that i completely forgot to switch to the relay transport
I see. I thought moving initlization into awake would fix it, but im still having an issue where my int networklist has a bunch of items, but they are like all weird? the server adds either 1 or 0, but then on the client it reads like 213213213, -1234, etc...
very weird numbers
hmm after changing it, the error persists. im fairly certain my relay code works since i wasnt getting any errors when using dtls but i could be wrong
additionally, the game seems to work fine on its own, bbut when trying to have multiple players, the network manager doesnt spawn the player prefab for each player
did you make sure to use wss in relay creation and click websockets in the transport component?
yup. thats what i meant when i said updating my code to use wss
Alright so I did some debugging and found out that it's probably due to me sending an client rpc as soon as the networklist is updated, so theres probably not enough time for it to be updated on the client properly between the rpc send time and the networklist change modification.
foreach (Transform section in sections)
{
List<Transform> glass = new List<Transform>();
foreach (Transform trans in section)
{
glass.Add(trans);
}
chosen.Add(Random.Range(0, glass.Count));
}
ApplyGlassRpc(RpcTarget.ClientsAndHost);
CustomNetworkManager.Singleton.OnClientConnectedCallback += plrID =>
{
ApplyGlassRpc(RpcTarget.Single(plrID, RpcTargetUse.Temp));
};```
How can I modify that code so that I can wait for the network variable to be updated before I send out the Rpc?
Networklist is the chosen variable btw
In OnNetworkSpawn() you should have all the updated values. You shouldn't be sending anything from Onclientconnected
Also NetworkList has an OnListChanged event you can listen for
Are you using lobbies to connect to the relay or are you manually entering the relay code?
This isn't being sent fron onclientconnected. The rpc is being called from the server much later after the player already joined
im using lobbies
Ig I could try OnListChanged , but if im adding a bunch of elements to the list on the server, wont the client get a bunch of events for list updated?
I would only want it to be notifed when the final element is added
It will only update once per tick.
So all the clients are connecting to the lobby? Is StartClient() returning an error?
no. i actually managed to fix that part, but im still getting the errors
Sadly it looks like the event is called multiple times, which is what I feared. What I might try doing is making a temp networklist, add all the items to it, and then set the global networklist to the temp one
Looks like that doesn't work either
Prob since I can't do smt like this NetworkList<int> test = new NetworkList<int>();
What is your favorite network platforms like photon pun and mirror
NGO is pretty cool cuz u get features like lobby and relay integrated pretty well and free up to a pretty generous limit
Idk if it's really production ready tho
There are a couple of quirks here and there and the community is small (literally just this channel and maybe #archived-unity-gaming-services )
But at least we have lord @sharp axle to help us out 😂
I think it's ready enough. Lethal Company is using NGO and it's one of the bigger games of the year
Oh interesting I didn't know that
Also the UGS services are framework agnostic so you use ohoton or mirror with them just fine.
Populate a regular list first then dump that into a network list when it's ready
How do I dump a regular list into a network list?
can I do smt like networkList = new NetworkList<int>(regularList);?
I am like 80% sure you can. But you might just have to loop through regular list and networklist.add()
But that would still cause the individual OnListChanged events to be fired for each item added
Looping through the old one anywya
You shouldn't be getting multiple change events per frame. At least not on the clients.
Wdym per frame?
void Awake()
{
chosen = new NetworkList<int>();
chosen.OnListChanged += changeEvent =>
{
Debug.Log("list changed!");
};
}```
in another functiuon being run on the server:
foreach (Transform section in sections)
{
List<Transform> glass = new List<Transform>();
foreach (Transform trans in section)
{
glass.Add(trans);
}
chosen.Add(Random.Range(0, glass.Count));
}```
this is printed like 20 times i think
Does that happen in the clients as well?
oh wait
ive been testing only on host
let me try it on the client 🥱
yup it also happens on the clients
In any case, I was able to come up with a different way to accomplish the same thing using numeros events
So for now this issue is solved
in 2024 which toturial i should start for networking in unity engine ?
I have a question: I was following a tutorial that making game server. The chapter 6 example has render manager and it is peer to peer. But the chapter 8's example is a Server-Client model without render manager. So I'm thinking how to debug and check the sent and received msg from client in the case of chapter 8? The tutorial doesnt mentioned it.So I'm kinda confused.And advice?
What is the program like that put in dedicated-server? Is that an exe? Does it has any render or window? How do I debug it?
Check the pinned message here for resources. But so far the best video tutorials would be Code Monkey's big Multiplayer video or Jason Weimann's Multiplay Mastery cource
Headless servers will have a console window but the standard way is to have a log file that it's printing messages to.
Also forgot to mention here that we have a Unity Netcode discord server. I don't think I can post the link here but its also in the pinned message here
😱
can someone help me there i am too dumb 🫠
Is that code running on the player? You don't normally need both network variables and RPCs. Just have the server run Kill() when Health.Value reaches 0
yeah ok true
is the damage code correct tho? just to be sure
Health.Value is either going to have server write permissions or owner write permissions. So you will only be able to change the health value either on the server or the client but not both
uhm sooo... what does that mean now, will it not work?
It should still work but you'll get errors when the server or the client tried to change the health when it doesn't have permissions to
NullReferenceException: Object reference not set to an instance of an object
Photon.Pun.PhotonTransformView.Update () (at Assets/Photon/PhotonUnityNetworking/Code/Views/PhotonTransformView.cs:61)
Has anyone enocuntered this photon Error.
Is the console seperate from the game server program? If seperate,how do they interact? I did some search yesterday and found there seems also a solution like remote debugging server... I'm not sure....
No, it's not separate. Remote debugging is a whole different issue. There are network profiling and analytics tools you can setup if you need realtime statistics
Thx!I c
Another questeion : Why do we need bit stream when read and write the pack? Is it possible to make a bit stream system in C#? What about BitConverter Class?
Any cases that write some bits to pack like 5 bits or 13 bits instead of byte(8 bits)?
uint32_t inBitCount )
{
uint32_t nextBitHead = mBitHead + static_cast< uint32_t >( inBitCount );
if( nextBitHead > mBitCapacity )
{
ReallocBuffer( std::max( mBitCapacity * 2, nextBitHead ) );
}
//calculate the byteOffset into our buffer
//by dividing the head by 8
//and the bitOffset by taking the last 3 bits
uint32_t byteOffset = mBitHead >> 3;
uint32_t bitOffset = mBitHead & 0x7;
uint8_t currentMask = ~( 0xff << bitOffset );
mBuffer[ byteOffset ] = ( mBuffer[ byteOffset ] & currentMask ) | ( inData << bitOffset );
//calculate how many bits were not yet used in
//our target byte in the buffer
uint32_t bitsFreeThisByte = 8 - bitOffset;
//if we needed more than that, carry to the next byte
if( bitsFreeThisByte < inBitCount )
{
//we need another byte
mBuffer[ byteOffset + 1 ] = inData >> bitsFreeThisByte;
}
mBitHead = nextBitHead;
}``` This is the code that in the sample project write in C++. The project C++ server and C++ client. I wanna move some basic part of client to C# and make game with Unity.
{
uint nextBitHead = mBitHead + inBitCount;
if(nextBitHead > mBitCapacity)
{
ReallocBuffer(Mathf.Max(mBitCapacity * 2, nextBitHead));
}
uint byteOffset = mBitHead >> 3;
uint bitOffset = mBitHead & 0x7;
byte currentMask = (byte)~(0xff << (int)bitOffset);
mBuffer[byteOffset] = (byte)((mBuffer[byteOffset] & currentMask) | (inData << (byte)bitOffset));
uint bitsFreeThisByte = 8 - bitOffset;
if (bitsFreeThisByte < inBitCount)
{
mBuffer[byteOffset + 1] = (byte)(inData >> (byte)bitsFreeThisByte);
}
mBitHead = nextBitHead;
}``` This is what I convert to C#. Am I doing right? Or maybe not nesecessary to do this? I'm not sure... Any suggestions?
at what point should i start learning networking
I would say after you are very familiar with single player development
The unity Netcode sometimes spawn players in Vector3.zero position.
Even I debugged and checked passed position but still many times it just spawns player to zero position.
I tried it with SpawnAsPlayerObject and InstantiateAndSpawn
Both do same thing.
Can someone help me fix rhis
show code?
Sure
I calculate random pos and rot and pass it in here. I debugged and it always passes non zero pos and rot. But Unity SOMETIMES spawns player in zero
public void SpawnClient(ulong clientID, Vector3 pos, Quaternion rot, bool isClientOwner)
{
if (isClientOwner)
{
NetworkObject.InstantiateAndSpawn(
playerPrefab,
NetworkManager,
clientID,
destroyWithScene: true,
true,
forceOverride: true,
pos,
rot);
}
else
{
NetworkObject.InstantiateAndSpawn(
playerPrefab,
NetworkManager,
NetworkManager.ServerClientId,
destroyWithScene: true,
false,
forceOverride: true,
pos,
rot);
}
}
@crude ridge here
where do you call SpawnClient from?
Its called in my Random Pos and Rot calculator script. But the issue is in this one. Because the debug comes correct inside this
spawnPoint = new Vector3(x, hit.point.y + player_spawn_height_offset, z);
Utils.DebugLog("[SERVER] Spawning client " + clientID + " at spawnpoint " + spawnPoint + " found in " + attempts + " attempts");
Quaternion rotation;
if (randomRotation)
{
rotation = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
}
else
{
rotation = fixedRotation;
}
SpawnClient(clientID, spawnPoint, rotation, true);
why do you pass in NetworkManager as a parameter?
these are all the paramters of the InstantiateAndSpawn function
It wants it
InstantiateAndSpawn(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)
Yes i am using that thats why
I even tried it with SpawnAsPlayerObject and behaviour is same in both
It only does it Sometimes not all the time
The player snaps to zero position
sometimes
Its need idk why
umm thats weird, i dont think thats the correct function. is this in the networkmanager?
is this correct?
So there is also other method
NetworkManager.SpawnManager.InstantiateAndSpawn(
playerPrefab.GetComponent<NetworkObject>(),
clientID,
destroyWithScene: true,
isPlayerObject: true,
forceOverride: false,
pos,
rot);
Can anyone explain forceOverride in simple terms.
"forceOverride": Whether you want to force spawning the override when running as a host or server or if you want it to spawn the override for host mode and the source prefab for server. If there is an override, clients always spawn that as opposed to the source prefab (defaults to false).
When to use bit level to read and write packect in network?
Damn, will be NGO over suitable for fast - paced games like FFS shooters or I am forced to wait until Dots is production ready and then use netcode for entities
Is there any way to make networking work for LAN networks (so for devices connected on the same wifi network) without any relay or lobby? Any good tutorials? I have followed a few threads here and there but it doesnt work and I feel i'm not googling correctly cuz I dont get many clear answers
Same for me, it sometimes work and sometimes dont
The problem persists
I found my problem on this link and this hasnt fixed since 2022
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1249
just experimented a bit (Friend of @vital sapphire , working together and sitting next to him) network for gameobjects on LAN works if you set the host devices IPv4 adress as the adress for both players
now i "just" gotta figure out the ipv4 adress
I do set Joiner client address same as host but it still does not connect
it just stuck on Start Client
and does not get connected to host
You can use Network Discovery
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
You will need to create your own client prediction system. Its doable in NGO just not built in
hey guys, does anyone know of a VoIP solution that uses the games host/server to host the VoIP locally instead of on an outsourced server somewhere else? I'm a bit concerned about running up a bill for hosting VoIP servers and was wondering if people could just do it themselves while hosting games :/
But NGO isn't able to have more than 16 players?
There is no player limit in NGO
So the server won't crash if there will be 80 players?
Depends on your server specs. If it crashes it won't be because of NGO
That's good news! Thanks 😁
hey guys, is there a way to RPC audio clips for a voice chat solution?
for this game, the multiplayer works if my friend hosts but it doesnt if I host :( We use use the correct IP adresses and ports.. is it a known issue that some devices cant be the host for networking?
are you gonna attempt to capture audio for a microsecond and using rpc send and play it to every player?
you could always look into Vivox too
honestly maybe but i do not know if it is worth it
yeah but does vivox host the voice chat in the same server that is hosting the game itself?
I mean basically just cut the microphone input into 500 or so millisecond chunks and RPC them once every half a second
or 25 server ticks
You'll want to look into WebRtc if you want p2p voip
thanks!
no idea honestly
But yeah if anyone has any suggestions for this, all I can think of is maybe it being a firewall issue on Lemur's pc
Vivox has a rather crazy 5k CCU free tier
That sounds like a firewall issue if it works one way but the other. Just make sure the host sets it's listen address to 0.0.0.0
how much is that though?
I mean
say if I have 4800 Hz audio
to save money
is there any way to hard-code it that you cant go over the free tier though? realistically you wouldnt go over most free tiers with small games but still :/ i'd rather have my game to stop working then to pay tbh
I believe that puts you in the top ~~100 ~~ 200 games on steam by player count
damn, maybe I will use vivox then
its just kinda internally frustrating to know that my game is dependant on a proprietary doohickey tho :/
listen adress 0.0.0.0 wasnt working so made a custom script where you get the local IPv4 address and use that as a "room code" 😅
just have a field you can copy paste the IPv4 address of the host and connects that way
unity just screams at me the endpoint / server adress is invalid
oh figured out small mistake, I was pasting the IP from discord and it had a "newline" thingy after it hence why the IP was invalid
still not able to join though, failed to connect
Have you tried the Network Discovery scripts I posted above?
Networkdiscovery was for the new depricated Unet no?
when i clicked on it i also saw this so i thought it was UNet specific
while im using unity transport
No it works with NGO
oh shoot lemme check it out ^^
thanks upfront
Shouldve looked at it sooner! the server discovery works excellently
though my friend hosting still is not working
I'll just leave it as a firewall thing and wait with it until i can try out on someone elses computer 😅
Thanks still though
apparently my laptop is the problem, we got another person to test and it works on their laptop as well

What is the best way to initialize Player network objects spawned with dependancies? NetworkManager spawns Player, but what if my player has a dependancy for ActionController, I don't want to create multiple ActionController objects for each object spawned (ie having it as component), I just want to have a single instance and just inject the dependancy where I need it
TLDR; Whats the best practice to inject dependancies into Player gameobject which gets spawned through NetworkManager
Should I just use Zenject for DI, and not think about it?
one way to do this is to register a custom prefab handler class for your player (NetworkManager.PrefabHandler.AddHandler), then you can do whatever you like in your overridden Instantiate method
If its a separate object just leave it local unnetworked in the scene and have the local player object find it with FindAnyObjectOfType<>. Or you can have the player instantiate it if its a prefab. Or just use Zenject if you are more familiar with it
I have an application based on firebase database, now I want to change the database of this existing project. I already replaced the json file with my new one i created. The leaderboard is clear when i open the game but now after i play the scores and names don't get updated.
please can you elaborate?
Thanks for this
@sharp axle Do you have any solution for this
It's been months and I haven't figured out
You can either spawn it with server authority, set the position then change ownership to the client. Or just use a clientRPC to tell the client to move it after it spawns
But I had thought that particular bug of it being one frame at origin had been fixed.
Yeah that's the only work around for now
Even the RPC couldnt helped. I tried debug. And position was fine till start and it just snapped to 0,0,0 in second frame of Update
This is happening in Host
Sure, the google-services.json file you import into your project may have a missing dependedncy, so under "project_info" object you add "firebase_url": and specify your firebase realtime database url
alright
Is it not possible to use an Interface for NetworkSerializable Data? I Got this Interface : public interface ITriggerData : INetworkSerializable and a concrete Implementation public struct MouseClickData : ITriggerData which implements public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter. But When I try to use it in my ServerRPC I got this failure: error - HandleActionRequestServerRPC - Don't know how to deserialize binrev.ITriggerData. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. Why? BTW, ITriggerData is empty, contains nothing.
you need to use the concrete types for RPC params, or how else would it know which one to instantiate on the other end?
Ok, that's an argument.
I had this working for multiplayer before but now that I've added propper character movement (not just wasd) it does this
this is the script moving the player https://gdl.space/sodacinuso.cs
uh it's me again, i have a shipai movement script with an interface for mod support and stuff
mod interface:
NetworkVariable<Vector3> Waypoint { get; set; }
ship ai script:
public NetworkVariable<Vector3> waypoint = new NetworkVariable<Vector3>(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
public NetworkVariable<Vector3> Waypoint
{
get { return waypoint; }
set { waypoint = value; }
}
but i can't change the waypoint in my selector script:
mod = ship.GetComponent<Mod>();
mod.Waypoint.Value = newWaypointPosition;
i get an error
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.NetworkVariable`1[T].set_Value (T value) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Runtime/NetworkVariable/NetworkVariable.cs:65)
again, maybe i am just dumb.
You cant put network variables in an interface. The network manager has no idea which object to send the messages to.
how can i solve this then ._.
Put the network variable in the Ship network behavior. You should still be able to grab the waypoints from the Mod interface and set the Value of Network Variable
You can install 1.8 by name in the package manager and specify the version
I have a byte array declared as private in MyUDPClient.cs. I think I shouldnt declare it as public? I have another BitStream.CS trying to access the array and convert it to bits. But I can't since it's private. I'm confused how to design it...
I have a question how do I execute a commande for all my clients ? When I am the host ?
If you are using NGO then sending a clientRPC will work
If I send a clientrpc then if I put the value in a playerprefs I can use it after with the right playerprefs name ?
How do I call a clienrpc btw ?
Host acts like a client and a server so if the host calls a client rpc it will broadcast the message to itself and other clients.
A clientrpc can only be called by a server. But Clients can trigger server rpcs that will trigger a clientrpc.
There is some example code if you want at this link:https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/clientrpc/
ClientRpc and ServerRpc are legacy features of Netcode for GameObjects and have been replaced with the universal RPC attribute. This documentation is for legacy use. For current projects, use Rpc instead.
Thank’s a lot for telling me all this I was a bit lost because it’s my first time
Of course, any time
@sturdy cloak can i use a playerprefs to send data to my server ? or should i use another system ?
You can save data to player prefs. Just know that those are stored locally on the client in the clear so it's easily hacked. The more secure option is to use Cloud Save or some other remote storage solution.
ohhh it's locally stored ok so to set a player class like being a sniper it could work ?
Because i'd like to :
- When i start the lobby queue it saves the current loadout
- The host get all the datas from the clients
- When the game start the host send back all the datas to the clients like (Weapons, gadget, throwable)
But i don't know how to do it
Okey so the way i would do it (im not sure if this is the best way).
I would make a NetworkList<CustomPlayerData>.
The customplayerdata will hold all the needed data and it has to be a struct and to hold only primitive data like ints,fixedstrings,floats etc (clientId, playername, loudout etc...)
Then than on Start Client the client will send their data through a server rpc to write to the list and add themselves to the list, now the host( server) has all the data sent from the client. All the clients will listen to the OnValueChanged for the NetworkList and that way whenever something changes for the NetworkList they will know what to do.
PlayerPrefs would be good way to store the data locally but yeah Cloud Save is the way to save data.
If your game is a casual one that hackers will not hack on its a okay approach
i don't want to make a casual game so i see what you mean
You need to give every item in you game an ID. Then your loadout can just be a list of IDs
yeah every items have an ID
Hello. I'm looking to implement a online database for my project but am unsure what to use exactly. Any recommendations?
Right now I'm looking into the Unity > Gaming Services > Cloud Save
That sounds about right and use Unity Economy for any kind of online currency.
Depends entirely on what you want to store and how the access patterns on that data look like.
what is considered the best solution for having players own items in a game (like an item server)? I'm making a multiplayer ccg (using NGO) and want to have a system where players can collect cards and also need to be able to communicate with my game in an intuitive way. i need to be able to associate data with the players in a way thats persistent and doesnt allow for clients to modify their items in any way
You can either use the Economy system or you can save what players own in Cloud Save or other remote database
steam multiplayer is not free, never was, (lot game dev say free-mp-valve its wrong), wish descriptions of those who have real world example calculation of a multiplayer games per anno, large community joins lobby, but 50% off than expensive, min pricing $.99 + transaction free starts by $.49 50% to $4.99 at 90% https://partner.steamgames.com/doc/store/pricing #steam-Lobby$
This is for pricing on the store. What are the rates for using Steam P2P?
Lobby is, every time without fail, throwing me a 404 on QuickJoin
404 is usually a web error. Make sure you still have internet or double check any firewalls you have
I have allowed it through my firewall and i certainly still have internet
will quickjoin give a 404 if there are no lobbies to join?
It might. I didn't think it was a 404 error though.
The status may be 404. The error code will be more specific
https://docs.unity.com/ugs/en-us/manual/lobby/manual/lobby-error-messages
Is it possible to use Unity Gaming Service to store data structures like serialized variables?
Yes, it has a service for storing arbitrary data. However it’s your responsibility to make the data conform to the service they provide. Such services are typically a key-value database or a wrapper around S3 file storage. none of them can deal with relational queries (those don’t scale horizontally).
I believe the standard practice is to convert the struct to json then save that string
Thanks
I have a super simple netcode game which has two buttons "create lobby" and "join lobby". When I run two clients with ParrelSync, one creates the lobby and the other joins, and both are switched into another scene. However, when my friend tries to join the lobby from his computer, he does join the lobby, but his client doesnt switch into the game scene. Why might this be?
I have spent a few days looking for solutions and would much appreciate any help.
Code here: https://forum.unity.com/threads/loadscene-works-locally-but-not-over-network.1550588/
You need to also create a Relay to join. StartClient() is actually connecting to the host there
Can you give me slightly more direction? Will this be ~1 line code addition or smtg more complicated?
I am looking up Relay now--the lobby tutorials I followed didnt seem to use it.
Yea, Lobby is a separate service. Its more than one line to create a relay. But its not that much more complicated. You will need to create and store the Relay Join Code in the Lobby Data
Interesting. Any idea why it works when I run both instances locally w parrelsync?
You are connecting to yourself in that case
what is the easiest way to make a multiplayer game? im making a map strategy game and rn I have programmed some interactions between the player script and the map. I just need to make it so that each player controls a player script
I started following this one tutorial, but it failed to download the packages from git
There is no easy way to make a multiplayer game
use unreal and make a first person shooter with the builtin framework
In unity, use any game object based framework. NGO/mirror/fusion/etc.
I dont want to make a first person shooter. I am making a 2d map strategy game
how much better is unreal than unity for a multiplayer fps game anyway?
it’s not necessarily better, it’s just preconfigured in a way that you basically have a (boring) networked fps right out of the box
Making anything else is extra work.
all popular game engines are selling the fantasy that making games is easy (if you use their engine), but that fantasy gets a hard reality check real quick when you start with multiplayer.
so while to an experienced network developer its probably relatively easy to make a simple 2d strategy game, there is just no way to cram all the necessary knowledge into a tutorial that gets you anywhere.
bruh literally all I want for the time being is to make it so that when they click the map, in changes the color of a strategic area to the color of the player's country
best thing you can do is take one of unity's (or others) network example project and study it until you really understand what they are doing, then adapt that to your game
You need to start with the very basics. Pick a network framework and go through their basic Hello World tutorial. There is no shortcut here. You are going to have to relearn a lot.
Hello everyone, today I wanted to share with you guys a tool that I have been using to test my multiplayer game inside the unity editor. Hope you guys enjoy it.
ParrelSync Repo: https://github.com/VeriorPies/ParrelSync
Discord: https://discord.gg/sNuVdqr8tR
I am following this tutorial, but I am lost as to how he got that little window in the top right corner
You'll probably need to go back to his channel from the begging to see what plugins he is using. That window is not a standard part of NGO.
how do i use a transform as a network variable
@mint anvil
ugh
yes life is tough, i am currently trying not to commit seboku creating a VR multiplayer game
You can use a Vector3 as the position. Or you can make a custom struct if you really need position, rotation, and scale.
Just had a thought about using NetworkVariable<(Vector3, Vector3, Vector3) but I have no idea if tuples will work
yeah i have the rework/code everything, i thought this would work ._.
@sharp axle how is that possible that matchmaker is sending server informations to clients before i set ReadyServerForPlayersAsync since the call is async?
Clients connect before the awaited spawnedCardBattleBoardManager.Inizialize function
does anyone know what could have caused this error in the image?
ArgumentException: Serialization has not been generated for type System.UInt64[]. This can be addressed by adding a [GenerateSerializationForGenericParameterAttribute] to your generic class that serializes this value (if you are using one), adding [GenerateSerializationForTypeAttribute(typeof(System.UInt64[])] to the class or method that is attempting to serialize it, ... The rest of the thing states that the error comes from a NetworkVariable. And doing the Generatewhatever things does not resolve my problem.
The potential source i belive is this, cause this is the only network variable with a ulong
public NetworkVariable<ulong[]> MetaUserIds = new NetworkVariable<ulong[]>(new ulong[0] {}, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
Is it not possible for network variables to store ulong arrays?
Maybe is not networkVariable but something like networkArray or list?
i dont use any NetworkLists in my own code, so i doubt its the source of the error
in fact maybe networkVariable can not accept arrays?
You can not
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/arrays/
Arrays of C# primitive types, like int], and [Unity primitive types, such as Vector3, are serialized by built-in serialization code. Otherwise, any array of types that aren't handled by the built-in serialization code, such as string], needs to be handled through a container class or structure that implements the [INetworkSerializable interface.
I'll have to doublecheck the matchmaker lifecycle. I don't know if it automatically sets the server to ready for players or not
i discover that the serverClient CloudCode RunModule function is causing the issue
the moment that i commented it everything was awaited properly
seems like is not really awaited or there is something that is not working with it
Ah ok, i believe i got it to work by manually implementing dome logic for it.
public struct MetaSessionUserIDs : INetworkSerializable
{
public ulong[] Ids;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsReader)
{
var reader = serializer.GetFastBufferReader();
var length = reader.Length;
if(length == 0) {
Ids = new ulong[0];
return;
}
if(length % 8 != 0) return;
if(!reader.TryBeginRead(length)) return;
Ids = new ulong[length / 8];
for (int i = 0; i < Ids.Length; i++) reader.ReadValue(out Ids[i]);
}
else if (serializer.IsWriter)
{
var writer = serializer.GetFastBufferWriter();
writer.TryBeginWrite(Ids.Length * 8);
for (int i = 0; i < Ids.Length; i++) writer.WriteValue(Ids[i]);
}
}
}```
This is something important i need to know but i can not found informations about it
is it not possible to call a ServerRpc from a client OnNetworkSpawn ? I sometimes see Trying to send ServerRpcMessage to client 0 which is not in a connected state
nevermind, call came from somewhere else 😦
I'm really forgetting some core things, but I can't figure it out
But I have a script Player_Stats on my player prefab that gets spawned by the networkmanager itself. Now this holds name, icon, mesh, etc...
Now I have an Input field and I want whatever you type in there to change the name inside the Player_Stats script from your own player prefab.. now how do I get a reference to this player prefab? It's been a long day and I can't make any sense of the forum posts
Finding your own player prefab is NetworkManager.LocalClient.PlayerObject
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/#finding-playerobjects
Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:
ahh my script was MonoBehaviour instead of NetworkBehaviour 😔 I was already finding it very weird something simple as that didnt work
thanks!!
Hey ! I want to play a particle system for all of my clients depending of how many player are in a trigger collision should i do this ?
void StartRareServerRpc()
{
Debug.Log("StartRareClientRpc");
StartRareClientRpc();
}
[ClientRpc]
void StartRareClientRpc()
{
Debug.Log("StartRareClientRpc");
particleSystem.Play();
}```
and in my script
```List<GameObject> players = new List<GameObject>();
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
players.Add(other.gameObject);
if (players.Count >= 2)
{
StartRareServerRpc();
}
}
}```
I did put my script as networkBehaviour and i put an network object on my gameobject
having an issue on my client where they can't see the animation playing
Are you using a Network Animator
https://docs-multiplayer.unity3d.com/netcode/current/components/networkanimator/
The NetworkAnimator component provides you with a fundamental example of how to synchronize animations during a network session. Animation states are synchronized with players joining an existing network session and any client already connected before the animation state changing.
I have come across my first major hurdle and I'm really struggling with understanding why what happens, happens 😄
I have a class PlayerController : NetworkBehaviour, this is the player object that spawns in the scene.
Notably, I have a network variable
private NetworkVariable<ulong> steamId = new NetworkVariable<ulong>(writePerm: NetworkVariableWritePermission.Owner);
I set it on Start like so:
private void Start()
{
if (IsOwner)
{
steamId.Value = User.Client.Id.id.m_SteamID;
}
}
Then, I call the following code to get avatars:
private void OnSteamIDChanged(ulong oldSteamID, ulong newSteamID)
{
SetPlayerAvatar();
}
public void SetPlayerAvatar()
{
Debug.Log(this.steamId.Value);
CSteamID steamId = new CSteamID(this.steamId.Value);
Friends.Client.GetFriendAvatar(steamId, avatarTexture =>
{
if (avatarTexture != null)
{
_icon.texture = avatarTexture;
}
});
}
Here's the weird part... on a client, it works fine. Both avatars are visible.
On the host, only their own avatar is visible. Why is this? O_o
The steam id value on the host for the connected client is 0. Only one avatar is visible on the host's PC - their own.
Change Start() to OnNetworkSpawn() so the network variable will sync
Tried that too, didn't help sadly.
The host might need to call SetPlayerAvatar() manually.
well i didn't put an network animator on it so i need to put one on to make a particule system work ?
No that's just for Animations. For particles you just need an client RPC to call Play() on it
so in the code i did it won't play for the client do you know why ?
I'm trying to think of a way to get around a certain issue with NGO, wherein gameobjects with a modified hierarchy are unable to spawn on other clients
has anyone managed to find a way to get round this?
no, if the particle system is enabled the .Play() will run it
You have to spawn the prefab then disable any children or components with client RPCs
I was thinking more in the context of a weapon customiser sorta thing
I guess the easiest way to do it would be just disabling the unused components?
Yea. you are not going to be able add components
anyone know if its a big deal to use the way ive always used to move characters (setting velocity and using a dynamic rigidbody) when doing multiplayer?
Syncing physics can be kind of tricky depending on your type of game.
if its client-authoritative and you just set the non-local-players rigidbodies to be kinematic, it's not a big deal
again, i want to jump from a bridge
i have a network transform to set a target of a spaceship, because transforms don't work as network variables, and i have to use network variables because everything runs on the server and otherwise the client can't set the target of the ship, but how can the ship now move to the target -> network transform in the code if i can't get the position?
hello,
I'm creating lobby with Fishnet and it works great. clients are spawned in the lobby, host clicks on start game and both clients go to game scene. however, I can't figure out how to spawn the player. if there is any guide about this, I'd really appreciate it.
not sure i understand this, if you're using a NetworkTransform, what's in your network variables? what do you mean by "move to the target -> network transform" and which position can't you get and why?
For example i want to assign a target transform (different parts of enemy ships) but I can't do that, because transforms are not supported as network variables, so i thought of using a network transform as a reference, but that doesn't work like a normal one (has no values like a position) for the ship to move to / target
can you give them some other kind of simpler identifier rather than trying to sync the references? if you know the layout of each spaceship on client and server, you can probably give them just a numeric id or something like that
Uh i am confused
if i'm understanding it right you want to set a reference to a particular transform within the ship? so rather than setting a variable to the transform, set it to an id value like "engine 3" and let the other client look up where that transform is on their end
uh, wait, every network object has an id right? ah idk why is this all so complicated
network objects do and you can send/receive NetworkObjectReference to refer to them, but i'm assuming the transforms you're trying to refer to here are not all separate network objects, they're probably children of the spaceship?
yes they are
how about making an array of transforms on the spaceship script? then the "id" you send is just the index in that list of the transform you're targeting and it's super easy to look them up
i- ... 😵💫
but what is with in general to set an enemy ship as a target to follow/attack
NetworkObjectReference sounds like what you need?
can i use that as a network variable
yes, it's basically just a wrapper around the object's id
ok
but how can i get anything out of it if it's just an id, like get the object it is on

There is an implict operator to and from GameObject that makes things much easier
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#implicit-operators
Brief explanation on using NetworkObject and NetworkBehaviour in Network for GameObjects
@sharp axle i swear without you I would have given up 100 times already
Hey everyone, I am currently working on a 2D roguelike multiplayer game and am intending to upload it onto steam. I don't really have experience in game development and mostly self taught myself and made games for fun. Im reaching out to get someone's opinion about the multiplayer aspect of the game. Right now i am using Photon's PUN Hosting for my game and so far has been working somewhat. I would just like to get an opinion if i should continue using photon or maybe switch to some other method to host multiplayer because i thought about it for a little longer and came to realize that photon might possibly not be the best option due to future additions to the game such as things requiring steam profiles and players not hosting there own lobbies that would accommodate their ping and possibly much else. I just don't know if im stepping in the correct direction with the multiplayer as it is something i've never done at all and have no knowledge, would something such as a custom dedicated server hosting be better for my game or what is your take on it?
You might want to look at updating to Photon Fusion but other than that there are not really any wrong answers. Most options just come down to budget
out of all possible solutions what would u choose if you didn't have insane coding skills.
Its not even about skill. Dedicated Server or Player hosted is almost the exact same code. I use a Relay service to keep costs down. But when you need security for PvP or in app purchases or whatever, dedicated server are kind of your only option
uuh am i missing something
Make sure you have NGO 1.8.1 installed. You might have to install it manually by name
oh-
ok..
Hey I have a small question I made a network list of ulong player ids and I have some memory leak warning that just pop up do you know why ?
can you show the code and the error?
yeah here is the error :
Unity.Collections.NativeList`1:.ctor(Int32, AllocatorHandle) (at .\Library\PackageCache\com.unity.collections@1.2.4\Unity.Collections\NativeList.cs:116)
Unity.Netcode.NetworkList`1:.ctor() (at .\Library\PackageCache\com.unity.netcode.gameobjects@1.8.1\Runtime\NetworkVariable\Collections\NetworkList.cs:14)
RareObjectScript:.ctor() (at Assets\RareObjectScript.cs:11)
here is the code :
{
new ParticleSystem particleSystem;
public NetworkList<ulong> playerIds = new NetworkList<ulong>();
public Material material;
public bool isAlreadyTaken;```
The 11 line is the network list
oh right you're creating the list in the constructor and never freeing it, NetworkList uses a native allocation in the background so you need to make sure you call Dispose when you're done with it
you probably want to create it in Start or Awake and dispose it in OnDestroy
well i never destroy the gameobject exept when i finish the game
the warning is probably only happening in editor then?
maybe how can i check if the error is still here in build ?
just run a build and look at the logs
I'm pretty sure NetworkList is supposed to self Dispose. I might be wrong though
actually yes it's a networkvariable so it does automatically iirc, but only in OnDestroy? so instances created in the editor might not
where do i see my logs for build game ?
find the log file in the build folder or connect from the console
doesn't seems to have the error in build
i just changed the number in the manifest.json xD
Is NGO suitable for small scale open world games, like an MMORPG?
Oxymoron detected
NGO can make the sync bit of a small world smorpg but it doesn’t give you any of the database stuff. Small world == no world partitions/phasing/instancing.
the complexity is still there even if you have just a few ccu
Very large worlds will require a lot of extra work but it's not impossible. There are still a lot of systems that you would need to make from scratch.
Any frameworks that help with this?
I'm not afraid to write code but I don't want to reinvent the wheel if I can avoid it
Can someone help me?
I keep getting this error:
Client is not allowed to write to this NetworkList
I've tried ServerRpc/ClientRpc and changed the Write Permission to both server/owner and I still get it.
there are no mmo frameworks, it’s an inherently custom problem where you have to mix and match multiple middlewares.
You are going to need to post your code here. By default only the server has write permissions. You can only change that to owner permission.
There are some assets like uMMORPG on the asset store but it's more a template than a framework. Plus I think you are stuck using Mirror with that one.
I figured it out. I had to put if(this.gameObject.GetComponent<NetworkObject>().IsLocalPlayer) in a bunch of places.
You can just do if(IsLocalPlayer)
I'll keep that in mind. Thank you.
Hey there => I'm using NGO. I add children to a prefab with a network object at runtime, then spawn that prefab but the Children are not spawned on clients. Is it something I'm not supposed to be able to do because the template prefab in the PrefabNetworkList doesn't have these children in it ?
yes, NGO has no awareness of any changes in the hierarchy like that, you'd have to tell the clients to spawn the objects too with an RPC
and secound script
I would go as far and say that NGO has no awareness at all not even prop initialization 😥 I feel like it's not made clear in the documentation
using System.Collections.Generic;
using UnityEngine;
public class gamemeneger : MonoBehaviour
{
public void SpawnGracza()
{
Vector3 pozycjastart = Vector3.zero;
GameObject mojGraczGO = PhotonNetwork.Instantiate("Gracz", new Vector3(58.29f, 0f, -837.0149f), Quaternion.identity, 0);
mojGraczGO.GetComponent<FirstPersonMovement>().enabled = true;
mojGraczGO.GetComponent<Crouch>().enabled = true;
mojGraczGO.GetComponent<Jump>().enabled = true;
mojGraczGO.transform.Find("First Person Camera").gameObject.SetActive(true);
GetComponent<PhotonView>().RPC("SpawnujGraczaRPC",PhotonTargets.AllBuffered, gracz.mojgracz.nick, mojGraczGO.GetComponent<PhotonView>().viewID);
}
[PunRPC]
void SpawnujGraczaRPC( string nick, int pvID, PhotonMessageInfo pmi)
{
GameObject nowygraczGO = PhotonView.Find(pvID).gameObject;
nowygraczGO.name = "Gracz_" + nick;
gracz gracz = gracz.ZnajdzGracza(pmi.sender);
gracz.playerObject = nowygraczGO;
if (gracz.team == Team.BLUE)
{
gracz.playerObject.transform.Find("Man_Full/Man_Cloth_Face_Mesh").GetComponent<Renderer>().material.color = Color.blue;
gracz.playerObject.transform.Find("Man_Full/Man_Balaclava_Mesh").GetComponent<Renderer>().material.color = Color.blue;
}
if(gracz.team == Team.RED)
{
gracz.playerObject.transform.Find("Man_Full/Man_Cloth_Face_Mesh").GetComponent<Renderer>().material.color = Color.red;
gracz.playerObject.transform.Find("Man_Full/Man_Balaclava_Mesh").GetComponent<Renderer>().material.color = Color.red;
}
if (gracz == gracz.mojgracz)
{
gracz.playerObject.transform.Find("Man_Full").gameObject.SetActive(false);
}
else
{
gracz.gameObject.transform.Find("Man_Full").gameObject.SetActive(true);
}
}
}```
the person who enters the game does not see the players who entered earlier, why?
if you want w can dent script: gracz
It does not. It will spawn what is in the network prefab list then update any network variables and that's it.
Is there any possible drawback of passing ownership of a game manager (a netcode manager [manages current round player, their current round action, etc])?
I would assume private variables and methods are different between what is currently in the Host and the current Owner unless they are changed in a ServerRpc call, is that correct?
I ask because I was trying to do server rpcs but without ownership of the game object (the game manager in this case) it fails, so after searching I reached two ways to solve it: set all server rpcs as RequireOwnership = false (plus checking if the sender is the current player) or changing the owner every turn between players. I was leaning to changing the ownership because it would look cleaner, but I'm pretty new and not sure if it's safe passing ownership of an important netcode manager to a [not trustworthy] client.
Hi. How can I sync the change of a string so it's the same on all clients? I have 2 players and each will generate a code based on their actions.
a NetworkVariable with a FixedString ( https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/ ) should work?
I'll look into it. Thanks
Look into using custom messages. Though there is nothing really wrong with setting ServerRpcs to Require ownership = none.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages/
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
thank you, I'll read about it
❤️ kb/s send to host and <4 kb/s send from host is good? This is rough estimates for 2 peer to peer players, so if there are 5, the host would receive 10-15 kb/s and send out around 4 kb/s to players. keep in mind this is done in webrtc, was really trying to keep the bandwith low, but ran into some issues where i need to increase it a bit, so i'm wondering if these numbers are fine.
outgoing data is typically player_count ^ 2, all players need to be updated with the state of all other players
why?
because you want players to see what other players are doing right?
atleast for positions, host doesnt relay instantly the data, it pools and sends it as one message
depening on your type of game ofc, if its "real time" or "live", its n^2
i still dont see why it has to be
it doesnt "have to" be, if you only update players that are in close proximity, ofc the number goes down, but you can't get out of O(n^2) data unless your players can't see each other
lets say we ignore all the other stuff like player joined, player left, player died, etc. etc. just position. I take all the position data, serialize it, turn it into a byte array, send it to host. Host adds that to a list of pooled position data, and sends it out every X ms to each player
oh yeah
now i see it xd
nevermind, yeah for host it*s n ^ 2
but for peers its n
in true peer to peer, its n^2 for all peers, but you don't have p2p you have host-based networking
which is the same as server based, with more annoying code
true
Can someoen help? Im trying to add servers to my game, but everytime I try to join a server it pauses the game and gives me this error
Hi im watching
PHOTON FUSION 101 - Part 2_6 Set up a multiplayer game
and i have a problem in my code or bug i dont even know
i dont get any error but my players dont spawn i dont know what i did wrong
all i know is i dont get log for if (runner.IsServer) {
i dont see runner.IsServer or player joined
also my "Basicspawner" get destroy after clicking on host
is it normal ?
i went and find the github sample , it work , i even copy and paste everything that was important about it (copy and paste scripts and even the prefabs ) but still it not working on my projects but it work on the second project (sample from github ) i dont get it why
but 1 thing i notice is
after i click on host button my "BasicSpawner"
gameobject
in my project just destoy
but on his project
change his position and go inside DontDestoyOnLoad
and i have no idea why
Is someone familiar with netcode for gameobjects, lobby and relay by unity? I have this bug which I wasnt able to fix in hours
yo can anybody help me a thing with photon? when i move a person it moves all players across the network but i'm not sure how to fix it
Hello, I am making 2D networked game with Unity netcode for GameObjects. I actually succeed making server authoritative player movement with Server Reconciliation, Client Prediction etc.
Now I am adding projectiles to the game that stuns the player when it hits him. So I am getting desyncs because the player hit on server side is not at same position as client prediction on local. Someone has some articles or theory in order to understand what's the optimized way to handle this ?
Thanks a lot.
projectile physics would need to be rolled back as well. You would need to retroactively apply the stun during server reconciliation
im using photon, and for some reason only the host of a room is being rendered, while everyone else is invisible and cant be collided with other players, is there a fix to this
Probably something wrong with your setup.🤷♂️
Might be better to ask in Photon community.
There will always be a desync in situations where force / knockback is applied on the server and not on the client
best way to handle it is to hide it
smooth the client correction so that its not an instant teleport, send the correction immediately after the knockback so it reaches the client sooner, etc
i think 😹
i tried that that server barely seems to have activity
also for stuns and slows which have a duration, that needs to be properly handled during rewinding and replaying inputs like evilotaku said 👍
so they expire ping amount sooner in time than for the server so that the client returns to predicting
Hello guys having a little issue,
GameObject bullet = Instantiate(bulletPrefab, this.gameObject.GetComponentInChildren<WeaponParts>().weaponMuzzle.transform.position, weaponSpawner.transform.rotation);
bullet.AddComponent<BulletScript>();
bullet.GetComponent<BulletScript>().bulletSpeed = weaponSpeedBalisitic;
bullet.GetComponent<BulletScript>().direction = (hit.point + dispersion - this.gameObject.GetComponentInChildren<WeaponParts>().weaponMuzzle.transform.position).normalized;
bullet.GetComponent<NetworkObject>().Spawn();```
with this code i spawn my bullet and give it a speed and direction but in my bulletscript it won't have the speed and direction
```public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
Debug.Log("Bullet spawned with" + bulletSpeed + " speed and " + direction + " direction");
GetComponent<Rigidbody>().AddForce(direction * bulletSpeed);
}```
this is the bulletscript
You can not add a network behavior to a gameobject at runtime. The clients will have no idea about BulletScript. I'm surprised it didn't start thowing errors
well if i put the bulletscript on my prefab will it work ?
and not putting the script at runtime
Yes. But you would also need to make bullet speed and direction a network variable. Or you can set those locally in it's OnNetworkSpawn()
How jank is this solution for combatting fly hacks (one of my gamemodes includes wall running in any plane): Find the plane the player is standing on at any given frame. Calculate the angle between said plane and the player's delta position vector from last frame and check if it falls within an acceptable range/
i have the data in my bullet but it won't add a force to it ?
should i make the add force to the network rigidbody ?
as long as it has a network transform and network rigidbody then it should sync up with the clients
well seems like the addforce to my rigidbody won't work even if he has a network transfrom,rigidbody and correct data from the networkvariables
If you are client auth then that will just get hacked too. If you are server auth then you don't really need the check
Hi, I'm currently doing some comparative research about networking solutions, and I was wondering about what are some examples of games that use Unity's solutions?
ohhh i got a warning : NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. Are you modifying a NetworkVariable before the NetworkObject is spawned?
i know why ok just need to fix it
perfect thank's a lot
The biggest one that I know of is Lethal Company using NGO. But a game's netcode is not something that gets talked about a whole bunch
yeah,
I just wanted to get a better idea of the kinds of projects people make with 'em
thanks a ton
Having a bit of trouble with this code : ```public float mouseSensitivity = 400f;
NetworkCommunication networkCommunication;
public Transform playerBody;
float xRotation = 0f;
void Start()
{
networkCommunication = GetComponentInParent<NetworkCommunication>();
}
void Update()
{
float MouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float MouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= MouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * MouseX);
networkCommunication.RotatePlayerServerRPC(playerBody.rotation);
}``` when i am a client when i move my mouse on the X axis the player shake left and right can someone help me with it ?
Is this using a Network Transform or Client Network Transform? Is it not spinning way too fast?
it's using an network transform
it's not spinning like it shakes
i'm making a vid for u
remove the sound of the video
Hey, the error is Only server can spawn NetworkObjects
It'd be part of CPSR
I have CPSR working for speed /teleport hacks, but I have nothing controlling for direction
With this only the server can rotate this object. So you're going to have to send MouseX in your serverRPC
This error is correct. Clients can not spawn anything only the server can
I don't know what your prediction system is doing doing but normally you would be tracking the position of the player. If it's off by a certain amount on the client then you pop the player back to the last known server position.
Yeah, but the issue is I have a gamemode where you can wallrun on any angle, and I need to make sure people can't fly hack. Normally that would be easy enough because you could just check the y component, but since player's can wall run, I need a more complex approach
Why aren't you checking the (x,y,z) and if its off by like .5 in any direction, then revert back and reconcile?
trying to do that but it does nothing when i send the mouseX i'm now lock on the Y axis
I'm confused, that
that is what I'm doing. But the issue is I need to figure out something to compare it to.
I have the player's new position, and the player's old position. I have that vector. Now to make sure they aren't teleporting or speed hacking I check the magnitude of that vector to make sure it's within a certain range based upon player's game state. The issue I'm trying to tackle is direction. How do I make sure the player doesn't fly straight up at a normal speed or clip? Normally, you could just check y component / you would only do these calculations on the x-z plane. However, because I am doing wall running, the y component won't always be the direction they are moving in if they decide to start flying.
If you are checking the client xyz position of the player compared to the old server xyz pos then it doesn't matter the direction. They can only move so fast in any direction.
But what if they start flying at the walk speed?
the server pos will be effected by gravity. eventually the client will be beyond the reconciliation threshold and will snap back down
oh, so the way I'm doing it is that the client get's to send their position and input to the server, and the server uses that as their position, but also check's their input and the delta position to make sure it makes sense
that way I don't really need to worry too much about synchronization just checks for anti cheat
oh man. Never trust the client
But im not?
If a player sends a "false" position, the server and all other clients are 1) going to treat that as a real position , and 2) the server is going to check it with their input
so the client's actions in whatever the position is on their screen will all be invalidated once they have to be checked by the server
If I'm being dumb, please correct me
The question is how you determine a "false" position.
Clients should only be sending inputs and receiving the True state of the world. Client should be the one testing their predictions and rolling back if need be. What you have is more Server Prediction. It can work that way but you have the server is more work if multiple bad clients are present.
I have a few questions. 1) If the client blocks a rollback ,that would only screw them over, right? 2) True it is more work on the server because they have to verify all inputs; is that going to be a lot of work on a dedicated server? I plan on having max 40 players. Let's say its about 2000 lines of code at O(1) time complexity, if the server is running at 30 or 60 ticks per second, that means 2.4 or 4.8 million lines of code, respectively, per second. Is that unreasonable? I'm not familiar.
@sharp axle sorry I forgot to react
I was always under the impression that managing the network traffic was the important part, but 5 m lines of code a second sounds like a lot
The plus side of server prediction is that you can detect bad actors sending false info and then kick them. With client prediction if they keep spamming the jump button you can just ignore it.
lines of code doesn't really matter but it will be an exponential increase in the amount of work per client.
Exponential? Because if there is an errror you have to send it to all the other clients plus having an additional client means another possible source of error? That seems more parabolic though.
And if it is parabolic it would be pretty linear parabola considering were not expecting much error that frequently, I'd think. anyways maybe im competely wrong. But thanks for your time, it's really cool of you to help out all the people here
Question to the community what is a good yt that starts tutorials for beginners.
For networking specifically?
To actually learn how to code in c# / unity
Do you have any coding experience? Also this would be better in #💻┃unity-talk or #💻┃code-beginner
I would recommend Code Monkey's videos on both counts
Personally, if you have no c# experience I'd look specifically for a c# tutorial first.
If you do have, then Code monkey is great
He is actually starting a C# course for beginners
Oh, well that sounds good then
Okay thanks for the help
I always tell people that before you go into game programming, you should learn the basics of OOP, which he probably covers
If his tutorial series isn't complete, there are plenty of other places to learn, although im not familiar I absolutely know they exist
Sorry to bother u again
, is it actually exponential or do u also think its more parabolic? It is important to consider if it is exponential
I've never benchmarked it myself. But if clients are also interacting with each other then I don't think it will end up parabolic.
True, if clients are reacting directly I'd guess itd be factorial.
Last question since I'm a beginner should I learn unity or Roblox coding?
I'm not familiar with roblox coding sorry
Oh k
I'm gonna try to break it down mathematically. Lets say you have n number of clients and each client interacts with other clients at a rate of n/c (c is constant) That would mean we could say the number of interactions between clients is equal to n^2 / c. Furthermore, each client has a certain amount of actions they would do on their own no matter what, so we can define this as n * d. So we'd expect the number of requests on the server for all these interactions to similar to O((n^2 / c) + n * d)
I guess there is no guarantee, that n/c is correct, it'd probably be close n^x/c or perhaps x^n, it's hard to tell
updating to 1.8.1 broke the network object script btw
it no longer shows up under the netcode components and is grayed out on the objects its attached to
You might need to restart Unity. check for any console errors too.
it only tells me the network prefabs need a network object component. they have one but like i said it's not working :D
and i restarted it many times, i also went back to the old version and it's still broken
no error just looks like this
To send to a client that he takes damage i need to make a client rpc with param ?
or a simple networkvariable and an oncollisionenter work ?
either will work. I usually have the server set the player health network variable
soo no clue what the problem is? 🥲
its not compiling for some reason. You would normally be seeing errors in the console
hm :/ weird
Hey. I’m working on using Netcode for Gameobjects for multiplayer.
How should i be setting up the cameras for each player? I am using cinemachine (also for the first time), where the camera and virtual camera is a part of the player prefab that gets instantiated when they connect to the server. However, whenever a new client joins the server, everyone’s camera just gets switched to theirs
you could turn off the virtual camera for all other players and it might "just work"
Check out how the client driven bit sized sample handles cinemachine
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/v1.5.0/Basic/ClientDriven
Hi, I'm using NGO 1.6.0 on Unity 2022.3.10f1
Actually, when I start the Network Manager as Host, it correctly spawns the player's prefab.
But if I do a Server / Client configuration, the client will never spawns the player's prefab...
Of course, my Client is correctly connected to the Server.
I hope someone has the solution to this problem.
Thanks in advance. 🙂
That is odd. There is no real difference between Host and Server. If player prefab is set in the Network Manager then it will spawn one for each client
Yes, that's why I don't understand why I have this problem, it's weird
put the camera (virtual and regular) into the player prefab, not outside
Hello everyone, I've been working with NGO over the past month, and everything is working as excepted with the exception of having high RTT and lag in the game. If the RTT is 1000ms, it roughly appears that it takes 1000ms for an action to occur on other clients like shooting projectiles.
Before I give up on NGO and experiment with another solution I thought I'd get some thoughts here.
Notes
- The high RTT happens even with only 1 player online
- It seems the longer the server is up, the higher the RTT becomes
- We are targeting WebGL, but have also been testing in a Windows application
- We are using a Dedicated Server with Unity Cloud Game Server Hosting and Relay with WebSockets to allow WebGL
- We've also tested without WebSockets/WSS/Relay
- If I ping the Server IP directly from my command prompt the ping is around 40ms
Packages
- Netcode for GameObjects 1.8.1
- Unity Transport 2.2.1
- Multiplay 1.1.1
- Relay 1.0.5
- Lobby 1.2.0
- Multiplayer Tools 1.1.1
- (Unity 2022.3.18f1)
Full Information:
https://forum.unity.com/threads/high-rtt-with-ngo-dedicated-server-relay.1553579/#post-9683618
I've also noticed today that when I upload a new build to Unity Cloud Game Server Hosting, the files sync, then go into a "Ready" state, but then never has any progress during the installation. Not sure why that's happening. The only way for me to get it to update is to delete the server, fleet, building config, build, then start over.
Normally when I upload a new build the server installs the files right away.
Hey i am trying to get my cinemachine working with my netcode for gameobjects setup.
I have two windows, one for the editor and one for a build. I am finding that whenever i start a host or client in my editor, my cinemachine works properly and follows my player. However, no matter what is selected (host or client) for my build window, the cinemachine just never seems to follow my player and sits at the default position
public override void OnNetworkSpawn()
{
if (IsOwner)
{
_audioListener.enabled = true;
_virtualCamera.Priority = 1;
}
else
{
_audioListener.enabled = false;
_virtualCamera.Priority = 0;
}
}
I've got no errors or anything. I dont think it is a network issue because my cinemachine doesnt work in my build window, regardless of if its a host or client
It seems the problem has been resolved by adding an Application.targetFrameRate to the server.
Now the RTT is mostly steady around the 100 range which is acceptable given the Relay Server.
hello, i am using netcode for gameobjects. i have a problem with client movement. i have two projects, in one it works perfectly fine ( that was my demo project where i test stuff) however in my main project the client simply doesnt move. i tried wasd movement but client doesnt move but i see that the client is trying to move (moving feet and legs etc, he is also animated but doesnt go forward)
tbh i used the main menu from a youtuber tutorial which included a lobby etc and i believe i am doing a mistake there.
and these two videos show the scenes and spawn mechanism
this is the code for player movement in third person
and this is the second project where it is working. the prefab list and character database confuse me too. i watched two tutorials but the one providing the main menu and networking tutorial doesnt show how character movement works and the characters only stuck in the air so i watched a second tutorial on how to change the character movement script so it works in coop
i am sure the issue is with the player prefabs and character database
Ok so I found the problem, when I uncheck connection approval, it's working
But now I would like to know why it's not working when it's checked ?
Do I need to do anything special in the code?
Edit: You need to use response.CreatePlayerObject = true;
what would be best networking for an fps multiplayer?
Any of them will work fine. Some have more built in features that other.
i have a quick question, as my game is a big multiplayer game and we can have a lot of server i'm wondering if i can broadcast a message trough all my clients currently on the game or not ?
Like if i make a maintenance on it and i want that everybody see the same message at the same time without making a update of the files
https://hastebin.skyra.pw/fidupezike.csharp I got TargetParameterCountException: Parameter count mismatch. error. I kinda know why but I have no idea how to fix it, btw if you are wondering what im tryinh to do it is everytime a player join a key, value of player id and nickmae pair will be added to the dictionary which get update eveytime new player joins
its photon fusion 2 btw
Hey, I need some help figuring something out. We are completely moving to Unity Networking right now.
We already implemented Unity Authentication and Unity Lobby.
We Would now like to also implement Relay (so we don't need to worry about NAT and Port Forwarding and shit like that) aswell as NGO.
How do we properly integrate Relay with Lobby? I know they work well together as that is what it says in the docs, but there is not really tutorial how to connect them (or I missed it)
You can use Cloud Code to push messages
https://docs.unity.com/ugs/en-us/manual/cloud-code/manual/modules/how-to-guides/push-messages
You basically just need to set the Allocation ID in the Lobby Player Data
https://docs.unity.com/ugs/en-us/manual/lobby/manual/relay-integration
cool thanks
would something like this be appropriate to auto refresh the Lobby list?
IEnumerator RefreshGameList(float waitInSeconds)
{
var delay = new WaitForSecondsRealtime(waitInSeconds);
while (true)
{
var lobbies = LobbyManager.Instance.GetLobbies();
foreach (var lobby in lobbies.Result.Results)
{
var gameListEntry = Instantiate(gameListEntryPrefab, gameListContent);
gameListEntry.GetComponent<GameListEntry>().SetLobby(lobby);
}
yield return delay;
}
}```
ok no its not xD it causes my whole unity to just freeze 😄
Sure as long as you Get lobbies method is correct
once I call it with StartCoroutine(RefreshGameList(5)); my unity just freezes
this is the GetLobbies:
public async Task<QueryResponse> GetLobbies()
{
var query = new QueryLobbiesOptions
{
Count = 10,
Filters = new List<QueryFilter>
{
new(field: QueryFilter.FieldOptions.AvailableSlots,
op: QueryFilter.OpOptions.GT,
value: "0")
},
Order = new List<QueryOrder>
{
new(asc: false, field: QueryOrder.FieldOptions.Created)
}
};
return await LobbyService.Instance.QueryLobbiesAsync(query);
}```
I avoid using while(true) at all costs to prevent infinite loops
could you tell me how you would refactor the code?
Personally I wouldnt auto refresh the lobby list at all. Just have a refresh button. What you have is fine, you just need make sure to stop the coroutine.
well something doesn't work properly, once I start the game my unity zu freezes:
private IEnumerator RefreshGameList(float waitInSeconds)
{
var delay = new WaitForSecondsRealtime(waitInSeconds);
while (true)
{
var lobbies = LobbyManager.Instance.GetLobbies();
foreach (var lobby in lobbies.Result.Results)
{
var gameListEntry = Instantiate(gameListEntryPrefab, gameListContent);
gameListEntry.GetComponent<GameListEntry>().SetLobby(lobby);
}
yield return delay;
}
}
void Start()
{
_refreshGameListCoroutine = StartCoroutine(RefreshGameList(5));
}
private void OnDestroy()
{
StopCoroutine(_refreshGameListCoroutine);
}```
but you are right, I will just add a refresh button.
Hello, good afternoon, I hope you are all doing well. I have a question: I would like to create a multiplayer client-server P2P game for Steam. Is there anything I should consider, such as pricing or any advice you wish you had heard before starting?
Hey I need some Networking help.
I have now managed to successfully connect Relay, Lobby and NGO (nearly).
But my problem is: when the second player joins, both players get spawn on top of each other and I control both players, is that caused by my Movement Script?
Your inputs are not checking for local player. And default the player object will spawn at the scene origin
could you link me the docs that talks about local player stuff?
okay so I managed to fix it a bit by using this code:
if (IsLocalPlayer) return;
transform.GetComponentInChildren<AudioListener>().enabled = false;
transform.GetComponentInChildren<Camera>().enabled = false;
transform.GetComponentInChildren<PlayerMovement>().enabled = false;
transform.GetComponentInChildren<LadderClimbing>().enabled = false;
transform.GetComponentInChildren<MouseLook>().enabled = false;```
but there is still multiple problems with that:
Animations are not synced network players are just tposing or stuck in the idle animation
also shouldn't it be IsOwner when trying to do server authoritive movement?
Hey having a bit of an issue, i'm trying to attach a gun to a player that i instantiate but it won't set as parent when i spawn it : ```
public void SpawnWeapon(SO_Weapons weaponSpawn)
{
weapon = weaponSpawn;
if (weaponSpawner.transform.childCount > 0) Destroy(weaponSpawner.transform.GetChild(0).gameObject);
GameObject weaponSpawned = Instantiate(weapon.weaponPrefab, weaponSpawner.transform.position, new Quaternion(0, 0, 0, 0), weaponSpawner.transform);
weaponSpawned.GetComponent<NetworkObject>().Spawn();
weaponSpawned.transform.SetParent(weaponSpawner.transform);
}```
my parent is an network object and my guns have a network object and network trannsform
You need to use a Network Animator
https://docs-multiplayer.unity3d.com/netcode/current/components/networkanimator/
The NetworkAnimator component provides you with a fundamental example of how to synchronize animations during a network session. Animation states are synchronized with players joining an existing network session and any client already connected before the animation state changing.
Network Object Parenting is a whole thing. I avoid it myself
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
how would you do it ?
I'll attach it with a physics joint if it really needs to be a Network Object. Most of the time you can get away with just instantiating a regular game object locally, Then you can do whatever you want with it
well i need all my players to see the current gun you are holding
after for a prototype is it really useful
I use int network variables to select what items are equipped. I have a big list of items in my item manager and then instantiate that index according to the players network variable. Your helmet might be item 24 and you backpack item 72. Your guns maybe items 15 -25
ohhhhhh i see
so you have a naked player and you instantiate the elements to other clients with network variables
that will make a lot of work to change everything
@sharp axle having a bit of an error "GetComponent requires that the requested component 'SO_Weapons' derives from MonoBehaviour or Component or is an interface."
Like a made networkvariables to cast int... and i need to acces my component which is a scriptableobject and i have this error i understand it but i can't resolve the error
Yea. a scriptable object is not a component. so you won't be able to GetComponent. Its an asset so you can load through the Resources folder if you need to
I've got an issue where if I try and move the players position to somewhere else when its spawned it will stay stuck unable to move
It works perfectly fine just spawned in without changing its position whenever i start as host
Not only will my input not go through it seems as if the network manager doesn't like it, as the player is completely stuck
I feel as if this a simple fix and a desync issue with teleporting
but I don't know the answer and I really need the help asap
Change Start() to OnNetworkSpawn(). If SpawnReference is in the scene then you will need to Find it when the player spawns
I used OnNetworkSpawn with the same issue
while i try to build my game with the new AssetDatabase.LoadAssetAtPath
i use the dependence using UnityEditor; as asked but i keep having a build fail
"Assets\BulletCreator.cs(82,18): error CS0103: The name 'AssetDatabase' does not exist in the current context"
and my 82 line is
"weapon = AssetDatabase.LoadAssetAtPath<SO_Weapons>("Assets/ScriptableObject/Player/Weapons/W_" + weaponSpawn.Value + ".asset");"
Yea. that's an editor only function. In a build you'll need to use Resources.Load
https://docs.unity3d.com/ScriptReference/Resources.Load.html
ohhhh ok i'll try thta
The folder has to be named "Resources"
yeah i put it in a Resources folder well there is folder in folder to let it clean and i know it's case sensitive i made a copy path but still won't work
Hey I've got a question. I have something in my scene. I want it such that when a player spawns in (using netcode for gameobjects), that specific script attached to said something finds the player that is local. How can i do this?
Resources.Load
Make it a Network Object and in its OnNetworkSpawn() you can grab NetworkManager.LocalClient.PlayerObject
is it preferable to have server determine available servers, eg load balancing (C->S->S1 or S2) or should the client ping each server directly (C->S1 or S2)?
Hello, good evening, I wanted to ask, what do you think about Fish-Net?
Hey so let’s say I have a prototype game that has multiplayer already using Netcode for gameobjects.
I can join as a server, host, or client in my game. I am curious to how setting up local split screen would work if I already have this server/client/host stuff set up. What would be the general idea for how split screen is handled? Is it possible to have split screen players on one device and someone else joining as another client?
ie like is it possible to set it up such that another client can join but is split screen with the client (or host) that is on its same device?
My inputs are also handled by the new Unity input system
i haven't actually tried it but ngo has made some steps at least towards supporting multiple NetworkManagers in a game - that said i think even if that works you'd probably be better off implementing it separately
unless you want each player to have a totally separate copy of the world, stuff like spawning and object ownership would be a nightmare
Yeah. Conceptually would it be just like the second split screen player is joining as a client or something? And just running its own version of the game as if you were online?
yeah, that would be the idea
Gotcha
normally you'd want one world with two cameras rendering to different parts of the screen, rather than two worlds though
So it’s mostly just a matter of setting up a client connection that when you join, sets up a split screen window with the host and making sure the inputs go to the right player
yes, but again, probably don't do this
Wouldn’t I need to do this if I want players to be able to be in different scenes from each other?
that's already something you probably want to avoid if at all possible in NGO, let alone while trying to make it work in splitscreen
So for a small-scale but open world game with low-intensive graphics, would it be best to just have the entire game in one scene?
well if you want players to be in totally different areas you have to manage which set of network objects each one can see, whether or not they're in different scenes
trying to make that work in splitscreen would be a massive waste of effort
For local co-op you would have the local client own both local players. If you want to use UGS services with both local players that a bit trickier but still doable
i see a lof of different options when it comes to networking i want to make a simple tag game which option is reccomended for a simple game like that?
Any of the currently supported frameworks will work just fine for that
are any of them easier to use then others?
Hello my friends, may I ask a question? I am using Netcode for Gameobjects and am able to sync Animation through a network animator. For my locomotion I have a blend tree going. The correct animation/ horizontal and vertical parameters are networked. But these parameters keep bouncing to zero making animation jitterish. Any way to lerp that parameters over the network? Any workaround for blend trees? I would be very glad for any hint or info about networked blend trees.
Is resolved
Hey guys, for a game i have to implement a system of Request/Response between the server and some clients
I tried to do it by calling a Server RPC that then calls a Client RPC as a response for everyone
public class simplemovement : NetworkBehaviour
{
public float speed;
private float Move;
private Rigidbody2D rb;
private SpriteRenderer sr;
private BoxCollider2D bc;
private Color[] colors = { Color.red, Color.blue, Color.green};
private int currentColorIndex = 0;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
sr = GetComponent<SpriteRenderer>();
bc = GetComponent<BoxCollider2D>();
sr.color=colors[currentColorIndex];
}
// Update is called once per frame
void Update()
{
if( !Input.GetMouseButtonDown(0)) return;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if( bc == Physics2D.OverlapPoint(mousePos) ){
currentColorIndex = (currentColorIndex + 1) % 3;
sr.color = colors[currentColorIndex];
sendColorServerRpc(colors[currentColorIndex]);
}
}
[ClientRpc]
public void colorClientRpc (Color color)
{
sr.color = color;
}
[ServerRpc]
public void sendColorServerRpc(Color color)
{
colorClientRpc(color);
}
}
but it just doesn't do anything
(i have a basic network manager that can spawn servers and clients)
try to modify attribute of sendColorServerRpc to [ServerRpc(RequireOwnership = false)]
Oh yeah it works now ! Thanks
I think it's a small problem, but i have no idea of the best solution
I have a network list of players and when the host starts the game 2 things are happening:
-
I need to choose a player for the Artist role
Players[artistIndex] = Players[artistIndex].SetRole(PlayerRole.Artist); -
I need to notify clients that the game is starting
NotifyGameStartClientRpc();
The problem is the sync of the order of these events
On the Host side, it works as it is in the script,
but clients have incorrect order, they receive game start and then the list is updating
Hey guys i'm wondering how to get my player latency on ms i'm looking on internet but it's not really accurate
I managed to get this line pingText.text = NetworkManager.Singleton.NetworkConfig.NetworkTransport.GetCurrentRtt(NetworkManager.Singleton.LocalClientId).ToString(); but i still haven't my current ping from the server
I think it’s not the good function to use
If RPCs and Network Variables are sent on the same frame, there is no guarantee of order. The quick and dirty solution is to simply wait a tick after setting the Artist Player before you start the game.
But it would probably be better to have each client send the server a Ready signal. Either a serverRPC or Network Variable book
Current RTT/2 should be fairly accurate. You would probably need to get a average over time. This is usually good enough for player indicators. If you need it super accurate for gameplay reasons then you'll probably need to use Ping/Pong RPCs
In theory, server time - local time should also get you your latency
I have watched tutorials over tutorials about how to make syncronization happen between host and client, but i still cant get over this bug ive spent hours trying to troubleshoot, as the host i can move a gameobject around and it syncs on the client, when i do the same on the client it does not sync, tutorials told me to add a client network transform, i did but that didnt fix it, it could be because all the tutorials ive seen so far use a player prefab and i do not but i really need some help fixing this xD
thanks, that makes sense
as a workaround, i'm passing the artist id to NotifyGameStartClientRpc, and after that everything goes smooth
client network transform will allow the owner to move the object. If it's not owned by thplayer then you will need to send a serverRPC to move the object
Yea that's a good solution too.
alright i think i understand, ill look up some tutorials on rpc thanks
The docs for RPCs are here
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/
Any process can communicate with any other process by sending an RPC. Starting in version 1.8, the Rpc attribute encompasses Server to Client Rpcs, Client to Server Rpcs, and Client to Client Rpcs.
private async void OnClientDisconnect(ulong clientId)
{
if(clientId == HostNetworkId && !GetNetworkManager.IsHost && clientId != GetNetworkManager.LocalClientId)
await UserDisconnect();
//await UserDisconnectServerRpc();
}
public async Task UserDisconnect()
{
var nm = GetNetworkManager;
if(!nm.IsListening || nm.ShutdownInProgress)
return;
LoadOfflineScene();
HideLobbyCode();
if(nm.IsHost)
nm.ConnectionApprovalCallback -= HandleConnectionApproval;
await LeaveOrDeleteLobby();
_connectionStatus = ConnectionStatus.UserDisconnect;
nm.Shutdown();
}
private async Task LeaveOrDeleteLobby()
{
if(_lobbyAPIInterface.JoinedLobby == null || GetNetworkManager == null)
return;
var lobby = _lobbyAPIInterface.JoinedLobby;
var joinedLobbyID = lobby.Id;
if (lobby.Players.Count <= 1 || NetworkManager.Singleton.IsHost)
{
await _lobbyAPIInterface.DeleteLobby(joinedLobbyID);
if (debugMode)
Debug.Log($"Deleted the lobby with the ID {joinedLobbyID}.");
}
else
{
await _lobbyAPIInterface.RemovePlayerFromLobby(AuthenticationService.Instance.PlayerId, joinedLobbyID);
if (debugMode)
Debug.Log($"{AuthenticationService.Instance.PlayerId} has left the lobby.");
}
}```
```cs
if (leaveOnEscape && Input.GetKeyDown(KeyCode.Escape))
{
await UserDisconnect();
}```
Hi, me and my teammate are trying to disconnect the player when they hit escape and load them into the lobby scene but we keep getting errors and dont know why, we have been trying to patch it for about 2 and a half hours now.
These are the errors we keep getting. Also, they are all client side errors.
I think you are overcomplicating this. All you need to do is call Network Manager.Shutdown() and then SceneManager.LoadScene() to go load your scenes. Call LeaveLobbyAsync() if you need to.
The issue when doing that is when the host leaves, it doesn't load the lobby scene for the client, only the host.
We want all players to load the offline scene when the host leaves and if a client leaves, only that client should be loaded back into the menu
When the host leaves the network will disconnect all clients as well. You can then use the Onclientdisconnected callback to switch scenes and leave the lobby if you need to.
public async Task UserDisconnect()
{
var nm = GetNetworkManager;
if(!nm.IsListening || nm.ShutdownInProgress)
return;
LoadOfflineScene();
HideLobbyCode();
if(nm.IsHost)
nm.ConnectionApprovalCallback -= HandleConnectionApproval;
await LeaveOrDeleteLobby();
_connectionStatus = ConnectionStatus.UserDisconnect;
nm.Shutdown();
}
private async Task LeaveOrDeleteLobby()
{
if(_lobbyAPIInterface.JoinedLobby == null || GetNetworkManager == null)
return;
var lobby = _lobbyAPIInterface.JoinedLobby;
var joinedLobbyID = lobby.Id;
if (lobby.Players.Count <= 1 || NetworkManager.Singleton.IsHost)
{
await _lobbyAPIInterface.DeleteLobby(joinedLobbyID);
if (debugMode)
Debug.Log($"Deleted the lobby with the ID {joinedLobbyID}.");
}
else
{
await _lobbyAPIInterface.RemovePlayerFromLobby(AuthenticationService.Instance.PlayerId, joinedLobbyID);
if (debugMode)
Debug.Log($"{AuthenticationService.Instance.PlayerId} has left the lobby.");
}
}```
would this be the only code needed then?
we tried using that code, when the client disconnected, the host got these 2 errors
and the client got these errors
I keep getting this error after spawning a player prefab inside a test scene using unity's network manager
naturally it doesn't tell me what class is causing the problem, and deleting objects and components one by one until I found an answer didn't help much
I tried adding a generic cube as the player prefab, and as soon as it's spawned the same error flares up
...found the problem
but not the solution
private NetworkVariable<int[]> TeamMembers = new NetworkVariable<int[]>
(
new int[4],
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Owner
);
unity seems to be throwing a hissy fit over this array, so I assume I did something very wrong here trying to create a network array
You should probably be using a NetworkList here
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#complex-types
Introduction
try NetworkList instead of NetworkVariable
private NetworkList<int> TeamMembers = new NetworkList<int>
(
NetworkListReadPermission.Everyone,
NetworkListWritePermission.Owner
);```
that's some timing
my bad
cheers lads
I'm trying to figure out how to make a weapon that can fire a fireball projectil but not successful yet. I'm using a game object with a particle effect on and a rigidbody and set a velocity to the rigidbody. I'm using a VRCObjectPool to spawn the projectile and then set a velocity on it. Now I could add a VRCObjectSync on this one but my idea was that I could save some network load by just setting the initial velocity of the object on all clients, but unsure how to do this with the network pool.
If I do not use a network pool i can just spawn a new object on all clients and set the velocity, but if i use a VRCObjectPool i guess i kinda want to refer to the same object? So this is what I do right now but that will only make the object move on one client and stand still on the others, well right now becase projectilePool.TrySpawn() will fail on all but one. But it should at least show a general idea of how the thoughts goes and someone can explain how it should really be done.
FireProjectile is called on all clients.
public void FireProjectile()
{
Debug.Log($"FireProjectile {_localPlayerName}");
var obj = projectilePool.TryToSpawn();
if (!Utilities.IsValid(obj))
{
Debug.LogWarning($"Unable to spawn projectile from pool {_localPlayerName}");
return;
}
Networking.SetOwner(Networking.LocalPlayer, obj);
var spawnPoint = projectileSpawnPoint.transform;
obj.transform.SetPositionAndRotation(spawnPoint.position, spawnPoint.rotation);
var projectileScript = obj.GetComponent<Projectile>();
projectileScript.Initialize(spawnPoint.forward, projectilePool);
}
@sharp axle do you know how else to fix this or no? Sorry for the ping just didnt know if you saw this or not
Disconnecting Players
adding on to this, I set the list up as explained in the link evilotaku posted, declarating the list then creating it on awake, but I can't add anything to it
NetworkList<int> TeamMembers;
[SerializeField] TeamData[] teams = new TeamData[4];
void Awake()
{
instance = this;
TeamMembers = new NetworkList<int>();
}
I tried using .Add(0) on awake, start, OnNetworkSpawn and even a function being called by the first player to enter the game as a host
every time I get a null reference exception
line 28 in GameManager is TeamMebers.Add(0); from this snippet:
public void DoTeamSetup()
{
TeamMembers.Add(0);
}
which is called from the player's OnNetworkSpawn here
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (!IsOwner) { return; }
GameManager manager = GameManager.instance;
if (IsServer) { manager.DoTeamSetup(); }
team = manager.getTeamMembers(0) <= manager.getTeamMembers(1) ?
manager.GetTeam(0, true)
: manager.GetTeam(1, true);
Material[] mat = mesh.materials;
mat[0] = team.teamEquipMaterial;
mesh.materials = mat;
}
I either get a null reference or a length 0 error
Its likely because you are using a Singleton. Being a static variable does weird things with the network
well crud. do you suggest I keep it in a regular gameobject then?
or rather a non-singleton script
Personally, I avoid singletons all together. Keeping it local in the scene and just grabbing it with FindObjectByType() is not a big deal
same problem
public class MultiplayerVars : NetworkBehaviour
{
public NetworkList<int> TeamMembers;
void Awake()
{
TeamMembers = new NetworkList<int>();
}
}
on the player's prefab, as a test:
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (!IsOwner) { return; }
GameManager manager = GameManager.instance;
if (IsServer)
{
MultiplayerVars mpv = FindObjectOfType<MultiplayerVars>();
if (mpv)
{
mpv.TeamMembers.Add(0);
mpv.TeamMembers.Add(0);
}
}
the MultiplayerVars script was placed inside an empty
Hey so I am trying to get a small open world network to work. I want it to be something similar to how multiplayer works in stardew valley for example, where it is player hosted and the client has authority.
My idea was that the world would be divided up into different scene. I would like the players to be able to be in different scenes from each other as well. Does anyone have a conceptual outline for how this would be handled? Is there a common/standard way this is approached?
For example, can the client send an RPC to the server (aka host player) to switch scenes?
Frameworks typically don’t provide this out of the box but you can ofc implement that yourself with custom scene management and sync logic. It’s fairly complex though.

