#archived-networking
1 messages ยท Page 12 of 1
yes, it can be that
but its not limited to being a broker
zeroMQ is a chassis which you have to build a car on top yourself, rabbitMQ is a finished truck
anyway, not suggesting you use it neccessarily but the documentation of it is a masterclass in transport/messaging design
ubt why not implement it with native sockets( libc sockets or wisock2)?
i can't however tell you how well that translates to actually doing it (making a custom transport) because i only ever use existing ones
because that involves a lot of groundwork and dealing with platform quirks which zeroMQ has done for you
oh got it
thats basically all that zeroMQ does for you
btw, unless you have crazy specific needs, you should use KCP or ENet or a transport like them
there is practically nothing gained from reinventing them (from what i can tell)
im all of this for fun. I don't care about effectivity. Just want to learn low-level networking
im not sure what knowledge is needed to get a job as multiplayer dev(networking)
oh, then definitely read the KCP implementation
depends on the project, for interesting ones you need a reputation / proven track record
its very difficult to get on the engine team in any game company
well id like to work on projects where i can optimize networking code and work on internals of high performance networking game server
i see, that sucks ;/
yeah
a lot
ive tried a couple of times to get a networking job at a game company, didn't work out, so take what i say with a grain of "salt found on the outside".
to be honest you completely ruined my motivation xd
i think if you want to really specialize in networking, its gonna be much more realistic for you than for me, i'm more of a generalist and netcode is a part of most projects but not a challenging one (small scale)
also there are a lot of really clueless netcode developers that ruin projects, so you apparently can get a job even without a clue...
I mean, i dont want to stick with mainstream network framewroks and just write actual logic for the game
do you have a specific example in mind?
those a projects i consulted on, none of them survived
you need to make your own luck if you want to work on that stuff
or there were some odd bugs coz netcode
yes, mostly its ex web developers thinking they can implement a realtime game server with node and a HTTP api
the primary misunderstanding is that node and http are supposedly fast
i mean http 2.0 is quite fast compared to 1.1
but web-dev fast and game dev fast are orders of magnitude different
thats the wrong kind of fast
game netcode data has completely different properties compared to web data
yeah i know
for one thing its not predicatble at all
you cant cache it
it needs extremely low latency
and its realtime
correct me if im wrong, maybe data is not cached but instructions are
well, you can cache it but you will only have misses, so its pointless
its conceptually impossible to cache a game server's response
what if its hearbeat tick?
well you can cache internally
but thats different from having a cache server to serve precomputed results without tickling the source
yeah, all data will differ
the heartbeat still needs to be answered by the actual server
i mean you can calculate some stuff to "predict"
thats something else
predictive loading/responses are a thing in web app development too, but very advanced and not your average joe's repertoire
But you have to fit within the server's tick timeframe anyway depending on tickrate of server
would say those are probably the most advanced things you can do in networking when it comes to games, if the predictions need to be corrected gracefully and correctly
i mean, if you care for it, if you can implement a competitive game server, you can probably find a job ๐ฎ
well, that would be immposible
not impossible, just a long road
Servers like this are developed by whole teams, not a single guy during his time off
yes, but a single guy can still hike 6000 miles if he takes his time ๐
can also fly into space xd
but realistically, yes, its not possible
imo, its not even possible to make a real game solo
you mean AAA calibre game?
real = game could potentially be a commercial success
no, any kind of game
you can have absurd luck and it might happen because of that, but you cannot "plan" to do it
Yea true I mean what is minecraft, never heard of it
Or all the indiedevs out there on youtube, it's all a lie
none of those were truly made by 1 at the point where the public noticed them
there are exceptions like luke pope, who truly does everything himself
The guy who did "return of obra dinn". That was a great title
thats luke pope
some games come close, like FTL (2 guys) or stardew valley (1 guy, 7 years, no life) and ofc vampire survivors
however you can't make a living off something that takes absurd amounts of luck to get anywhere
@austere yacht Well that sound like its better to stay in webdev or other "safe haven ' and do games as hobby ๐
thats the advice yes, statistically you have no chance, its like trying to be a rock or movie star, some still make it
if you have a great personality and can work the yt as a creator, you can definitely make it
Yes of course if you dom't have funding and 10k + wishlists you probably shouldn't quit your job for your game, this should be obvious
Also this has nothing to do with networking
i though networking would be paid a little more better than other areas, due to lower interest regards it
probably is, its considerably more frustrating work, and that kind usually is better compensated
but also, stuff that requires expensive, hard to find, experts (in CS) is eventually replaced by a library or framework by management
which means that in this case only the best will be left which will provide better and better solutions?
some studios are complaining that they can't find any developers for inhouse engines and infrastructure anymore so they are forced to adopt standard engines/frameworks
yes, its a power law
but its not a simple as "only the best will make it"
its also eliminating/crowding out alternative, lower profile, more niche approaches
idk if this is happening to networking as much as it is to the whole engine question
you just need to become one of the best. ez, don't let me crush your motivation!
take NGO, "some guy" wrote it, put it on github for free, unity saw it, bought it, made it its featured solution, that could be you!
yk, i think this discord is mostly a support group for former web developers who want to regain their sanity
You just have to understand that it's just a job and not a hobby like it used to be.
after that, everything becomes easier
Every day you smile in the mirror and write the same crud application like yesterday and yesterday and...
That doesn't sound too bad actually
Does anyone know how to send int[] through network variables with netcode for gameobjects?
with netcode can I have like a networked object with one of the children not networked
oh my god I had to scroll down on this page and I found it
You can't arrays are reference types. Network variables can only be value types. You should use a NetworkList<int> instead
which one out of pun2, fusion and bolt is better for FPS with lag compensation?
fusion for sure. Its build in.
I have an ultra-basic question about networking and "server-authoritative" setups. Because ServerRPC calls cannot return a value, how does a client check if a certain action is possible?
Network variables or client rpcs depends on how much controll you want to have over the chain
So let's use the simpler one networkvariable
You would create a boolean network variable and name it isAllowed in your server rpc you than set the value of isAllowed and it will automatically sync to all clients, which means you can get access to the value of isAllowed on the client
Note: I don't have a clue if it will be there instantly, like lets say you call your serverrpc and dieectly checking afterwards what the value is, you would need to test that
So, in the parlance of the game itself, many gamestate variables are public - the number of cards in the draw deck, the current score, etc. Should those just be network variables then?
I'm trying to get my head around the idea that the game state is private and can only be altered by the GameManager. Can a network variable be a getter?
like ie, i have a private List<Card> drawDeck; can I have a public NetworkVariable<int> CardsInDrawDeck => drawDeck.count; or something like that?
Uhm idk, try it out
But your list wouldn't get synced you have to handle that as well
I guess that gets back to the original question: If I want to know something about the gamestate (say, the number of cards in the drawdeck) how would I do that? Is the answer to replicate any gamestate changes on the server down to the client so that they're synced, and then let the client query it's own copy of the gamestate? That seems to break the "server authoritative" model....
You could have the drawDeck completly on the server side and handle all the gamelogic it self there and then create a NetworkVariable<int> cardCount
And a function RequestCardCountServerRpc(){
cardCount.value = drawDeck.count;
}
This assumes tho, that all your logic is handled on the server and that the clients do not need to have a synced copy of the drawDeck. Is that what you wanted to know?
A networkvariable can by default only be set on the serverside btw
How you syncronize your data depends on who needs access to what and when
For example: in my game Enemies, Trees and other things have a health value, I don't need to syncronize it tho, because everyrhing that happens with the health value happens on the server side, so the client's don't need to know about it, when I would add a healthbar or sth like that, which would be set locally since it is ui, I would need to get access to that health value, via a NetworkVariable to read it out on the client side. So it depends on what you are trying to achieve
So yea you can absolutly acces stuff like your drawDeck count, which isn't synced via a network variable, the rest of your logic would just need to account for that
it seems like network variable is the way to go for public-facing gamestate; then keep the actual variables private
it sounds like network variables are functionally private-set tho to so maybe save the gamestate directly in network vars?
except that I don't think things like a list of generic classes (say, my Card class) can be saved in a network var without implement ISerializableMemCpy?
Yes. But there are workarounds for example I have a item class in my game, which I need to have synced and it includes a gameobject, for the prefab, so I can't serialize it. They way I have dealt with it is simply writing a handler for requesting that item. I registered all of them in a list and can get them by name, so I only need to sync the names of that Item, you could do a similar thing with cards
My best advise is, just play around with it for a while and you will figure it out how you can deal with things. Maybe even ask chatgpt not for solutions, but explain the process and it can give you additional informations, that way you can learn alot of it fast
You can have a CardData struct that implement INetworkSerializable. But what do is just have a big list for my card pool. then I can just send Card IDs back and forth
yeah that's what i've done in the past
I need some help cuz the photon voice view doesnt look like in the tutorial what im watching
I tried using this, but it unfortunately didn't work. I tried running three instances, 1 host, and 2 clients, and found that every instance was using the same camera, but controlling different players, if the code you provided didn'/t work, does it need to be modified or is it something else that I am missing?
I actually solved this issue, so now I am trying to get Network Transform working, Why does it ask for a Network RigidBody when every resource I check doesn't require one?
Even if I add the Network RigidBody, players aren't synced
If you have client authoritative movement then you'll need to use Client Network Transform. Also check your inputs are only applying to the local player
By Local Player, should I use the argument
if (!IsOwner)
{
Destroy(this);
}
or
if (!IsLocalPlayer)
{
Destroy(this);
}
and both network transform and client network transform ask for a network rigidbody
I wouldn't destroy the component, just disable it.
If it has a network transform and a rigidbody then its going to assume that you also need a network rigidbody
Is there code that I need to add for the network to sync? The players are in completely different positions despie having Client Network Transform and Network Rigidbody
Host:
Client:
How are the players spawned? Are you having the players spawn automatically or are you spawning them manually?
They are spawned through a network manager
That should just work. Is it just the positions that are off? Is the movement working at all?
yes, the movement does work, let me try changing the position
For some reason only on the host version, the second player spawns in the ground
but even then, I don't see the host moving on the client build
They should be spawning right on top of each other
im making a game that has a mechanic where there's some items for sale in a public shop. all players have access to the same single shop and it's first come first serve. id like all players to have a fair shot at claiming an item but am concerned that either the host or players with lower latency would always have an advantage. is there a way in netcode for gameobjects to implement something like this that's fair to all players regardless of their latency to the relay?
I don't think you have both first come first serve and not be biased towards lower ping. There are tricks to compensate for lag but host advantage is hard to overcome.
it's a board game so not very fast paced, could i do something like check a timestamp of when a client makes a request and compare, then award it to the player with the earlier time?
Hi, I have just started on an aircraft marshalling simulator game and i am stuck in making the aircraft move with respective to the air marshaller wand does anyone know how to get started for eg.Player moves wand left aircraft turns left
Is it possible to pass a prefab reference over RPC?
Curious how is best to get a client to call a server rpc to spawn a prefab, have the server spawn it properly, then have the calling client get a reference to that new object in the scene. Seems like a really convoluted process.
Depends on which framework you are using. In NGO, you can send NetworkObjectReference
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization#networkobjectreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
Interesting, thanks for sharing the link. That seems to cover part of the issue, but getting the reference of the result back to the client seems difficult still, since only the server can spawn network objects.
For example in the doc there, if ShootTarget were needing to return a GameObject so more work could be done on it.
Oh yea, Network Object Reference will only work for Spawned Objects. The reference can be implicitly cast back into a GameObject however.
Ok. Do you happen to know of a way to access the NetworkManager NetworkPrefabs list? It's internal for some reason within NetworkConfig and I can't find any other way to examine it.
Reason being, I could just pass the index of the prefab that I want to spawn, along with an "id", client RPC that to the server, then server creates the object and populates the given ID so that the client can identify the object it requested.
In version 1.3 they broke out the prefab list into a scriptable object. That should allow you to do this. I haven't tested it yet.
Seems like 1.3 is not on PackageManager yet
You have to add it by name and specify the version 1.3.1
how can I make my player move in the correct direction no matter what way I face?
https://pastebin.com/JpT5035K
that script has my movement method incase that's needed
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Whats the best way to sync an editable object between players? It has a bunch of children that can be edited(transforms). Json?
JSON is not very efficient but if it's not being sent very often then its the easiest way.
Hmmm okay, what would be the other option? It's not sent often, only when a user does a transform edit of one of the children.
The other option is custom serialization. Usually involves turning the class data into a struct that can be sent over the network.
basically ive got a fully functional fps game. i would want to implement multiplayer in it but i couldnt find a networking solution that supports peer 2 peer mesh
There are some challenges with that when it comes to NAT and IP leakage when you aren't connecting through a relay server.
public class Entry : NetworkBehaviour { }
using UnityEngine;
using Mirror;
public class ListManager : NetworkBehaviour
{
[SerializeField]
public Entry template;
public readonly SyncList<Entry> syncList = new SyncList<Entry>();
private void Start()
{
if(isServer)
{
GameObject obj = Instantiate(template.gameObject);
NetworkServer.Spawn(obj);
Entry newEntry = obj.GetComponent<Entry>();
syncList.Add(newEntry);
}
}
private void Update()
{
if(isClient)
{
foreach (Entry entry in syncList)
{
Debug.Log("Entry: " + entry);
}
foreach (NetworkIdentity id in NetworkClient.spawned.Values)
{
Debug.Log("ID: " + id.name + "," + id.netId);
}
}
}
}
I'm finding that the SyncList is not getting populated, client-side. It's being populated with NULL values on newly-joining clients. The NetworkClient.spawned dictionary has the Entry objects, but the syncList is just nulls ... any idea what's going on here? Why is SyncList just nulls?
I need some help with photon. I have a fast photonview and its master is constantly changing. Sometimes this object is teleported on other devices. Do you know the solution? how can i create a solution
i will connect through steams relay server
i followed CodeMonkey's multiplayer netcode for gameobjects tutorial and have a test build on steam that im trying out with a friend. im using unity lobby and relay like he does in the video, when i host the game he's able to join but if he hosts i cant connect to him. any suggestion or thoughts what might be wrong and where i could look?
im able to see the lobby he creates, just not connecting to it
If he can join but can not host, then that could be a firewall issue.
i thought the point of using relays was there shouldnt be any issues with ports or firewalls?
There can always be issues with ports or firewalls. But it could also be other network issues that prevent hosting. You can have him try to join the relay from another client on his PC
im looking in the log, it says LobbyConflict, (16003). Message: player is already a member of the lobby. maybe something wrong with my unity authentication and sign in?
It says you have already joined the lobby. Can you get the relay data from it?
i think you were right that it was an issue with ports/firewall, cause i tried with two other friends and didn't have that problem with them. only the one friend.
i do have another issue though, similar topic. i could join their game and they could join mine. but going from a game back to the menu, and creating a new lobby again they're not able to join that one, getting the player is already a member of the lobby error. the lobby is deleted when a game starts, and the scene is reloaded upon exiting an existing game to reset all the variables. i exited the game completely, relaunched and created a lobby and then they were able to join
Guys Help Please Idk how to explain i am using this tutorial and this is my code and in game nothing happens!!! HELP
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
In this tutorial we will look at how to make an online chat function that lets all our players on the server message each other!
Photon engine - https://www.photonengine.com/
Multiplayer episode 1 - https://youtu.be/nmPukdOsYQA
Patreon! https://www.patreon.com/diving_squid
Play my games! https://diving-squid....
With photon
idk if photon has a namespace (like every other code in the world) but id like to note that this code does not have a using statement for anything related to photon.
- Is your IDE configured?
- Are you getting compile errors?
Yes and no
@sharp axle https://gist.github.com/fholm/5fa82cceb6766208ef9dd7b15be4811e here is a better example of CSP
which cuts to the core and does exactly the same as the YT video you linked, w/o overcomplicating
Sweet, I'll check it out. Thanks!
it's as cut down as possible to illustrate the exact functionality
My IDE is configured and im not getting compile errors
in unity mirror how can i do random variable but same on the clients
Get the random number on the server then save that number to a syncvar
i am trying but doesnt work correctly
i wrote this code
do you think is it okey?
and this is checking on the player clienta
I can't help on the specifics, I don't use mirror. But that all looks fine to me. You might need to use the hooks to get exactly when the syncvar changes
why do you have the second if statement, you are setting the value directly above, so it doesn't do anything and it seems like the rest of your code doesn't access it anymore
Hello, I try to Create a server build for my hosted server on digital ocean; do you know if I have to use local ip 127.0.0.1 for this build, or the ip adress of the server ? thx ๐
It should be 0.0.0.0
ok I try; a bit borred, it works 1 week ago, I work in database and now can't conenct my client to the server :/
thanks to help
it seems my server is running, but can't connect the client today
my unity server build is located in root folder, root/gamerserver/mybuild
Hi ! Can someone help me with multiplayer.
I've setup the multiplayer host in Unity Gaming Server and the Lobby too but still don't know what to do next
What are you trying to do? You don't normally need both server hosting and Lobbies
Can i dm you pls?
is there a way with netcode for gameobjects to check the time a client makes a request to the server so that players with higher pings could be competitive and on par with other players to do something first
Hey I have an Issue, I get this error message:https://hatebin.com/ecnkzcusgo whenever I shoot a player that has been respawned. Can anyone help?
the shooting and respawning works fine the first time but once you have died and respawn it doesnt work. And just gives an error message that says Object refence not set to an instance of an object
I think this might be what you need
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networktime-ticks#example-2-using-network-time-to-create-a-synced-event
LocalTime and ServerTime
Are you destroying the player when it respawns?Something is loosing its reference somewhere along the way.
thanks, i think this will be helpful
I cant figure out why one of the functions im calling isnt running
[Client]
public void NetworkSetupClient()
{
if (isOwned)
{
Debug.Log("About to run CmdGlobalInstan");
CmdGlobalInstantiate3PersonModel();
}
}
[Command]
private void CmdGlobalInstantiate3PersonModel()
{
Debug.Log("Running CmdGlobalInstan");
GameObject Model = Instantiate(Resources.Load<GameObject>("SpawnablePrefabs/Square.prefab"));
//Model.transform.parent = ThirdPersonModelHolder.transform;
Model.transform.parent = ThirdPersonModelHolder.transform;
Model.transform.localPosition = Vector3.zero;
Debug.Log("Instanciating 3rdPerson Model");
NetworkServer.Spawn(Model);
}
The CmdGlobalInstantiate3PersonModel function is not running
or at least doesnt spawn the object like i want
I only get the Debug.Log("About to run CmdGlobalInstan"); debug in the console
any help is much appreciated :)
You should specify which networking you are using. But you'll need to check the console logs of the server/host. That's where RPCs sent from the client are actually run.
I use mirror
Hello. I have players drawing lines. They are collected in a list in their own scenes. I want them to draw on their own, and when a button is pressed, they both get eachothers lines. So there are already objects with net IDs in their scene, I want to spawn them for the other client on the button press.
The host client is also the server, and there is one joined client.
My code needs to NetworkServer.Spawn the objects before doing anything with them. This works fine on the server, but the Client cannot spawn unless it is called in a [Command]. However, when trying to pass through the objects I want to spawn into said [Command], it says this is not possible as they are not spawned. so I am unable to send objects to the Command. But I can't spawn them without [Command] when a client tries to run this... What should I do??
You cant pass objects in a RPC like that. You should probably send just an array of Vector3 positions, then have the server spawn them at those locations.
What if I already have those objects spawned at one client? They also have a lot of stuff, like renderer, scripts, ect.
I'm guessing you're using mirror. But normally you can't send reference types like classes over the network. You could try to serialize it into JSON then send that string.
Hear me out!!!
selectedType is an enum
and i can`t network enums if i remember correctly... so how about this?
[ServerRpc(RequireOwnership = false)]
public void BuyFiveCost_1ServerRpc(ServerRpcParams serverRpcParams = default)
{
if (fiveCost_1Bought.Value)
{
return;
}
int playerIndex = NetCodeUI.Instance.GetPlayerDataIndexFromClientId(serverRpcParams.Receive.SenderClientId);
fiveCost_1Bought.Value = true;
PlayerNetwork player = NetworkManager.Singleton.ConnectedClients[serverRpcParams.Receive.SenderClientId].PlayerObject.GetComponent<PlayerNetwork>();
player.moneyResource.Value -= 5;
}
im getting an error when calling this serverrpc saying the client cannot write to this network variable. im a little confused cause the network variable is set that the owner can write to it, and im also calling this in a serverrpc that doesnt require ownership
[ServerRpc]
private void SpendMoneyServerRpc(ulong clientID)
{
if (!IsServer)
{
return;
}
PlayerNetwork player = NetworkManager.Singleton.ConnectedClients[clientID].PlayerObject.GetComponent<PlayerNetwork>();
player.moneyResource.Value -= 5;
}
tried this as well and still getting an error that client cannot write to this network variable
You can also just cast the enum to an int or byte
make sure that the ServerRPC is on a NetworkObject and in a Network Behavior
it is
oh, if moneyResource is set to Owner write permissions then the Server is not going to be able to write to it.
yeah that was the issue. i wrongly assumed server could still write if it was set to owner. thanks!
Yea, there is a mistake in the docs. The server can still read when its set to Owner. I guess it could also be a bug in the Write permissions.
Im making a game using Mirror and I need every client to instantiate their own prefab from resources and i cant figure out how to make every the clients that are not the host to run it
i call my function at ServerChangeScene (an override)
it calls
gamePlayerInstance.GetComponent<NetworkGamePlayerLobby>().GlobalInstantiate3PersonModel();
[Command]
public void GlobalInstantiate3PersonModel()
{
if (!isOwned) { Debug.Log("Not Owned in 3d Model"); return; }
Debug.Log("Running 3rd Person Model Code");
Rpc3PersonModel();
}
[ClientRpc]
public void Rpc3PersonModel()
{
var prefab = Resources.Load("SpawnablePrefabs/Square") as GameObject;
GameObject Model = Instantiate(prefab);
if (Model.GetComponent<NetworkIdentity>() == null)
{
Model.AddComponent<NetworkIdentity>();
}
Model.transform.parent = ThirdPersonModelHolder.transform;
Model.transform.localPosition = Vector3.zero;
ServerSpawn3Model(Model); //TESTING
}
[Command]
private void ServerSpawn3Model(GameObject model)
{
NetworkServer.Spawn(model);
}
it only spawns a prefab on the host client
how can i make it spawn one for every client
i need every client to go to their own resources and spawn their prefab
im relatively new to networking so any help / explanation of what i have to do is very helpful
thanks :D
You can't send a GameObject in a RPC like that. I would keep the prefabs in a list then you can just send the index of the list
public void Rpc3PersonModel
i think the name needs to end with ClientRpc, just to mention one thing
I don't think mirror has that restriction
oh TIL
I could be wrong though
i cant
the prefabs change per client and the changes are unknown to the server / myself
they include cosmetics, etc
If they are unknowm to the server then there is no way to spawn them. If it's a just a unique combination of assets then you can send that config as a JSON. (Head #3, body #1, hat #7)
i save the changes to a prefab
i can spawn them in because i can load them from each client with Resources.Load() etc
i just want to know how to make each client do that
and spawn it in
and for all of these spawns to be known to all other clients etc
so they can see them
if that makes sense
You'll need to serialize those changes as json and then you can send those up to the server so it can spawn them
do i have to do it that way?
i feel like my current method works, i just need to make the loading and spawning code run on every client so there is one for every client
am i wrong?
Clients can't spawn things. They can only instantiate objects locally. The server has to know what to spawn.
i just had to and assign a prefab var at awake for each player and then loop through all the game players and spawn a prefab from each component's prefab
i know but they can send commands to make the server do it
Hello I am a beginner I am looking for help for the network part, I am currently using Photon pun 2 on unity and I would like to know how to transfer data to all users connected to the same room (in my case I just need to transfer an int to all users)
hi there, i am using Mirror on unity and i wanna set a random integer value but it should look the same on server and client side. what can i do?
Hello, I am making an online multiplayer game and for some reason the movement on the client side appears to glide to its destination even using transform.position = Vector3 blah blah blah
Idk why, its only on the client side tho
pls help
when i use a serverrpc to reposition an object, on the host it instantly snaps to the location but on the clients it kind of glides smoothly into position over 500-1000 milliseconds. tbh both look fine but i want it to act consistently one way or another. any way to change this behavior?
nvm fixed it, had to uncheck Interpolate on the Client Network Transform script. was gonna delete the Q but ill leave in case any fellow newbies run into the same thing
tysm
Network Solution: Photon PUN
Issue: Network object (Player) kinda slides and goes back
Using: Transform view on main parent, Rigidbody view on player's body
i have this which should at LEAST make the first person controller rotate, yet it dosent. im assuming this is being overridden by the mirror server but how could I override that?
Are you using a client network transform or a regular network transform? In the normal one the change would be made by the server which would result in latency and the gliding effect
So im trying to send data over to clients but unity crashes every time I call the clientRPC. Ive got no clue on the reason and im attaching images of all the necessary code. The part that is making it crash is the Modifier_RG[][] (second variable on the function)
Also finalTracks.Values is a list<list<modifier_rg>> and im converting it to an array to send it. the parent list usually has a count of 3 and each child usually has a count of 1-2
Also sending arrays because I cant find how to send a dictionary so im just sending the keys and values separately to combine on the clients
Thanks! ๐
in the crash logs its telling me "Modifier_RG[] doesn't implement interface Unity.Netcode.INetworkSerializable" But i do have it implemented as seen on the 2nd picture above
Anyone know the issue?
I'm trying to have an object instantiate and bootstrap all necessary objects for a scene but I'm stuck on the camera in multiplayer. My script instantiates and spawns the host and client player, both works fine:
public void SpawnPlayerServerRpc(ulong clientId)
{
GameObject newPlayer;
newPlayer = (GameObject)Instantiate(playerNetwork);
NetworkObject netObj = newPlayer.GetComponent<NetworkObject>();
newPlayer.SetActive(true);
netObj.SpawnAsPlayerObject(clientId, true);
}
It should then instantiate a player camera and assign all necessary objects to it:
void CameraNetworkStuff()
{
playerCamera = Instantiate(playerCameraPrefab);
playerCameraController = playerCamera.GetComponent<PlayerCameraController>();
mainCamera = Camera.main;
mainCameraController = mainCamera.GetComponent<CameraController>();
playerCameraController.followTarget = NetworkManager.LocalClient.PlayerObject.transform;
playerCameraController.tilemap = mainCameraController.tilemap;
}
This works for the host (both objects, the camera and the tilemap get assigned) but not the client, the client gets a NullReferenceException in this line and the tilemap does not get assigned:
playerCameraController.followTarget = NetworkManager.LocalClient.PlayerObject.transform;
Why?
You'll need to make sure that only the local player is calling the camera function.
I tried this before by asking for IsOwner and the error disappears, but then also no camera gets instantiated for that player, but maybe I am misunderstanding something? It's not a networked object to begin with, it should only exist locally on each player, so there shouldn't be a need to ask for the owner, should there?
I was able to nail my problem down a little more:
void CameraNetworkStuff()
{
playerCamera = Instantiate(playerCameraPrefab);
playerCameraController = playerCamera.GetComponent<PlayerCameraController>();
playerCameraController.followTarget = NetworkManager.LocalClient.PlayerObject.transform;
}
Why would this spawn a camera for the host and assign the transform, but only spawn the camera and not set the transform for the client?
playerCameraController.followTarget stays empty on the client
apparently it's a problem tied to connection and delayed instantiation, I can assign all values if I tie them to a keybind... I guess executing the things in OnSceneLoaded() and OnNetworkSpawn() is not enough as even when the network and scene have been fully loaded there is still a delay for the player object to be spawned. It seems like I am trying to access it here before it has spawned
Hi there, i am using Mirror on unity and i wanna set a random integer value but it should look the same on server and client side. what can i do?
Pick a random number once and send it to everyone
i tried clientRpc and SyncVar but doesnt working
can you give example please
i am searching for 1 weeks about this mechanic
You have to make sure that it's being done on the server first. Then you can just save that number to a syncvar
how can i save to syncVar function
syncvars are variables not functions
is it possible to have a list inside of a networklist?
like NetworkList<List<class>> OR NetworkList<NetworkList<class>>
i did some really scuffed stuff to make this work
if anyone else is having the same problem give us a shout and ill tell you how to workaround it ๐
Was the clientRpc called on the server? If not call it in a serverrpc and make sure, for example via a bool variable or a check if the client calling is the host, that this is executed only once.
Send the clientrpc in the server rpc function
The clientrpc needs to be triggered on the server in order to be send to everyone
For example in some cases, where I want to sync a current state I have code like this in my Project (which uses NGO):
myServerRpc(int num) => myClientRpc(num);
So I just send it trough
After some more research, it seems that you just shouldn't access a recently spawned network object without waiting for at least 1 frame (or alternatively use OnNetworkSpawn() within the spawned object) to avoid accessing it before it has actually spawned and cause a NullReference Exception. Shouldn't this happen to a lot of people? I can't find a lot of information on this.
Does someone know a good way of making sure the object has spawned and is in the scene? My only idea is trying to find the object in the Update-loop (e.g. in the case of the player object by its ID) and then assigning values to it
hi guys,i would create a VR game and i am using Photon Fusion but i am having troubles with it,is Netcode good for VR games?
netcode and VR are unrelated, you can make a VR game with any netcode library
i intended,if i would use netcode to create my vr game is the service good like approsimation of object ecc...
cause i used photon and i did not like it
if you expect some sort of plug and play solution to make a networked game you will not be happy with any of the commonly recommended libraries, in practically all situations netcode involves A LOT of custom work
For VR i am using the Interaction Toolkit,i want to pass to Netcode cause it is done by unity
I get an error that my script isnt a component
I use Photon.Pun and if I change MonoBehaviour to MonoBehaviourPun, would it change something?
[Netcode for Gameobjects] If somebody was to spawn a player mid game, would you use SpawnWithOwnership or SpawnAsPlayerObject?
If you are spawning the player then use SpawnAsPlayerObject
here is the code I've written. When I spawn the player using SpawnAsPlayerObject, on the server, both players have isowner checked and the new player has islocalplayer checked, would you happen to know why that is? @sharp axle
PUN 2: If I try I can't join the game from the build on the editor or vise versa. It works fine from build to build but thats not optimal for troubleshooting. If you need any more information just request it
I get an error that my script isnt a
A couple of things here.
Network object reference is only used for objects that have already been spawned.
You don't have to send client id, ServerRpcParams already sends it.
You need to instantiate the object before you can spawn it.
Thanks a lot for the help. How would I let the server know which prefab to spawn and where should I instantiate it then? I am using a callback to spawn the player as shown below:
I keep a list of prefabs on a player manager. The player chooses a character then sends that index to the server.
Normally I just instantiate it right before I call SpawnAsPlayerObject
I keep a list of prefabs on a player
I am trying to use UTP but i am not using NGO, my question is, is there a way to send some authentication info with the connect message from the client? So that server can decide to accept or reject a connection?
I am getting confusing information when googling, are there any limitations for using Steam when using netcode or is it completely compatible?
in specific I heard there were issues with steam relay
I'm not aware of any issues with Steam Relay. You will just have to use one of the custom Steam Transports that the community has made.
hi guys,sorry for my ignorance but i don't understand how netcode works,what is the difference between netcode for gameobjects and relay?
i saw that there are various plans in the unity page
Netcode is just the network library. The Relay Service is what would be used to actually connect the player host to the clients. You can also choose to use a Dedicated Server hosting service and not use Relay at all.
ah ok,now i am following a tutorial of netcode but how is possible that i manage to start games like host and join like client without using relay or dedicated servers?
this one to be clear
If you are running them on the same machine or on the same LAN, there is no need for it to use the internet
Ah ok so i was using the Lan?
Any pointers as to why my ServerRpc only gets executed while running as Host, but if I run it as a Server it calls the ServeRpc function fine with no errors but doesn't actually execute it?
Server can not call a ServerRPC. Only clients can call them. The host is also a client
Well shoot I misunderstood how ServerRPCs work then. I understand what I need to do now, thanks a-lot.
PUN 2: If I try I can't join the game from the build on the editor or vise versa. It works fine from build to build but thats not optimal for troubleshooting. If you need any more information just request it
Netcode for game objects, it may be unavoidable but does anyone know how to minimize lag and delay when client spawns in projectiles? I have a client shooting and thereโs pretty noticeable delay on the object spawning in and flying
You'll need to so some client prediction. Basically spawn the projectile locally immediately. If its going in a straight line then its easy enough to sync it with the server location.
Thanks a lot dawg ๐
hi all, I'm new to networking in unity and been following the Relay with UTP examples, can I just plug RPC stuff straight into that?
It should work. But if you're new then you really should be using the Relay with NGO example
Thanks
Whatโs the benefit of using NGO over UTP out of curiosity?
UTP is very low level. Basically dealing with socket connections directly. Plus RPCs are already part of NGO so you are already using it.
right gotcha, thanks!
hi guys i am using netcode and i don't find the component "client network transform",has been modifyed?
You can create your own or grab one from github
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform#clientnetworktransform
The position, rotation, and scale of a NetworkObject is normally only synchronized once (when that object spawns). To synchronize position, rotation, and scale at real-time during the game, you must use a NetworkTransform component. NetworkTransform synchronizes the transform from server object to the clients.
solved thanks
hi i'm following the NGO docs and we want to implement Relay with join codes. On the docs it doesn't say much about where the relay stuff needs to go to request an allocation, anyone able to shed some light?
brilliant, got it up and all working now. Thank you very much for the help ๐
why do I get an error that ClientRpc method must end in ClientRpc suffix even though it's called TestClientRpc literally from the first tutorial on the netcode site?
Are you sure there isn't a typo somewhere?
nope, I just pasted the file from the tutorial page
Make sure the player has a Network Object on it
it did. re-opened unity and re-pasted it and it works now. it is identical to the old version so in my opinion it was probably some unicode related shit. thank you very much for your help!
I was wondering like how the games work which are just 1v1 games like clash royale like do they host a server when we click play because I am trying to make something like that and I am only able to find tutorials that help making a full lobby by hosting and joining, How can I actually make a peer to peer 1 v1 multiplayer which is random ?
when using relays is it normal for other players movement other than your own to look jittery if you uncheck interpolate on the client network transform script? looks fine with interpolate on but i was hoping to keep it off for some other reasons
in my game each player has their own board, and the players can teleport to each board. i wanted interpolate off cause they do this thing where they kinda glide/zoom to the board theyre teleporting to instead of the transforms position updating immediately and them snapping into position
or instead of turning interpolation off, is there a way I can make the teleporting look more normal instead of characters sliding around?
ahm hello im getting confused on how to do lag compensation in photon
i have no clue from where to start fixing any existing problems
fr i dont even know if it works
what do i do to make player movement "smooth"?
in NGO is there an easy way to reference clients from a client (not the server)? if i need to do something in a serverrpc it's easy to reference NetworkManager.Singleton.ConnectedClients list with the serverrpcparams, but if i need to do something in a clientrpc im not sure how to access a similar list since only the server can access ConnectedClients
You have to make your own. I usually just have the player object save itself to a list in OnNetworkSpawn
When finding the distance between a client and an enemy, I run the command every frame to detect distance, all that is changing is the enemies and clients position by very small increments, yet I get random extreme outliers like this (see distance from target). Any ideas on how I can fix this. Btw both the client and host are run from the same pc so I don't think its a lag problem. Help with this would be greatly appreciated.
I think the best approach with PUN is to use the Smooth Sync package from the Asset Store. Heard good things about it and it possibly does what you want without need to explain it.
You need some server for the matchmaking. Once players found one another, some network solutions will attempt to connect the peers directly. Depending on the platform, this may work better or worse, so you usually want some alternative connection path...
The networking you "need" depends on what you try to achieve. The genre, interaction and platform. How players connect is probably not important in the end.
Is the network manager part of paid unity? If it isn't, how do I access it?
can the length of join codes be altered?
Please help.
You using NGO im assuming?
If so it shouldnโt be, you need to make sure you have the Network for GameObjects package installed. Itโll then just be a script you attach
What's NGO?
Network for GameObjects
Have you got any net code working at the moment or are you starting for the first time?
If you're learning networking, use this https://docs-multiplayer.unity3d.com/netcode/current/about
It's more newcomer friendly that writing something yourself.
Learn more about the available APIs for Unity Multiplayer Networking, including Netcode for GameObjects and Transport.
There's a page explaining getting started stuff, including your NetworkManager script https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo
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).
Matchmaking is available on Unity Gaming Services right , Can I just use it?
I am not a specialist in multiplayer and tbh I hate photonand all 3rd party things
For rn I have no Ideas on matchamking but I think I want bothplayers to connect on server and play there as its just a turn based board game
I am trying something of miniclip's 8 ball pool style, they actually run the game on client side and all the data is transferred to server , compared and then sent to the players so server makes calculations and the game runs totally on client side
whevener i try connect to photon (pun) i get this error.
should a host instance type invoke OnClientConnectedCallback ?
because for me it doesn't
Using a unity server for that is most likely overkill. Many mobile games use a custom lightweight server made in .Net or something that run several hundred instances on a machine.
If the server is doing very little consider looking into Unity Cloud Code. It has matchmaker integration and can probably do the compare calculations you need without expensive servers.
Clients should get their own Onclientconnected event, yes. But they won't see the other client's connection event
I'm pretty sure join codes are always the same length
i know that, my problem is is that by using a host instance, which is both a server and a client, it doesnt invoke the callback as a client (the OnClientConnectedCallback on the server part of the host)
That's odd, the host should see it twice.
Find the PhotonServerSettings asset in the project and copy paste a PUN / Realtime AppId from your Photon Dashboard into the field for the AppId. Maybe copying went wrong or so.
Then forget about my reply. I work on Photon...
Joke aside: You should not worry about matchmaking in the beginning. Get the actual multiplayer stuff working and fun and you can easily wrap it with whatever matchmaking you chose.
Hey guys, I have a very strange issue and I could use some advice in solving it
Working on a multiplayer game, and players can place rule tiles on the tilemap. The tiles have a game object attached to them.
This works, but there is a weird issue. On client only, the tile spawns at world center very large, before flying into place from
0, 0, 0 and resizing itself to fit where it should be.
While its funny and im glad that it works, I would like the tile to just appear on clients like it does on host. Any idea how to fix?
@alpine pulsar Thanks, that helps a lot.
np
Sorry I don't get wdym by overkill
Btw thanks for the cloud code thing, it feels like the thing I need
A unity server is running the full game engine. If you don't need the complex physics simulation or Animations or running GameObject scripts then that's a lot of wasted processing that you're going to be paying for.
Ok,I get it what you say
using photon, how would i get the transform of an instantiated object
this might be obvious but this is my first time working with photon forgive me
(i tried just .transform)
maybe the issue is the GetComponent?
is it because i'm trying to set it's values before it's even instantiated?
how would i wait for it
please help
are there any tutorials on how to integrate KCC (https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131) with netcode for game objects?
How do I get a player to spawn at Y 1 using the Network Manager?
Like without using spawn points? If there isn't, how do I get access to the Network Manager spawn point thing?
With csp or just client auth?
Hello. I have a coroutine on server side which needs to call coroutines on clients side.
private void MyFunction() {
if (IsServer) {
StartCoroutine(ServerRoutine());
}
}
private IEnumerator ServerRoutine() {
ClientRoutineClientRpc();
yield return new WaitForSeconds(1);
playsound();
yield return new WaitForSeconds(6);
}
[ClientRpc]
private IEnumerator ClientRoutineClientRpc() {
yield return new WaitForSeconds(1);
displaySomething();
yield return new WaitForSeconds(2);
displayAnotherThing();
}
The problem is that ClientRpc function cannot return IEnumerator .
How to solve this use case ? I need that the server routine wait until all clients have completed their own routine.
U here too ๐
Iโm Batman
a watchful protector
anyone know how I can pass a list of strings to the client from the host in netcode and also need to sync a char multi-dimensional array somehow
Guys got a little networking issue, I have a swing animation play on players. It works on each player, but when you see another player in game doing it the animation just plays underneath them. Normally there is an object that rotates in the direction your mouse is, so the swing plays in that direction. How can I sync the animation to play in the proper direction in the network animator
Someone please
I am so utterly confused right now
This is a long one, basically:
I have a method that changes the character the player is playing as (which just changes a variable right now)
in the player controller i do this
and then in that CharacterPickController I do all this
and this is how the player manager handles it all
Yet, the characters aren't synced
When I press U and I on the unity build, I can see the player manager changing the character
But when I press them on the build, I can't see the character changing for that player
First time working with netcoding and everything and I am losing my mind
I can send the full codes of all of them if it's needed
Beginner Question: so lets say i have a dungeon/map consisting of multiple rooms that are getting generated randomly and right now ive been trying to spawn it on the server first and then copy and paste it on all clients with server and clientrpcs, but now im thinking if it wouldnt be easier to just spawn the dungeon as a whole on the network instead. but then again that could put a bigger strain on the performance right? so i guess what im asking is, what do you guys think is a better approach
any, im nostly interested in how KCC interacts with netcode or should interact with it
depends on if u want client auth (then it wont matter, jsut runt he KCC and send pos/rot of transform to other clients)
or if u want server auth
then u need CSP
client side preidction
but if i just send pos / rot, dont i miss out on all the kcc goodness on the server? instead, shouldnt i just send the input and let the kcc motor handle it?
I'm trying to connect to the game with networking but it's not working. I put the IP address in on both of my laptops but I don't know what's wrong. if you want we can go into a chat and figure this out
so i assume i actually need to use fusion
is there any way to not just be forced to start over if i have a pun 2 game already
not exactly against starting over since i don't have much done but just asking
if its client auth it doesnt matter as the simulationwill be in the client, if server auth you need to send your inputs and then play it in the server
and on client side you need to use CSP as fholm mentioned
When I start a host in my game, the player used to spawn in, but now that I added a bit of code to make multiplayer work properly, it doesn't. Can anybody help?
This is the code:
using UnityEngine;
public class PlayerSetup : NetworkBehaviour
{
[SerializeField]
Behaviour[] componentsToDisable;
private bool isLocalPlayer;
void Start ()
{
if (!isLocalPlayer)
{
for (int i = 0; i < componentsToDisable.Length; i++)
{
componentsToDisable[i].enabled = false;
}
}
}
}```
@stiff charm?
Anybody?
I'm getting this warning if it's helpful:
NullReferenceException: Object reference not set to an instance of an object
None of those fields are going to be set for the player. isLocalPlayer is not going to be set until after OnNetworkSpawn()
I fixed it. I changed !isLocalPlayer to IsLocalPlayer and removed the private bool isLocalPlayer;.
Now I just need help with my other problem of getting a player to spawn in a certain place without using spawnpoints.
It's been sixty years since I posted a question similar to yours. I still haven't got a reply.
I'm using a KCC for movement and using client authoritative movement with my players. Everything is looking crisp. I want to add a rigidbody ball in the scene, which all clients should be able to push around. I've added NetworkObject, ClientNetworkTransform, Rigidbody and NetworkRigidbody components to it. The problem is that only the client on my host instance can move it for some reason. The player on the client instance simply gets stuck next to it, without being able to push it.
Any ideas why?
I've tried every imaginable configuration: players with server autoritative movement, removing the NetworkRigidbody component on the ball, NetworkTransform instead of ClientNetworkTransforms on the ball, etc.
Because there is no shared physics system or physics prediction in NGO
Hi guys i am using netcode lobby and i have this issue with my code,when i create a lobby i store the result in a variable called "currentLobby",than when a player join the lobby in his "currentLobby" variable he can see 2 player,while in the "currentLobby" of the host i can just see 1 player,how can i solve this problem?
Thank you for your reply. what i dont understand is, if the server instance sees the client player with its collider and rigidbody hit the ball, from the server instance's perspective they are just 2 rigidbodies interacting, so why doesn't it just update the new ball and client player positions based on that collision?
That's what i'm thinking. so under normal circumstances with a simple controlller, the ball should move both on the client and host, right?
Yes but the movement on the clients will be delayed
that's fine, i'm just trying to make it move for now. wonder if i should switch out my kcc package
if I want movement to be server authoritative and i want to use a kcc setup, is it best practice to run the kcc locally, send the new position to the server and have server side integrity checks, or just send the input to the server and let that handle everything?
actually, the second option would have terrible input lag and a horrible experience, no?
yes, like i said you need client side prediction if u want server auth
but that still wont solve your physics issue
because the client wont be able to push the rigidbody on his game anyway
and he will mis-predict anytime that he moves into a rigidbody
(i.e. it will get pushed on server, but it will block you on client temporarily)
leading to jitter and mis-predictions
can anyon help me with my script
the problem is
that im trying to set a string for the nickname
but its not showing up
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class RoomManager : MonoBehaviourPunCallbacks
{
public static RoomManager instance;
public GameObject player;
[Space]
public Transform spawnPoint;
[Space]
public GameObject roomCam;
[Space]
public GameObject nameUI;
public GameObject connectingUI;
private string nickname = "unnamed";
void Awake()
{
instance = this;
}
public void ChangeNickname(string _name)
{
nickname = _name;
}
public void JoinRoomButtonPressed()
{
Debug.Log("Connecting...");
PhotonNetwork.ConnectUsingSettings();
nameUI.SetActive(false);
connectingUI.SetActive(true);
}
// Start is called before the first frame update
void Start()
{
}
public override void OnConnectedToMaster()
{
base.OnConnectedToMaster();
Debug.Log("Connected to Server");
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
base.OnJoinedLobby();
PhotonNetwork.JoinOrCreateRoom("test", null, null);
Debug.Log("We're in the lobby");
}
public override void OnJoinedRoom()
{
base.OnJoinedRoom();
Debug.Log("We're connected and in a room!");
roomCam.SetActive(false);
SpawnPlayer();
}
public void SpawnPlayer()
{
GameObject _player = PhotonNetwork.Instantiate(player.name, spawnPoint.position, Quaternion.identity);
_player.GetComponent<PlayerSetup>().IsLocalPlayer();
_player.GetComponent<PlayerHealth>().isLocalPlayer = true;
_player.GetComponent<PhotonView>().RPC("SetNickname", RpcTarget.All, nickname);
}
}
can anyon help me with my script
the problem is
that im trying to set a string for the nickname
but its not showing up
the string will be set in a different script here
using System.Collections;
using System.Collections.Generic;
using Photon.Pun;
using UnityEngine;
public class PlayerSetup : MonoBehaviour
{
public FirstPersonController movement;
public GameObject camera;
public string nickname;
public void IsLocalPlayer()
{
movement.enabled = true;
camera.SetActive(true);
}
[PunRPC]
public void SetNickname(string _name)
{
nickname = _name;
}
}```
Which solution i should use for client-dedicated server model when i want place my server on my own linux machine?
is there a certain version this became available ?
https://docs.unity.com/lobby/en/manual/lobby-events, bc SubscribeToLobbyEventsAsync doesnt exist in 1.0.3 or am i just suppose to poll the lobbie to get updates ?
Netcode for GameObjects Integrated Scene Management
Any of them should work with Linux. I could be mistaken, but I think photon is the only one that's not self hosted.
whatever offers the best performance for your use case, better perf = cheaper servers/more players per server, which lowers hosting costs
is there a KCC that you guys recommend which works well with client authoritative architectures? currently i am using https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131 and I love it, but it's built around a server auth model.
I did that but my network prefabs didnโt spawn in
A KCC just provides you with a function to move an object. You can use it in any networking architecture.
If I have the buttons to activate a player spawn in one scene (scene A), but the network manager responsible for the spawning in another (scene B), will the spawn still work? Also, if I have code in scene A that sends me to scene B when I press start, will that spawn the player?
im when I initializeasync() and someone is connected to the internet, everything works fine, however, when they dont have internet, my catch is not catching the error. what do I need to do to run the code inside the catch block if the initialilize async is not successful?
private async void AuthenticateUser()
{
// Authenticating using a guest user
try
{
await UnityServices.InitializeAsync();
AuthenticationService.Instance.SignedIn += () =>
{
Debug.Log("Signed in using ID: " + AuthenticationService.Instance.PlayerId);
theMenu.SetActive(true);
};
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
catch (AuthenticationException error)
{
ErrorHandler.Instance.HandleError(error.ErrorCode, "Error Authenticating User");
}
}
Do people just ignore networking until they have a problem or something?
@raven pond here is the networking discord https://discord.gg/unity-multiplayer-network
they might be able to helpo you too
Thanks.
hello everyone
I have a simple problem with PUN 2
that's my error and I've tried everything to fix it
show some code
the code is like 665 lines though
show the code block thats causing the error
what kind of object is Extensions
I am not sure, I imported PUN 2 and then I got that error
try replacing tostringfull with ToString(properties)
how can i make text update across all screens in netcode
do i just attach a network obj component
hmm. did you write this code?
do it and see
nope, PUN 2 is to implement multiplayer
is the error causing your game not to be able to run?
i did and it did not work
thought thats how youd do it ho
are they hosts and clients?
yes
PUN discord server is not active nor is responding to anyone
hence me coming to the unity server
can you explain to me when and when not a network object would update on all screens, cause Im running the following method when both my client and host player win and nothing happens ``` public void win(int playernum)
{
winText.text = "Player " + (playernum + 1) + " Wins!";
}```
i would watch a video on netcode for game objects to learn the basics of everything. you dont have to watch everything but skip through to find what you need. but the basics of how network objects communicate between each other is very good to know
โค Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
๐ Get my Complete Courses! โ
https://unitycodemonkey.com/courses
๐ Click on Show More
๐ฎ Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubre...
yeah ive watched that one, I have almost a full game made with coorelating colors to each player i just cant figure out this win condition
also that video does use relay or any of that which caused some odd errors
โค Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
โ
Learn more about Relay and UGS https://on.unity.com/3tQZLLW
๐ Relay Docs https://on.unity.com/3OjXL8z
๐ Get my Complete Courses! โ
https://unitycodemonkey.com/courses
๐ Learn to make awesome games step-by-step from start to finish.
๐ Click on Show More
๐ฎ Ge...
heres for relay
i saw that one too ill just figure it out haha
he doesnt go much into ui
unless youre using the lobby plugin
if he includes project files, i suggest downloading and playign around with it. there are also sample files on the official unity netcode for game objects documentation
if someone familiar with netcode wanna just vc for 5 misn
does anyone know how to use photon?
Is someone intelligent able to help me here?
I'm trying to get a player to spawn a bit off the ground, and I can't seem to figure out if spawn points exist in Unity.
what I did was naming an empty GameObject "Spawn" I searched it in the scene and just set the player position to the spawn position. Not really happy with that, but it works most times, if someone has a different approch, let me know
for better placing add a capsule colider, set it to the player size and disable it, if you have gizmos on you can see how high the player will be spawning
Ok.
Whats the best way to detect if the host left/disconnected/crashed, to disconnect Clients?
Thats how i currently do it, but it feels dirty ._.
private void OnEnable() {
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback;
}
private void OnDisable() {
NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnectCallback;
}
private void OnClientDisconnectCallback(ulong id) {
Debug.Log("OnClientDisconnectCallback: " + id.ToString());
if (IsClient) {
if (id == 0) { // 0 = host?!
LobbySaver.instance.currentLobby?.Leave();
LobbySaver.instance.currentLobby = null;
SceneManager.LoadScene("MainMenu");
}
}
}
I use NGO with Facepunch Transport
The only problem i have with that is that if the host loses internet connection, it takes a bit for it to fire on the clients, but unfortunately, the OnClientDisconnectCallback does not get called on the host without internet anymore, so he stays in the scene ._. (yeh i know i ask for "isClient" for the actual action, but the debug log does not appear on host side, so it does not get fired)
Hey guys I have more of a general question. The docs often state that Netcode for Gameobjects is meant for "co-op" multiplayer games specifically. Is there a reason it's not suitable to use in non co-op games, like 1v1 PvP matches? I'm working on a fighting game which is obviously not co-op, so I'm wondering if I should use another multiplayer solution for that
I'm referring to statements like this in official Unity docs : "Netcode for GameObjects is Unity's new netcode library. Netcode for GameObjects is the evolution of MLAPI, and it is created so you can use it to set up and program smaller-scale, co-operative client-hosted networked experiences"
A fighting game should be done using deterministic rollback netcode
Usually
Yes, but ignoring that specific thing, I'm trying to ask if there is something in NGO that makes it inherently not suited for game that are competitive instead of co-op
That is the main reason. You have to implement your own rollback Netcode and the physics is nondeterministic
Competitive games usually have a tick aligned simulation for accuracy and then either use state-sync with client side prediction or deterministic rollback to reduce perceived latency. NGO provides neither so you have to build them yourself (which is very hard to do right)
Nothing really stopping it from being done in NGO, but Netcode for Entities or Photon Fusion would be a better match for faster paced competitive games
Is this worth learning right now? Waiting for actual mp support to move back to unity
Okay, thank you both for your replies ๐ for my particular game having those things is not necessary to begin with, so I feel more comfortable continuing with NGO
Feel free to hit us up over on the Netcode Discord that was linked above. I'm a mod there
Man NGO is so frustrating, specially if you depend on the community Transports. So many essential stuff missing in general, in the transport i am using, or it's broken in the transport 
Think i'm gonna switch to Mirror and FizzyFacepunch
Amazing thanks, just joined!
Hello everyone, I'm making my first (serious) multiplayer game and I need help with a bit of design philosophy:
- Each of my weapons has 4 tiers, each tier dealing more damage per bullet than the last one
Now, I'm using the same bullet prefab for each tier, and in the moment of the shot I go into the instantiated bullet and change the values according to the weapon that fired it (this is only working locally for now). Thing is, I believe that doing this every time anyone shoots a bullet and having to let every player know about this change might be a bit heavy network wise, so my other option is to create a new bullet prefab for each tier and shooting the correct bullet, so everyone already has the right values by default.^
Is the second option the best or am I overthinking the first option? Any other solutions that you might have? Thanks!
Hi guys,if i am a client and i would send a message to the host of the session via RPC how can i do it?
cause i tryed with [ServerRpc] and [ClientRpc] and the message doesn't arrive
As long as the server is keeping track of everyone's weapon, what you have should be fine. Probably would be easiest to have a netvar assigned for the weapon tier that way everyone gets automatically updated
but I would still need to "inform" the bullet of what tier weapon shot it no?
Is the weapon itself not the one assigning bullet data?
So, the weapon is a scriptable object, I instantiate the bullet and get the bullet script and set the values
I hate this channel just throw it in the trash (pssโฆ did u know i hate networking ๐
anyone can help me with this on multiplay server allocation :
Server exit: triggering deallocation (exit: 139, signal: signal 0)
This error keeps crashing my server , what could be the cause ?
i think so. netcode for game objects is there actual mp support and its finally here
using lobby, relay, and netcode for game objects is what im doing and it definitely has a steep learning curve but because its all first party, i love it
So netcode has built in listen server support and stuff?
depends on what you mean by listen server. You can host a dedicated server wherever.
Like unreal engines listen server, a client hosts the game and players connect to that client, does it work on a global scale?
Using the Relay Service, yea.
Is it free?
There is a free tier, but its a paid service
You can also use Steam P2P or Epic Online Service's Relay
Isn't epics free if it's on their marketplace or som
I've never used it. But AFAIK, there are no restrictions on it
Steams is free as well, if it is on their market place, which will cost you 100$
Hey, seeking advice from some people experienced with networking. I am looking into Unity's Netcode for GameObjects. Is this something you would consider a good option for networking in games? Personally it seems a bit weird that everything is run on the same codebase. Very interested to hear some more experienced opinions on this subject though.
most games run on the "same code" base for server/client
Really depends on the type of game. NGO is mainly geared for smaller co op games.
does it have any obvious drawbacks for the simplicity it provides?
It does lack some features like prediction and stuff like that
hm, and when hosting as a server, will you have to run the server through the game?
It does support a dedicated server setup but it is more focused on client/server p2p
You can have these p2p structres hosted by unitys own solution relay, host it on your own, or switch out the transform and use steams/epics/whatever solution
So you don't have to host the server through the game, you can hwve a server build, but for most games on this scale a host(so client and server on the same machine) would be a good solution
Searched it in the scene?
I take it that the NetworkStartPosition doesn't exist anymore?
Using Unity NGO, consider a game where there is a dungeon scene loaded and running on a server. Any given client should only have this dungeon scene loaded if they are actually inside the dungeon, and can join/leave the dungeon at any time. Is this possible?
I am worried that many NetworkObjects will rely on RPC's that throw errors if a client does not have a copy of the object loaded on their game.
In unity Netcode, that never existed. You you are spawning an object manually, then it will spawn at whatever location it was instantiated at. Or whatever position it was at when Spawn() is called.
If you are spawning the player object automatically through the network manager, then you can use Connection Approval to change the spawn position.
You will need to use custom scene management in this case. By default all scenes loaded on the server are automatically replicated to the clients.
Thank you, I'd gotten that far, but I'm wondering how I can call RPC's and such on objects that exist in a scene not shared by all clients. It seems to require the object to be spawned with NetworkServer.Spawn(), which then tries to instantiate the object on clients where the scene isn't even loaded
The dungeon manager in question (a network object in the dungeon scene), calls an RPC basically requesting that the server generates the dungeon with a random seed if it doesn't exist, but if it does already exist, the client will call some kind of sync function, retrieving the seed, generating the dungeon, sync-ing enemy health values, etc.
The problem is that the RPC's don't seem to fire because the network object has not been "spawned" and spawning it with scenes only loaded on some of the clients causes errors in my experience so far
Ah. OK.
Sounds like the dungeon manager needs to exist outside of the dungeon. Are you using NetworkHide() on the dungeon when players are outside of it?
Even if the Dungeon Manager exists outside of the dungeon, I thought all of the other network objects in the dungeon scene (enemies) would have the same problem, so I figured I was doing something else wrong?
And no, I'm not familiar with NetworkHide()
Its called Object Visibility in the docs. You for things in the dungeon, you can keep a list on clients in it and only send clientRPCs to those still in the dungeon.
https://docs-multiplayer.unity3d.com/netcode/current/basics/object-visibility
What Is NetworkObject Visibility?
That sounds useful, I'll look into that! Thank you 
So I have a few objects around my scene that I'm using as spawn points, and I have tried many scripts to get the player to choose one randomly and spawn at it, but none of them have worked. Can someone help?
Have you looked at the ClientDriven Sample
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven/#server-side-player-spawn-points
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
Ah, if I'd changed FOUR WORDS in my script I would have had that. I wondered why it wasn't looking normal. Thanks.
With Facepunch Transport, whats the best way to retrieve the SteamID in a OnClientConnected & OnClientDisconnected Event? The Id's on the networkmanager of course are no steamid's but just 0(host), 1, 2, 3, ..... (clients). So i wonder if there is a proper way to do so, or do i have to manually assign it through the steam lobby?
is there a way to create a private scene just for a lobby?
like everyone in a lobby would be moved to a new scene
you figured that out meanwhile? Also need to know ๐
Hi guys quick question,let's say that there are 2 players and a ball,let's call the players blu player and red player,the ownership of the ball is of the blue player,i want that if the red player touch the ball it apply a force to the ball,my question is if the red player doesn't have the ownership on the ball can he apply the force to the ball?
and than on the screen also the blue player can see the ball moved
how can I tell server from client to despawn certain object? because when i pass gameobject as parameter to ServerRpc method, it gives me an error: Don't know how to serialize GameObject
how would i go about changing the colour of connected players as they join (i.e. p1 is green, p2 is red, etc.)?
If you are using Unity Netcode, then you need to send it as a NetworkObjectReference
I would use a Network Variable to set the Color for the player
Hi, i have a problem that i want to be able to change the color of the same cube from server and from client, however when im calling the OnValueChanged function the Network Variable is not updated on my client, i've tried debugging stuff and in the function the value of netvar is 3 as it should be, but in inspector it's always 0 and in debug after using the function, the netvar goes again to 0. I even tried to assign the updated value from the function to a local variable but it had the same issue of going back to 0
Link to the code: https://gdl.space/xifimamire.cs
Hello! I would like some advice please. I have a little 2D platformer game that I would like to be able to play online with friends. I have attmepted to do the networking via Photon Pun, until I realized that it was severely laggy and depricated. Then I attempted to use Photon Fusion and failed miserably. (it caused a few grey hairs probably). Can you suggest a different tool to me that you had positive experiences with?
I don't think clients can access the spawn manager spawned object list. But you could also just add a color network variable and that will sync to all clients
Retrofitting networking into a existing single player ga!e is always going to be a bad time. A complete rewrite is usually in order.
can this be the issue for my variable resetting to 0?
Because the manager spawned object list is called after i try to get the cubeId value and my main problem is in the value, the list won't work for sure as the value i try to send into the rpc functions is always 0
If it's been spawned then you can just send a NetworkObjectReference
send it through what?
in your RPC
did you mean smth like that? https://gdl.space/umalukumev.cs
i'm just not sure how a NetworkObjectReference works and didn't find any examples of its use
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
ok i still can't understand, from what i read here you need to have a reference for an object to use it, but i don't have a reference for my spawned object on my client
here i changed the serverRpc and now use the NetworkObjectReference, but have no idea how to use it on clients side: https://gdl.space/onuzokuyuz.cs
Is there a way to LoadSceneAsync through Unity's NGO Scene Manager?
The network object can be implicitly cast into a network object reference and back
but how do i get the network object if i have no object reference on client?
if its spawned then you can get the reference
i can use that no problems on host because it has the reference because the host was the one who created the object, how does sending the NetworkObjectReference into an Rpc help the client get the reference?
i'm sorry im just like really lost in here๐
you can just (NetworkObject)netObjRef to get the object
all scene loading in NGO is async
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/using-networkscenemanager
Netcode for GameObjects Integrated Scene Management
No way to do something like this though?
asyncOperation = SceneManager.LoadSceneAsync(nextScene.ToString(), loadSceneMode);```
so just
[SerializeField]public NetworkObjectReference objref = new NetworkObjectReference();
spawnedCube.GetComponent<NetworkObject>().Spawn();
objref = spawnedCube;
and then in client when i need the reference i do
(NetworkObject)objref
?
for loading screens
You can sub to OnSceneEvent
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events#tracking-event-notifications-onsceneevent
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
basically, yea
Well now im just getting a nullref, the host still gets the reference to the object and changes its color just fine, it's again the client that's the problem
is this the right way of assigning a NetworkObjectReference?
private void assignIdServerRpc(NetworkObjectReference networkObject){
if(networkObject.TryGet(out NetworkObject obj)){
objref = obj;
}
else{
Debug.Log("Didn't find any objects");
}
}
then in RPC (networkObjectId is the objref)
private void greenClientRpc(NetworkObjectReference networkObjectId){
NetworkObject w = (NetworkObject)networkObjectId;
w.gameObject.GetComponent<MeshRenderer>().material.color = Color.green;
}
You don't have to do this bit. As long as the object has been spawned and hasn't been destroyed, you can (NetworkObjectReference)obj
But if you are just changing colors it would be way easier to just have a color network variable rather than dealing with RPCs
So just objref = (NetworkObjectReference)spawnedCube; after the cube was spawned?
The thing is that i want to create something bigger but got hardstuck on this part and try to deal at least with something as simple as change the color
ok so it goes like this:
private NetworkObjectReference objref = new NetworkObjectReference();
if(IsServer){
spawnedCube = Instantiate(cubePrefab);
spawnedCube.GetComponent<NetworkObject>().Spawn();
objref = spawnedCube.GetComponent<NetworkObject>();
}
and that's it for the host
now on client
startGreenServerRpc(objref);
private void startGreenServerRpc(NetworkObjectReference networkObjectId){
greenClientRpc(networkObjectId);
}
private void greenClientRpc(NetworkObjectReference networkObjectId){
NetworkObject w = (NetworkObject)networkObjectId;
w.gameObject.GetComponent<MeshRenderer>().material.color = Color.green;
}
and im still getting nullref for client
which reference is null? The network object reference or the network object? It could also be the gameobject or meshrenderer. or even the material if there is not one assigned
oh sorry, it is the networkObjectId in greenClientRpc
ok i see. objref is only getting set on the server. so on the client its still null. startGreenServerRpc(objref) on the client can just have the spawned cube object as the parameter
so now i've changed it to startGreenServerRpc(spawnedCube); and it shows an error ArgumentNullException: Value cannot be null. Parameter name: gameObject
and if i change it to startGreenServerRpc(spawnedCube.GetComponent<NetworkObject>()); i get UnassignedReferenceException: The variable spawnedCube of PlayerNetwork has not been assigned.You probably need to assign the spawnedCube variable of the PlayerNetwork script in the inspector.
Right, spawned cube is also only get set on the server. You'll need to find it on the client. Either use GameObject.Find() or have a script on the cube that assigns itself to spawnedCube
Ok so FindWithTag sure works thank god on that, also wouldn't i also need to somehow find the needed client in the cube script?
Just tried like 5 methods of using NetworkVariable, different ways of NetworkObjectReference and it all boiled down to finding with tag, anyway huge thanks for all the help you've provided, ill maybe try to use those on a clean project (because who knows) but itll be whatever time later
If you wanted to change the color of the cube for everyone then you don't really need to specify a client
oh yea i remember that i wanted to do it that way once too, but if i was a client i still like didn't know how to get the reference of that object with the script๐
yo guys i just realized making a multiplayer game is prettyyyy hard
basically 0 tutorials on how to do it properly
There are a few good channels like Code Monkey. But tutorials are tough because it's wildly different for every game.
Hello. I am trying to instantiate bullet objects for my players but only the host is able to spawn bullets.
Does anyone know what Im doing wrong?
The prefab is a network object and its been added to my network manager
maybe watch this vid i dunno for sure but might help
https://youtu.be/j6XPp_RHI9Q
This Unity Multiplayer tutorial will teach you how to spawn and destroy objects over the network as well as assigning client authority. For project files access, check out the repository here: https://github.com/DapperDino/Unity-Multiplayer-Tutorials
------------------------------------------------------------------------------------------------...
he's doing exactly what you have problem with- spawns objects from different instances
You are getting your input from inside the serverRPC, which only runs on the host/server. You need to call the serverRPC after you get the input from the local player
Hey there I am working on a game using PUN with alot of projectile... currently I am using PhotonNetwork.Instantiate function to spawn bullets but bullets are lagging way too much...any solutions for this?
Maybe if each bullet is running its own code, that code could be written more efficiently? Thats how i solved the same issue. @kindred crest
For now it has translate function to move forward and collision detection...many people are recommending to use RPCs instead of photonnetwork.instantiate
What should I use?
Cause projectile is a big part in my game
Im new to netcode still so im not sure
I'm trying to use a NetworkList<NetworkObjectReference> like this:
public NetworkList<NetworkObjectReference> tiles;
public override void OnNetworkSpawn()
{
if(!IsOwner) return;
if(IsServer){
tiles = new NetworkList<NetworkObjectReference>(new NetworkObjectReference[40]);
and get an error:
Player_Controller.tiles cannot be null. All NetworkVariableBase instances must be initialized.
i've also tried to do this without new NetworkObjectReference[40]
Whats the proper way to structure code to accomodate latejoiners? The following code works when two players load the Dungeon scene together, but does not when there is a late joiner (as the late joiner never gets the ClientRPC)
public override void OnNetworkSpawn()
{
if (!IsServer) return;
GenerateDungeon();
}
public void GenerateDungeon()
{
levelGenerator.Seed = GenerateRandomSeed();
GenerateDungeonClientRPC(levelGenerator.Seed);
levelGenerator.GenerateLevel();
}
[ClientRpc]
public void GenerateDungeonClientRPC(int Seed)
{
if (IsServer) return;
levelGenerator.Seed = Seed;
levelGenerator.GenerateLevel();
}
Would one want to have an "isSynced" check in Start(), which calls some custom syncronization function to fetch data from the server? Is there a cleaner way of doing it through the already existing RPC's or a common format people use for these situations?
I would put the Seed in a Network Variable
Right that works for this but I mean in a more general sense
I can't just make everything a Network Variable when I want to sync data right? Or can I? ๐
Generally, network variables are for persistent state that you would want a late joining client to know about. RPCs are for one off events, like attacks or effects.
Gotcha, okay
whats the best way to network a bool? i want the bool to be what it is for the master client on all clients (with pun)
I have no clue of pun, but if this is a one time thing, like a coin toss to decide who starts a match for example, you can do it with rpcs
Otherwise you can look into NetworkVariables, that is if they exist in pun
Does anyone know how adaptive dejitter buffers work? Also I have a few questions regarding this
Write to it whenever data arrives and read from it at a fixed interval, measure your RTT, adjust the buffer length relative to RTT and your fixed time step
so at the point in time when the buffer shrinks, the player on the server (I'm implementing a buffer on the server) will have to drop some excess inputs that are in the buffer?
that depends on your game's needs, but most likely you don't want to drop any inputs, you want to consume them in some way.
so if the server consumes 2 frames worth of inputs that say "move left by 1" within the buffer shrinking frame then the player has to move at super speed right?
can i ask what you are using this buffer for? is it important that input is consumed at regular intervals? typically you'd just consume input whenever it arrives and have the "smoothing" happen by some interpolation algorithm right where the data use actually used.
I've used an input buffer for something like a fighting game in the past. Basically just kept a queue of the last 7ish frames of received inputs
I'm using it (going to) mostly for movement but maybe everything. In a pvp fast paced game
If you need to shrink the buffer dequeue 2 inputs and merge them. Merge meaning making sure that important inputs are not missed such as button presses for abilities. This will cause a misprediction on the client if you run client side prediction but there is no way around it
can you be more specific, why would you need the interval smoothing for a fast paced game? if you need an input buffer you are outside the realm of "fast paced"
Note that growing / shrinking the jitter buffers is very rare and not the common case and you want your algorithm that handles their size to act with quite a bit of momentum.
ohh so merge in a way that would be achievable through normal gameplay (no super speed)
if you just want to queue up inputs that is something else, that buffer would not need to be adaptive, or rather it always is, since its a queue, but its max size can be one-size fits all
Yes this is how most game servers work that are tick based. They run 1 gameplay simulation per tick and need 1 input for it.
If you start with stuff like moving some players multiple time per ticks that's just asking for people to cheat.
I'm thinking the buffer is to deal with small amounts of jitter. Would a queue just be a statically sized jitter buffer?
exactly the cheating problem was why I was wondering about this
what exactly is the problem you expect to have that arises from jitter?
that every frame of input a player sends will arrive just a little later than the frame was simulated on the server, preventing the player from moving at all
but I have a feeling I'm very wrong about something in this idea...
yes
you do not assume that the server tick and the client tick happen at the same exact real time
You're not, you need some way to deal with jitter and queuing inputs in a buffer and an algorithm for managing the buffer size based on ping / jitter
you always assume that the client sees an outdated state
yes but what about when the player doesn't send any inputs on a specific frame, the server has to keep simulating and sends out a game state where the player doesn't move. The server maybe drops the input that arrived late, but what if every input arrives late due to clock drift or an increase in ping
you'd make your game such that inputs are events and not values that need to be re-sent every tick
i.e. the server synthesizes a "pressed" state from "up" and "down" events received from the client
That's horrible for competitive games since you need to send inputs over reliable transfer which is way too slow in case of packet loss
wait so the server should simulate packets on the next tick without caring about whether they arrived late?
well, i have no experience with unreliable netcode, so maybe there is some magic you'll need, for your fast paced game, i'd just use a reliable transport like KCP and build on top of that, i.e. use events and skip the buffering, or rather have the transport deal with it
This seems to be getting into rollback which is a bit beyond anti jitter
but isn't jitter handling (beyond what a transport does and merging ticks) only ever relevant in games that also need some sort of rollback/prediction/reconcilation?
no it's not. Even games that don't have prediction (such as league of legends) can benefit a lot from jitter buffer. If you get into client side prediction it just becomes pretty much a must.
it's paramount for just having smooth rendering of remote object
would Netcode for GameObjects handle 80 to 100 players? survival/space/crafting type of game.
or better off going with something like mirror?
That would be more dependent on your Server Infrastructure than your networking stack. Its going to be tough no matter what you choose
Probably a fairly basic question, but how could I go about handling a ready-up system, where i need to check if a disconnected client was readied up (just a bool). Struggling with understanding how to access information from a client that has already disconnected
You would either have to save the bool off somewhere else or have some kind of side channel like a lobby service maintaining a connection
Thanks, making another class to store player data sounds like a good idea to look into ๐
I changed the model of my player prefab. With the new animator I put a NetworkAnimator component on (just as I had done for the old model). Now no animations are syncing and I'm getting the following error message as soon as a client connects:
InvalidCastException: Specified cast is not valid. Unity.Netcode.Components.NetworkAnimator.__rpc_handler_1069363937 (Unity.Netcode.NetworkBehaviour target, Unity.Netcode.FastBufferReader reader, Unity.Netcode.__RpcParams rpcParams) (at <c2e82697161d40e9820b973f81b832b4>:0) Unity.Netcode.RpcMessageHelpers.Handle (Unity.Netcode.NetworkContext& context, Unity.Netcode.RpcMetadata& metadata, Unity.Netcode.FastBufferReader& payload, Unity.Netcode.__RpcParams& rpcParams) (at Library/PackageCache/com.unity.netcode.gameobjects@1.1.0/Runtime/Messaging/Messages/RpcMessages.cs:77)
I have no idea why this is happening and the error goes away when I remove the NetworkAnimator component. Does anyone have any insight into what might be going wrong here?
why is the NetworkManager hiding these useful methods?
internal ulong TransportIdToClientId(ulong transportId)
{
return transportId == m_ServerTransportId ? ServerClientId : m_TransportIdToClientIdMap[transportId];
}
internal ulong ClientIdToTransportId(ulong clientId)
{
return clientId == ServerClientId ? m_ServerTransportId : m_ClientIdToTransportIdMap[clientId];
}
Can I use PlayerPrefs with Photon Pun 2?
Haven't seen PlayerPrefs integration in any networking solution so far, but the data types PlayerPrefs supports are common, so you certainly can send them over. Doesn't really make sense to automatically sync player preferences over the network, as this is generally meant for basic client settings.
PUN has custom properties, which should get the job done
What is the right way to initialize NetworkList<NetworkObjectReference>? I've tried some stuff but get the "All NetworkVariableBase instances must be initialized" error
Hello, Can someone tell me the difference between SDK matchmaking and API matchmaking?
Hello,
I have an issue with Netcode for Gameobjects.
When I try to start a server on the editor, I have no problem at all but in a standalone I get an error
at CommandLine.Awake () [0x0001e] in ...\CommandLine.cs:15
(Filename: ...CommandLine.cs Line: 15)
Here's the script :
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class CommandLine : MonoBehaviour
{
private void Awake()
{
string[] args = System.Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-server")
{
NetworkManager.Singleton.StartServer();
}
}
}
}
Can anyone help me? Please
Does NGO support WebGL at this time?
Are you referring to the Unity Game Services Matchmaking? You may be seeing the Web API which would be used for games outside of Unity.
The Singleton might be set in Awake(). Try doing that in Start()
Yes, but you would need to use Unity Transport 2.0
in netcode for game object, do RPCs always go through even if there is packet loss/drop? are they "resent" if they dont reach the other side or are we supposed to check for that manually?
Yea, RPCs and Network Variables are always sent reliably by default. You can change the delivery of RPCs however.
Thank you, I'll try this
It worked, thank you a lot
how can I destroy a network object?
Wow, steamworks actually does not give you any possibility to kick members from a lobby, abut allows you to listen to the memberkicked event? 
And....wow, they suggest to send a custom packet and leave the lobby on the kicked client then
The whole point of me wanting to kick somebody is if they did not get authenticated by the server, like when they mod the game or write their own "tool".
Hello, I'm working on a turned based game. From the server I would like to allow a specific clientId to do something on a keypress. To do that, in the update function that handle input, when a key is pressed I need to do something like "if (currentClientId == allowedClientId) { doSomething(); }. The problem is that I don't know how to get the "current client id". How to get the clientId of the client executing the current code ?
Is it NetworkManager.Singleton.LocalClientId ?
Guys in the method "OnNetworkDespawn()" how can i see the player who despawn?
is there a way to get the NetworkPlayer of the player who despawn?
hey guys how do i check that after running network.StartHost(); or StartClient(); that has succesfully connected to the server or the client
okay i figured out
its override void on network spawn
@radiant dome tell me how your on network despawn looks like
public override void OnNetworkDespawn(GameObject despawnedObject, NetworkDespawnEvent despawnEvent)
{
// Get a reference to the NetworkObject being despawned
NetworkObject networkObject = despawnedObject.GetComponent<NetworkObject>();
if (networkObject != null)
{
// Get the ID of the client that owns the NetworkObject
ulong ownerClientId = networkObject.OwnerClientId;
Debug.Log("Object despawned, owned by client ID: " + ownerClientId);
// Do something with the client ID, such as send a message to the server or other clients
}
}
i believe this should work, im no expert and i have a hard time doing unity but i think this should work
Hey I am working on game in which projectiles plays a big part and they travel at high speeds, so its difficult for to keep the bullets on server side since it will cause a huge lag, a solution I might have is create a dummy bullet which has no effect on anyone and is spawned in client side and main bullet on server side which will calculate the damage and stuff, Will this solution work out?
I have this error
it is like using these parameters i can not override the method
What could I use instead of broadcastsReceived, seems outdated in the new version of Mirror
Guys when the method "OnNetworkDespawn" is called is there a way to get the player info of the player who quit?
hey everyone, i am playing around with Netcode for GameObjects and want to deploy a dedicated server build to my Azure Windows VM. I can't seem to connect though. I added an inbound port rule for port 7777 but no success connecting. Does anyone have any resources on how to configure a Azure VM in order to allow connections?
I get these errors when I install the package for client network transform, i installed it using the git URL. is there a fix for this?
the errors also go away if i remove the package
Same I don't know how and I can't start my game
@wise fern dont dm me, just type in here.
You don't actually need the whole package. just copy the code here
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Multiplayer.Samples.Utilities.ClientAuthority
{
/// <summary>
/// Used for syncing a transform with client side changes. This includes host. Pure server as owner isn't supported by this. Please use NetworkTransform
/// for transforms that'll always be owned by the server.
/// </summary>
[DisallowMultipleComponent]
public class ClientNetworkTransform : NetworkTransform
{
/// <summary>
/// Used to determine who can write to this transform. Owner client only.
/// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
/// </summary>
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
}
I ended up doing that, i was just concerned about why the samples were full of errors. thanks still
Ok sorry
@shrewd junco It doesn't let me put the script on the player how did you fix it
You'll need to remove network Transform if there is already one there
I got it
why did they removed the NetworkDictionary? First Network Variable type i wanna use, just to figure out it got removed :/
Hello everyone. I'm working on my game (rts like settlers) and now is time when i'm considering to add networking to it. I'm thinking to to having multiple servers (with option to add new if needed) and allow player to join and start to selected server (limited to 100-400 players per server). It would be more like mmo not like multiplayers like Apex or CS, Fortnite etc. What I should looking for? Which tools, packages etc? I just need a point what could allow me to do this and I will be able to learn and use it myself ๐
It may be a bit out of date but you can try the community version
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDictionary
Guys us there a way to know when a player disconnect but no calling the method on all the players in the session?
cause i am using OnClientDisconnectedCallback,but if i disconnect i can not run the method,while the players who are still in the session can run the method
for example in a game of 2 players let's say there is a blu player and a red player,i am the blue player and when i disconnect i can not run the method OnClientDisconnectedCallback,while the red player can
Hi, I'm working on dynamic player colours with a net variable and it's struggling to update for late connectors
Player 1 (Host) will always be green
Player 2 is blue and can see the Player 1 fine and player vice versa
Player 3 is red. Players 1 and 2 can see player 3's colour fine, but it doesn't fetch the previous colours.
What could I potentially be missing?
Pastebin: https://pastebin.com/sAfchPk1
I've also attached a screenshot for a visual representation of what's happening.
Any help is greatly appreciated
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hello. I just migrated to 2021.3.24f1 and now I get the warning:
[Netcode] Runtime Network Prefabs was not empty at initialization time. Network Prefab registrations made before initialization will be replaced by NetworkPrefabsList.
I have create a NetworkPrefabsList but I still get this warning.
Sorry if I have my terminology wrong or anything, but is it possible to do Client-Side Prediction when using a NetworkTransform? It seems like when I have a NetworkTransform on the character it is completely nullifying any client-side location modification and keeping the character at the last recieved server location.
@heavy swan your character is server authoritative ?
No, I don't want the character to be server authoritative
My goal is to have the character move itself and then send its inputs to the server, which then moves the character on the server too
@heavy swan What does mean "Character move itself" ? from client user input ? or by IA ?
I'm not sure what those two things mean.
In short, my movement method is pretty much transform.position += inputVector.normalized
You'll have to write your own network transform if you want client prediction. But you can use Client Network Transform if you just need client authoritative movement
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform#clientnetworktransform
Gotcha, thanks! I think I have some solid ideas on how to make a network transform at this point, I just (up until earlier today) hadn't considered that the default unity one wouldn't have any support for client prediction.
It seems that everything is OK (network play seems to work) but I still get this warning. Any idea if it's a real problem or just a Unity bug ?
I'm pretty sure that warning can be ignored
@sharp axle I can ignore the warning, but when there are several warnings to ignore they can hide a real important warning. That is why I would like to remove this one if possible.
Can someone explain why the second Debug.Log logs Interaction instance while the first Debug.Log logs CreateTile instance? I'm completely lost at this one.
https://pastebin.com/Er0Vjked
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
could someone please point me in the right direction for making a brawl stars styled lobby screen, where I can make a private match/team and play with bots, or use a matchmaking play button to find a public match
Depends on which networking library you are using. I'm familiar with Unity Netcode but so much with Photon or Mirror
With NGO, what is the correct pattern to set the initial value of some NetworkVariable on the server in order to guarantee that a Client will read the latest value during OnNetworkSpawn? Is this even possible? It seems unintuitive based on the documentation.
the initial value and the latest value are two separate things, what exactly do you want to achieve? In any case the NetworkVariable is automatically initialized to the latest authoritative value on spawn (before OnNetworkSpawn is called) and subsequent updates are automatically pushed to the client.
I think you are looking for OnSynchronize
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior#networkbehaviour-pre-spawn-synchronization
I'm trying to set a value on the server before it ships out to the client.
for example an "id". Server spawns it and sets the id value immediately. Clients would be guaranteed the value state being correct when it is spawned on their side.
if you set that network var before calling Spawn() on the object it will be initialized to that value on the client when the client receives the OnNetworkSpawn callback
I avoided this since it generates warnings
NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. Are you modifying a NetworkVariable before the NetworkObject is spawned?
While the answer is "yes, I'm definitely doing that on purpose." to the warning, I'm not sure what issues this could create down the line.
nvm, what i said, you can't actually set a value on an unspawned network variable
A NetworkVariable's value can only be set when:
Initializing the property (either when it's declared or within the Awake method)
While the associated NetworkObject is spawned (upon being spawned or any time while it's still spawned).
so, if you want to init it, you need to do it in awake (which probably doesn't help you) or spawn it and immediately after set it, and have the client subscribe to the networkvariables onChanged event in Awake, it should then be guaranteed to receive that update event
But all of those solutions are bad practice
who says?
Race conditions
what race conditions?
we are talking about a newly spawned object, which should go through some init anyway, if you have an existing object with a netVar, it gets automatically synced on all late joining clients
Yes, but it's been designed to not have any way to accept any inputs before flying out the door.
idk what that means
You cannot initialize a NetworkVariable from another script and define the initial state unless you have the data inside the class and use it in Awake, based on the documentation.
That is terrible.
the docs specifically mention that OnChanged callback i described above as a way to handle your case
TIP
If you need to initialize other components or objects based on a NetworkVariable's initial synchronized state, then you might contemplate having a common method that is invoked on the client side within the NetworkVariable.OnValueChanged callback (if assigned) and NetworkBehaviour.OnNetworkSpawn method.
on the client side
It's saying that "because we deny you the ability to set the initial state externally, you have to make all clients wait to recieve an additional RPC call with actual valid data".
I can only assume that this is incorrect, since it's complete nonsense to have an architecture that does this.
i'm not sophisticated enough in netcode architecture to judge that
there might be reasons for why it is done this way, you can also implement your own network variables with different behaviour
Based on the docs it means that all initial data is guaranteed incorrect and you need a separate call to update the data unless the object already exists and is packaged to a hot-joining client (for example) with the current data.
could also be that its done this way because best practice is to only change a network variable through a callback and never poll it
Event based updates are fine, but there's no reason to not be able to guarantee the initial value before you send it off to clients.
maybe, you can take that up with the NGO designers, personally i don't have an issue with the way it is
If you don't need to initialize any network obejcts from the script creating them, and/or you don't mind wasting rpc calls every time you need to initialize networkvariables then sure, it would seem fine.
Im trying to make a brawl stars-styled matchmaking system for my game and I don't know where to start.
If you want to use Unity Game Services then you need the Matchmaker service and Game Server Hosting
https://docs.unity.com/matchmaker
https://docs.unity.com/game-server-hosting
is there a way to sort by distance to client when searching for lobbies?
Hi guys,i don't see a thread abput Vivox voice and this seem the more appropriate place where i can write,in the unity services platform i see that Vivox has been blocked and i don't know why,where can i find help to solve the problem?
You can open a support ticket from the Unity Dashboard
I think the best you can do is add the region to the lobby data then you could sort by region.
dang that sucks steam lobbies support it 
Unity lobbies are not tied to a connection. The relay is what's tied to a region. You can technically be in multiple lobbies like a chat room.
but can i get my ping to a relayed lobby to sort by it?
cuz i set up relays from my lobbies also, but if cannot search by distance its still kinda meaningless
You can ping the relay server, yea
yeah but i cant use this info to sort my lobbies, i can only do this after i get a set of lobbies no?
Yea. you have to get lobbies before you can sort them
and id have to query each lobby to get relay info to get the ping to it, doesnt seem very feasible in practice to use this
You have query options where you can only get lobbies with a certain region set
hmm, so when creating a lobby id set the region, then the searcher would search it with the "s1...s5"?
or u mean thers a building region variable? As i dont see that one
yea. each lobby can have 5 strings and 5 numbers that can be queried
i see. Last question, how does the player identify its region? Need to do that during the sign up phase or sth manually or theres a built in thing?
There is a QoS service you can query
https://services.docs.unity.com/qos/v1/index.html#section/Overview
i see, thanks this may be the way to go
hello, Is that the right chanel for questions about netcode?
Sure either here or over on the Unity Netcode server
https://discord.gg/unity-multiplayer-network
nice thx
can I use photon for matchmaking?
Sure. But you'll also need to use Unity Server Hosting.
I am trying to destroy a bullet object in my project but I am getting the error: destroy a spawned network object on a non host client is not valid. How can i fix this?
You need to destroy the bullet in a server rpc
How you call that server rpc depends on your structure, the easiest way would be to call it on the vullet itself with
[ServerRpc(RequireOwnership=false)]
void destroyServerRpc() {
GetComponent<NetworkObject>().despawn();
}
despawn could be written with a capitel D, I'm not sure
The requireownership = false is for when you want to call the function from a gameobject that doesn't own the bullet. Don't know how your netcoee structure is, so I just included it
thank you
In Netcode for GameObjects, the NetworkManager has a method that is defined as this:
Once a client has been disconnected, how do I access the reason parameter that was passed?
I figured out that it's NetworkManager.Singleton.DisconnectReason, but it's coming empty. Any idea why?
This is what I'm running:
NetworkManager.Singleton.DisconnectClient(clientId, "kicked");
And this is my callback listener:
private void OnClientDisconnect(ulong clientId)
{
if (!NetworkManager.Singleton.IsHost)
{
string reason = NetworkManager.Singleton.DisconnectReason;
Debug.Log(reason);
}
}
Hey everyone! i have an issue where when the bool variable is set to true on server the client starts moving a few milliseconds after the host how can i make it sure that all the players aka clients start at the same time along with the Host, same thing happens even if i set the timer variable as a networkvariable
Below is the code for setting timer that sets the bool variable to true
//GameModeManager Class Script
public bool startMatch = false;
void Update()
{
StartMatchServerRpc();
}
[ServerRpc(RequireOwnership = false)]
private void StartMatchServerRpc()
{
if (MultiplayerManager.Instance.totalPlayersConnected.Value == MultiplayerManager.Instance.maxPlayersAllowed)
{
if (MultiplayerManager.Instance.matchStartTimer.Value > 0f)
{
MultiplayerManager.Instance.matchStartTimer.Value -= Time.deltaTime;
Debug.Log("Match Starting In " + Mathf.RoundToInt(MultiplayerManager.Instance.matchStartTimer.Value) + " Seconds!");
}
else if (MultiplayerManager.Instance.matchStartTimer.Value <= 0f)
{
startMatch = true;
MultiplayerManager.Instance.matchStartTimer.Value = 0f;
}
}
}```
Below code is inside PlayerController
private void Update()
{
if (!IsOwner) return;
if (!IsSpawned) return;
if (!GameModeManager.Instance.startMatch) return;
PlayerMovementServerRpc();
}
[ServerRpc(RequireOwnership = false)]
private void PlayerMovementServerRpc()
{
Vector3 movementDir = new Vector3(0f, 0f, 1f);
transform.position += movementDir * runningSpeed * Time.deltaTime;
}
says in the docs that the property should be queried "after" that callback... could mean the property is not guaranteed to be populated until after that callback is complete
Im following a photon tutorial and i made these override voids OnPlayerLeftRoom() and OnLeftRoom() They do not work. Error: No suitable method found to override.
Are you implementing the proper interface?
i fixed it
but i have another problem
those two override functions are not being called
If there are no more errors, then maybe they're never occurring because their requirements weren't met - players leaving the room and whatnot.
if i have a server authorative inventory system how is the data stored on the server? do you keep an array of player data then find the player whos made the request and check the inventory?
Have a quick question. I've been beginning to convert my game into a multiplayer game using Unity Netcode. here is the method I use to spawn a bomb:
[ServerRpc]
void PlaceBombServerRpc(Vector3 gridSpace, ServerRpcParams serverRpcParams)
{
var placedBomb = Instantiate(bomb, gridSpace, Quaternion.identity);
placedBomb.layer = bombLayer;
placedBomb.name = serverRpcParams.Receive.SenderClientId + " Bomb " + bombNum;
placedBomb.GetComponent<BombBehaviour>().playerStats = playerStats;
placedBomb.GetComponent<NetworkObject>().Spawn(true);
bombNum++;
}
The bomb that is instantiated on the server and the bomb that is spawned for all of the clients are not the same. The layer isn't being assigned, the name isn't being assigned, and the playerStats variable is not being set, leaving it null. I must not be assigning these values properly with my current ServerRpc, what is the correct way to edit a spawned network object?
I'll usually just keep a list of structs that contains an inventory id and quantity. Maybe make it a networklist if it needs to sync to other players
i dont want it to be synced to other players i just want it to be synced to server
what im doing rn is im making a networkmanager script that encases all this type of stuff
and im going to make it a singleton with a dontdestroy on load
like dis
You need to either set the variables with a clientRPC or make those network variables that the server can set after it spawned
Hmm ok, that's what I thought. Do you know how I would go about syncing the class "PlayerStats" to all other clients? This class holds all information about the players power, speed, ammo, and powerups, so making each of those a network variable (there's like 50 integers that I don't wanna do) would kind of suck. Is there an easier way to sync a class to all Clients?
You can put those variables in a struct implementing INetworkSerializable and make it a Network Variable. But keep often changing values like ammo its separate thing. That will end up eating bandwidth
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/inetworkserializable
Ok, I was reading up on the network variable documentation and I saw that you couldnetwork serialize structs. I've never used structs before, what differs them from a class? Can they still inherit monobehaviour/networkbehaviour so that the can run awake and update? Or are they strictly for establishing data and writing methods that are manually called to change that data?
Actually you can only serialize structs for networking in NGO anyways. Structs are value types where as classes are reference types. But yea, mainly for storing data.
Structs and other INetworkSerializable.
Thanks for the advice. I think I'll keep my PlayerStats class and create a struct that is network serializable that takes info from PlayerStats so that I can pass it into the struct and serialize it on the network. There shouldn't be anything wrong with that, right?
I don't see anything wrong with that.
Hi, I am about to start creating a multiplayer game.
I wanted to use a cinemachine since it's a topdown game and a friend told me that I need a camera attached to a player and that it can't be a separate object.
I think that it could lead to issues w cinemachine because I want it to have some easing while following the player.
Is this true and if yes, why can't you just have the camera as a separate object that's not networked?
Attaching the camera to the player is an easy implementation of following the player, but Cinemachine already does it on its own. I would say attaching it to the player misses the point. Perhaps attaching a virtual camera would have some sense because toggling it would allow you to make some predefined closeups.
I don't think the camera should be synchronized over the network. In almost every game each player controls the camera individually and it has no effect on other players, so I just don't see a point in that. Synchronizing it could create some extra lags or jittering.
Check out the client driven sample here. It uses the 3rd person controller and cinemachine
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven
So if I am not wrong that's exactly what I was thinking.
Have a camera and a virtual camera as completely separate objects from the player and just don't network them at all, correct?
There should only be one main camera in the scene. You just have to make sure that the local player is the only one controlling it
I am aware of that, I am asking if the camera has to be attached to the player object because we've been arguing about that for the past 20 minutes, I don't see the point of it and think that it could lead to issues and he says that it has to be attached and that somebody in this server told him so.
If the camera is attached to the player then it gets duplicated when a new player spawns in. It's possible but you then have to disable the camera on the remote players.
yes, but why do that in the first place is what I am asking, why not just have a camera as a separate object in the same scene and never network it?
The sample I posted has the local player assign itself to the camera's follow script
So, have a cnimeachine vcam in the scene, instantiate a player and assign it to the said vcam's body client side.
Correct?
Yea, that how I do it
Thanks for clearing that up
Different games have different requirements. There is no wrong way of doing things
Attaching the camera to the player is simple, so it's quite easy task for beginners. Perhaps that's what someone had in mind when suggesting that solution. Hover it misses the point in multiplayer games, especially when you're using cinemachine.
Using Photon Pun 2, and even though both gameobjects have Transform View Classic, the localScale of the canvas isn't synchronized between clients?
So networking and rigidbodys don't really go hand in hand right? So would I just implement my own gravity?
Depends on what you are using. Unity Netcode has a Network Rigidbody component you can use.
I tried it but wasn't really working as intended
it had some delay when using it
if you werent the host
You would use Client Network Transform in that case. It makes it client authoritative.
You might still ultimately end up handling your own physics though. Depends on your usecase.
As someone who has the camera attached to the player and uses cinemachine:
The answer is simple, ease of use
It's just way simpler to disable the cam by default and enabling it on the local player
You might have better luck over on the Photon Discord. Check the pinned message here for the link
Is it possible to send a client RPC to one client with Unity NGO?
This doesn't seem to work
[ServerRpc(RequireOwnership = false)]
public void PlayerReadyServerRPC(ulong clientId)
{
Debug.Log($"[D] Client Ready Request");
ClientRpcParams clientRpcParams = new ClientRpcParams
{
Send = new ClientRpcSendParams
{
TargetClientIds = new ulong[] { clientId }
}
};
PlayerReadyClientRPC(levelGenerator.Seed, clientRpcParams);
}
[ClientRpc]
public void PlayerReadyClientRPC(int Seed, ClientRpcParams clientRpcParams = default)
{
Debug.Log($"[D] Initialize Client");
levelGenerator.Seed = Seed;
CreateDungeon();
}```
"Initialize Client" logs on all clients when I call "PlayerReadyServerRPC" from one client
Nvm, I've just realized I'm calling the server rpc from each client, so obviously it'll log back once on each one ๐
How does that work exactly? Are the rpc params always sent when you call an rpc, and this just overrides the default ones?
Also, I know this structure is totally redundant for this one specific task, but I plan on having it do more than share the level generator's seed, and the RPC's are a way to wait until certain syncronization states are met
That's right the default RPC params are always sent if not specified
Thank you two
can any one give me some refrence iwant to make model under 2000 polycount
Hi guys,i tryed to run the multiplayer of the game and i am having problems,there are 2 players and 1 disk,everytime a player hit the disk the ownership of the disk change.When i am the owner of the disk the gameplay is perfect and there is 0 lag,but than when the other player hit the disk the movement of the disk is "lagging" and the gameplay is not good to play,here there is a video of the gameplay https://www.youtube.com/watch?v=b573GjR9xqo
Do you think it is a client-prediction problem?
cause the movement of the objects when i am the owner is perfect and there is not input lag
Got a question, If a client instantiates a projectile, will it be able to interact with a server spawned object (like an enemy)
Or does it have to spawn on the server also to interact
On the client it will only be local. The server and the other clients will have no idea that it happened
Sounds like it, had a similar problem with weapons on my character I solved it by having a local instance of the weapon anywhere, which follows the movement of the animation and handle the logic where it needs to be handled (in my case the player which owns the weapon and the server)
Maybe you can do something similar with the disc to solve the problem
I haven't written any prediction code tho, so can't help with that
I don't thing it is a client-prediction problem,now i removed some code and there is no more the changing of ownership everytime a player hit the disk. All works perfectly when i am the host but when i am the client the disk is constantly lagging,it is like the position of the disk is not syncronized when I am the client
the solution to a "physics" game like this is full world prediction on both players
or if one is the host, only the client needs to do full world prediction
if i understood the problem is that the client transform position of the disk doesn't manage to syncronize well the position of the disk to the client
as i said in the other discord, u need csp for physics
to get this to be smooth
on all ends
But why I need CSP,I donโt understand
in netcode for gameobjects, whats the right way to disconnect a client that is denied connection in my ConnectionApprovalCallback? i have tried setting response.approval to false and running NetworkManager.DisconnectClient(). but still after a while NetworkManager tries todisconnectclient manually in ApprovalTimeOut() and gets a null reference when tryign to get the clientId.
internal ulong ClientIdToTransportId(ulong clientId)
{
return clientId == ServerClientId ? m_ServerTransportId : m_ClientIdToTransportIdMap[clientId];
}
This is what I'm getting a "KeyNotFoundException: The given key '1' was not present in the dictionary." error on
it seems like setting response.Approved = false in my connection call back disconnects the client before it even gets connected and it causes the issues.
So my work around for now is to set response.Approved = true and start a coroutine that waits for it to get connected and disconnects it. Not elegant but working, for some reason I feel like i went through all the relevant documentation and tried everything as it should be implemented without success.
if i subscribe to Instance.networkManager.OnClientDisconnectCallback and try to display the Instance.networkManager.DisconnectReason in there, it wont even grab the string assigned in "response.Reason" in my approvalconnectioncallback
You can just set response.Reason if you need to send one
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval#sending-an-approval-declined-reason-networkmanagerconnectionapprovalresponsereason
for sure,although its not working with the callback.
i found a bug report describing my situation:
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/2534
seems like their connection approval is broken when not approving a connection.
does anyone have an explanation as to why clientIDs in NGO are ulongs
idk about you but im personally not expecting 18,446,744,073,709,551,615 players to be in a lobby in my game
how would I have code be called on all clients. im trying to make every client run a function on their own and I need to do this from the network manager. How would I go about this
my current Method is this:
for (int i = GamePlayers.Count - 1; i >= 0; i--) //Run on each client
{
NetworkConnectionToClient conn = GamePlayers[i].connectionToClient;
conn.identity.gameObject.GetComponent<NetworkGamePlayerLobby>().NetworkSetupClient();
Debug.Log("Ran for Client : " + GamePlayers[i].gameObject.name);
}
but this does not run on any clients that are not hosting
this is using Mirror
Not using mirror, but it should be similar there. Look into clientrpcs
How it works, you have code which executes on the server and every client needs to do something, so you call the clientrpc function, the server then sends a signal to all clients to execute the function you called. The important step is, it needs to be called from the server
In NGO it would look like this
void someServerFunction(){
myFunctionClientRpc();
}
[ClientRpc]
void myFunctionClientRpc() {
}
Hello. In my project I have it so a player can shoot a bullet and the bullet will despawn after reaching a certain range. However for the clients, the bullets disappear slightly earlier than for the host. Does anyone know why this is happening?
To clarify, the bullets disappear at the same time but on the client they move slower so they wont have traveled to the max range before disappearing
I get this error when I attach a network object to a prefab and instantiate that prefab. Does anyone know a fix?
how do they get destroyed? via RPC from the server or without signal for the server? And how do they update their position?
Hey so I want to make offline mode for my game and I have a button that loads the scene. But sense my scripts check if photonView.IsMine to function it doesnโt activate the scripts. How can I fix this
Destroyed via GetComponent<NetworkObject>().Despawn();
and their position is updated by changing their transform
transform.position += direction.Value * speed.Value * Time.deltaTime;
@austere yacht
i mean is it updated by the server?
the bullets have network transforms
from your description it seems that the position might get updated/written by the client and the server
whats the problem tho
The problem is latency. The host will always be ahead of the clients. The host despawning the bullet on its time. The best route in that case is to just disable the renderer.
Honestly bullets should probably be using a object pool in any case.
Multiplayer Play Mode 0.1.1 - Unity Trasport 1.3.4 - Multiplayer Tools 1.1.0 - Netcode for GameObjects 1.4.0
Any ideas why I am getting these errors when opening player instances using MPM?
would anyone like to take some time out of their day to help me with creating a matchmaking system similar to brawl stars via DM? please let me know
I have a problem, i need to network a GameObject because i need to access a camera and another gameobject in one of its components. I have this gameobject synced as a syncvar and it always returns null all other client sides. this gameobject has a network identity but i still dont know.
I use Mirror btw
any suggestions on how to do this is appreciated
Hey
I hope I'm in the right place I'm currently pretty desperate I think I have a good idea for a mobile multiplayer game but I'm just overwhelmed with what networking solution to choose. For the context my game should be a one vs one and action based.
I am a solo developer and would not like to pay a lot of money before releasing the game but for the nature of my game it is very important to have a good ping and a low response time .
So I've read quite a bit but I'm totally unsure which choice to make I was specifically looking at photon quantum and netcode for entities as I've read that for the type of game I'm planning they would be the best options but with photon you have to pay $250 just to try quantum.
Could I use unity netcode for entities also for example with playfab or similar?
I would really appreciate any help thanks in advance.
if you can implement the necessary systems for a competitive game yourself (actually just the needs of your particular one) you can use any framework that has an authoritative server model (its just 2 players and probably not too much going on that would necessitate an ECS solution like quantum or dealing with Entities), you probably get the most readymade "free" solution for competitive games with photon fusion so long as you stay in its free tier which should allow you to launch your game at a small scale. With NGO you'd have to do more yourself and dive a bit into the lower level API but its also less opinionated and may suit your game better. If you want to pay a bit of money you may look into stuff like FishNet which has certain competitive features in its pro version. Your primary concern as solo developer should be on minimizing effort, so using readymade backend services for matchmaking/lobby/chat/persistence (Playfab/Photon/Unity) might be critical, the free tiers on those are quite limited.
Thanks for taking the time to answer I will look into fusion a bit more ๐
Hey the RPC function in my game is only getting called only on one player even tho it should be called for all and have more than 1 players...using PUN RPC_target.all
Any idea why this might be happening?
Is there a very simple example of a Photon RPC that might just tally votes or send a number over? The general structure of the most basic first RPC? Any good example projects recommended? Basically simplest template for the important functions in a multiplayer game?
I have the dedicated server working, and the movement working; so players can sync and move across network, but the players can't really do RPC or much else. I wanted to create a simple "Vote" for a Race Track, and a simple way of determine "First Place, Second Place" etc in simple Racing Game.
Probably will also have to deal with a basic "Red Shell" like in Mario Kart, like a button that spawns one and zero in.
does anyone know how I can implement a team system into my Photon Pun Search and Destroy game? I am looking to make 2 teams of 3 = 6 players.
Examples should cover teams https://doc-api.photonengine.com/en/pun/v2/class_photon_1_1_pun_1_1_utility_scripts_1_1_pun_teams.html.
You might want to roll your own gameobject based team tagging system if you are planning to have team specific AIs/objects since there is no easy path for simulating actual Photon Players afaik.
Anyone here to help me with multiplayer callbacks.. I have a CS0246 error.. Can't see what Reference I'm missing
This is the line with the error
LobbyEventCallbacks m_LobbyEventCallbacks = new LobbyEventCallbacks();
const int
Well, what library is that api from?
Not sure what's your question. Sorry can you explain?
What networking library are you using? Or where is that class(LobbyEvenCallbacks) from?
If you're doing networking you should be able to answer that at least.
I'm still learning lol. I guess I need to create a (LobbyEventCallbacks) for this? I was thinking this LobbyEventCallbacks was in the unity library package already
Ok, simpler question: where did you even got the idea to use that class?
And if you're still learning, you should start with single player projects.
I outsource the lobby funtion. And it was working. But now the script are missing. I did Retrieve almost the full project. But now I have that error and I'm trying to figure out way
Still trying to figure out if this came with unity package or did he created the script. Lol
Ask the person that wrote the code. Or read through all the relevant code and try to guess.
LobbyEventCallbacks Have you stuck this into Google?
There's two forum posts with instructions, did you try them?
Yes I did. ๐
I'd assume you're missing a package in your project, but I'm not gonna go about assuming what package that is...
I think it's your responsibility to know about what is used and why in your project. Even more so if you outsource it.
I'm assuming this is using the Unity Lobby Service. Lobby events are still in beta and need scripting defines set in the editor
https://github.com/Unity-Technologies/com.unity.services.samples.game-lobby#ugs-events-beta-note
I know PUN only:
Example: OnTriggerEnter sound is being played for everyone:
private void OnTriggerEnter(Collider other) {
Sound.Play();
PhotonV.RPC(โPlaySoundโ, RpcTarget.All)
}
[PunRPC]
void PlaySound(){
Sound.Play()
}
Sound = Audio Source
PhotonV = Photon View
How I can check if entered relay id exists when client is connecting to relay
Hi guys, question, which networking method should I use to make a game like Tales of Pirates, Ragnarok Online, Nin Online, byond type games?
Seems like you mentioned only mmorpgs. The networking part of mmorpgs is really complex. I only know of/have worked with SpatialOS to handle that many players. But I can't find any recent infos about spatialOS, so don't know if it still exists
Im calculating around a 100 player max for a server
So I have searched a bit and it seems like spatialos is pretty much non existing at this point. So I can't give you tipps
I have heard mirror can support so many concurent players, but I have not worked with it.
Mirror does seem to lack loadbalencing tho