#archived-networking

1 messages ยท Page 12 of 1

rocky bramble
#

isnt zeromq based on amqp?

austere yacht
#

ZeroMQ is its own thing

#

its a library/framework for implementing protocols

rocky bramble
#

oh, awesome

#

i though its another message broker

#

like rabbitmq

austere yacht
#

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

rocky bramble
#

ubt why not implement it with native sockets( libc sockets or wisock2)?

austere yacht
#

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

austere yacht
rocky bramble
#

oh got it

austere yacht
#

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)

rocky bramble
#

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)

austere yacht
#

oh, then definitely read the KCP implementation

austere yacht
#

its very difficult to get on the engine team in any game company

rocky bramble
#

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 ;/

austere yacht
#

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".

rocky bramble
#

to be honest you completely ruined my motivation xd

austere yacht
#

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...

rocky bramble
#

I mean, i dont want to stick with mainstream network framewroks and just write actual logic for the game

rocky bramble
austere yacht
rocky bramble
#

lol

#

they couldn't scale because of the architecture?

austere yacht
rocky bramble
#

or there were some odd bugs coz netcode

austere yacht
rocky bramble
#

xddd

#

make everythign synchronous and blocking this is the wae

austere yacht
#

the primary misunderstanding is that node and http are supposedly fast

rocky bramble
#

i mean http 2.0 is quite fast compared to 1.1

austere yacht
#

but web-dev fast and game dev fast are orders of magnitude different

austere yacht
#

game netcode data has completely different properties compared to web data

rocky bramble
#

yeah i know

austere yacht
#

for one thing its not predicatble at all

#

you cant cache it

#

it needs extremely low latency

#

and its realtime

rocky bramble
#

correct me if im wrong, maybe data is not cached but instructions are

austere yacht
#

?

#

wdym?

rocky bramble
#

nvm, i misread

#

I though you were sayin "nothing can be cached"

austere yacht
#

well, you can cache it but you will only have misses, so its pointless

#

its conceptually impossible to cache a game server's response

rocky bramble
#

what if its hearbeat tick?

austere yacht
#

well you can cache internally

#

but thats different from having a cache server to serve precomputed results without tickling the source

rocky bramble
#

yeah, all data will differ

austere yacht
#

the heartbeat still needs to be answered by the actual server

rocky bramble
#

i mean you can calculate some stuff to "predict"

austere yacht
#

thats something else

#

predictive loading/responses are a thing in web app development too, but very advanced and not your average joe's repertoire

rocky bramble
#

But you have to fit within the server's tick timeframe anyway depending on tickrate of server

austere yacht
#

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 ๐Ÿ˜ฎ

rocky bramble
austere yacht
#

not impossible, just a long road

rocky bramble
#

Servers like this are developed by whole teams, not a single guy during his time off

austere yacht
rocky bramble
#

can also fly into space xd

austere yacht
#

but realistically, yes, its not possible

#

imo, its not even possible to make a real game solo

rocky bramble
#

you mean AAA calibre game?

austere yacht
#

real = game could potentially be a commercial success

austere yacht
#

you can have absurd luck and it might happen because of that, but you cannot "plan" to do it

nocturne vapor
austere yacht
#

there are exceptions like luke pope, who truly does everything himself

rocky bramble
#

The guy who did "return of obra dinn". That was a great title

austere yacht
#

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

rocky bramble
#

@austere yacht Well that sound like its better to stay in webdev or other "safe haven ' and do games as hobby ๐Ÿ˜„

austere yacht
#

if you have a great personality and can work the yt as a creator, you can definitely make it

nocturne vapor
#

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

rocky bramble
#

i though networking would be paid a little more better than other areas, due to lower interest regards it

austere yacht
#

but also, stuff that requires expensive, hard to find, experts (in CS) is eventually replaced by a library or framework by management

rocky bramble
#

which means that in this case only the best will be left which will provide better and better solutions?

austere yacht
#

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

austere yacht
#

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

austere yacht
rocky bramble
#

hehe

#

There is always embedded. But to be honest everything is better than webedev

austere yacht
#

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!

austere yacht
rocky bramble
#

after that, everything becomes easier

#

Every day you smile in the mirror and write the same crud application like yesterday and yesterday and...

nocturne vapor
#

That doesn't sound too bad actually

stray kettle
#

Does anyone know how to send int[] through network variables with netcode for gameobjects?

steel cosmos
#

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

sharp axle
terse idol
#

which one out of pun2, fusion and bolt is better for FPS with lag compensation?

pallid mulch
versed lily
#

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?

nocturne vapor
#

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

versed lily
#

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?

nocturne vapor
#

Uhm idk, try it out

#

But your list wouldn't get synced you have to handle that as well

versed lily
#

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....

nocturne vapor
#

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

versed lily
#

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?

nocturne vapor
#

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

sharp axle
versed lily
atomic crest
#

I need some help cuz the photon voice view doesnt look like in the tutorial what im watching

pearl oasis
#

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?

pearl oasis
#

Even if I add the Network RigidBody, players aren't synced

sharp axle
pearl oasis
#

and both network transform and client network transform ask for a network rigidbody

sharp axle
#

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

pearl oasis
#

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:

sharp axle
pearl oasis
sharp axle
pearl oasis
pearl oasis
#

but even then, I don't see the host moving on the client build

sharp axle
cunning sphinx
#

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?

sharp axle
#

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.

cunning sphinx
#

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?

deft spear
#

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

craggy garden
#

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.

sharp axle
craggy garden
#

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.

sharp axle
craggy garden
#

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.

sharp axle
craggy garden
#

Seems like 1.3 is not on PackageManager yet

sharp axle
empty night
hollow glen
#

Whats the best way to sync an editable object between players? It has a bunch of children that can be edited(transforms). Json?

sharp axle
hollow glen
#

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.

sharp axle
summer shell
#

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

spring crane
wispy locust
#
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?

novel knot
#

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

summer shell
cunning sphinx
#

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

sharp axle
cunning sphinx
#

i thought the point of using relays was there shouldnt be any issues with ports or firewalls?

sharp axle
cunning sphinx
#

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?

sharp axle
cunning sphinx
#

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

rugged obsidian
#

Guys Help Please Idk how to explain i am using this tutorial and this is my code and in game nothing happens!!! HELP

#

With photon

wraith olive
rugged obsidian
#

Yes and no

graceful zephyr
#

which cuts to the core and does exactly the same as the YT video you linked, w/o overcomplicating

sharp axle
graceful zephyr
#

it's as cut down as possible to illustrate the exact functionality

rugged obsidian
mint sundial
#

in unity mirror how can i do random variable but same on the clients

sharp axle
mint sundial
#

i wrote this code

#

do you think is it okey?

#

and this is checking on the player clienta

sharp axle
nocturne vapor
# mint sundial i wrote this code

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

limber holly
#

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 ๐Ÿ™‚

limber holly
#

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

lethal cargo
#

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

sharp axle
cunning sphinx
#

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

hazy galleon
hazy galleon
sharp axle
cunning sphinx
calm granite
#

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 :)

sharp axle
lavish garden
#

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??

sharp axle
lavish garden
#

What if I already have those objects spawned at one client? They also have a lot of stuff, like renderer, scripts, ect.

sharp axle
sand talon
#

Hear me out!!!

#

selectedType is an enum

#

and i can`t network enums if i remember correctly... so how about this?

cunning sphinx
#
    [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

sharp axle
sharp axle
cunning sphinx
#

it is

sharp axle
# cunning sphinx it is

oh, if moneyResource is set to Owner write permissions then the Server is not going to be able to write to it.

cunning sphinx
#

yeah that was the issue. i wrongly assumed server could still write if it was set to owner. thanks!

sharp axle
calm granite
#

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

sharp axle
cunning sphinx
#

public void Rpc3PersonModel

i think the name needs to end with ClientRpc, just to mention one thing

sharp axle
cunning sphinx
#

oh TIL

sharp axle
#

I could be wrong though

calm granite
#

the prefabs change per client and the changes are unknown to the server / myself

#

they include cosmetics, etc

sharp axle
#

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)

calm granite
#

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

sharp axle
calm granite
#

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?

calm granite
#

i just did it

#

so

sharp axle
calm granite
#

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

calm granite
empty magnet
#

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)

mint sundial
#

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?

little abyss
#

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

cunning sphinx
#

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?

cunning sphinx
#

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

little abyss
#

tysm

weak plinth
#

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

dim pike
#

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?

nocturne vapor
pallid quarry
#

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! ๐Ÿ™‚

pallid quarry
#

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?

calm frost
#

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?

sharp axle
calm frost
calm frost
#

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

calm frost
#

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

mint sundial
#

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?

austere yacht
mint sundial
#

can you give example please

#

i am searching for 1 weeks about this mechanic

sharp axle
mint sundial
sharp axle
mint sundial
#

i mean what is function to save it

#

anyone give example or any tutorial link please

pallid quarry
#

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 ๐Ÿ™‚

nocturne vapor
# mint sundial i tried clientRpc and SyncVar but doesnt working

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

calm frost
#

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

radiant dome
#

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?

austere yacht
radiant dome
#

cause i used photon and i did not like it

austere yacht
#

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

radiant dome
#

For VR i am using the Interaction Toolkit,i want to pass to Netcode cause it is done by unity

atomic crest
#

I get an error that my script isnt a component

atomic crest
#

I use Photon.Pun and if I change MonoBehaviour to MonoBehaviourPun, would it change something?

sharp parcel
#

[Netcode for Gameobjects] If somebody was to spawn a player mid game, would you use SpawnWithOwnership or SpawnAsPlayerObject?

sharp axle
sharp parcel
#

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

little sorrel
#

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

sharp axle
sharp parcel
sharp axle
sharp parcel
#

I keep a list of prefabs on a player

silent flame
#

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?

calm frost
#

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

sharp axle
radiant dome
#

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

sharp axle
radiant dome
#

this one to be clear

sharp axle
radiant dome
#

Ah ok so i was using the Lan?

wet spindle
#

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?

sharp axle
wet spindle
little sorrel
#

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

raven bear
#

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

sharp axle
alpine pulsar
#

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?

sharp axle
alpine pulsar
#

Thanks

alpine pulsar
sharp axle
#

UTP is very low level. Basically dealing with socket connections directly. Plus RPCs are already part of NGO so you are already using it.

alpine pulsar
#

right gotcha, thanks!

radiant dome
#

hi guys i am using netcode and i don't find the component "client network transform",has been modifyed?

sharp axle
# radiant dome hi guys i am using netcode and i don't find the component "client network transf...
radiant dome
#

solved thanks

alpine pulsar
#

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?

alpine pulsar
crystal marlin
#

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?

sharp axle
crystal marlin
sharp axle
crystal marlin
hollow wave
#

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 ?

cunning sphinx
#

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?

kindred ice
#

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"?

cunning sphinx
#

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

sharp axle
#

You have to make your own. I usually just have the player object save itself to a list in OnNetworkSpawn

vocal bane
#

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.

stiff ridge
stiff ridge
# hollow wave I was wondering like how the games work which are just 1v1 games like clash roya...

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.

raven pond
#

Is the network manager part of paid unity? If it isn't, how do I access it?

alpine pulsar
#

can the length of join codes be altered?

raven pond
#

Please help.

alpine pulsar
#

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

raven pond
#

What's NGO?

alpine pulsar
#

Network for GameObjects

#

Have you got any net code working at the moment or are you starting for the first time?

hollow wave
#

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

woeful cradle
#

whevener i try connect to photon (pun) i get this error.

crystal marlin
#

should a host instance type invoke OnClientConnectedCallback ?

#

because for me it doesn't

sharp axle
sharp axle
sharp axle
crystal marlin
sharp axle
stiff ridge
stiff ridge
raven bear
#

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?

raven pond
#

@alpine pulsar Thanks, that helps a lot.

hollow wave
#

Btw thanks for the cloud code thing, it feels like the thing I need

sharp axle
# hollow wave Sorry I don't get wdym by overkill

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.

hollow wave
#

Ok,I get it what you say

tawny sluice
#

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

crystal marlin
raven pond
#

How do I get a player to spawn at Y 1 using the Network Manager?

raven pond
#

Like without using spawn points? If there isn't, how do I get access to the Network Manager spawn point thing?

graceful zephyr
hard creek
#

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.

silent flame
graceful zephyr
silent flame
twilit ingot
#

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

raven bear
#

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

tawny sluice
#

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

crimson flint
#

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

crystal marlin
graceful zephyr
#

or if u want server auth

#

then u need CSP

#

client side preidction

crystal marlin
#

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?

wise fern
#

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

tawny sluice
#

wait should i use PUN 2 or fusion?

#

what's the difference

tawny sluice
#

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

silent flame
#

and on client side you need to use CSP as fholm mentioned

raven pond
#

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;
            }
        }
    }
}```
raven pond
#

@stiff charm?

raven pond
#

Anybody?

#

I'm getting this warning if it's helpful:

NullReferenceException: Object reference not set to an instance of an object

sharp axle
raven pond
#

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.

raven pond
#

It's been sixty years since I posted a question similar to yours. I still haven't got a reply.

crystal marlin
#

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.

graceful zephyr
radiant dome
#

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?

crystal marlin
graceful zephyr
#

Probably some quirk relating to KCC/NGO/PhysX interactions

#

Hard to say

crystal marlin
graceful zephyr
#

Yes but the movement on the clients will be delayed

crystal marlin
crystal marlin
#

actually, the second option would have terrible input lag and a horrible experience, no?

graceful zephyr
#

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

ornate scarab
#

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; 
    }
}```
wise goblet
#

Which solution i should use for client-dedicated server model when i want place my server on my own linux machine?

twilit ingot
subtle depot
#

how can i change the scene with netcode

#

and remain connected

sharp axle
sharp axle
graceful zephyr
crystal marlin
#

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.

Get the Kinematic Character Controller package from Philippe St-Amand and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

subtle depot
vagrant garden
raven pond
#

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?

spiral lark
#

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");
        }
    }
raven pond
#

Do people just ignore networking until they have a problem or something?

spiral lark
#

they might be able to helpo you too

raven pond
#

Thanks.

weak plinth
#

hello everyone
I have a simple problem with PUN 2

#

that's my error and I've tried everything to fix it

spiral lark
#

show some code

weak plinth
#

the code is like 665 lines though

spiral lark
#

show the code block thats causing the error

weak plinth
spiral lark
#

what kind of object is Extensions

weak plinth
#

I am not sure, I imported PUN 2 and then I got that error

spiral lark
#

try replacing tostringfull with ToString(properties)

weak plinth
subtle depot
#

how can i make text update across all screens in netcode

#

do i just attach a network obj component

spiral lark
spiral lark
weak plinth
spiral lark
#

is the error causing your game not to be able to run?

subtle depot
#

thought thats how youd do it ho

spiral lark
#

are they hosts and clients?

spiral lark
#

hmmm

#

i would ask in the pun discord

weak plinth
#

PUN discord server is not active nor is responding to anyone
hence me coming to the unity server

subtle depot
#

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!";

}```
spiral lark
#

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

#
subtle depot
#

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

spiral lark
#

โค 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...

โ–ถ Play video
#

heres for relay

subtle depot
#

i saw that one too ill just figure it out haha

#

he doesnt go much into ui

#

unless youre using the lobby plugin

spiral lark
#

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

subtle depot
#

if someone familiar with netcode wanna just vc for 5 misn

ornate scarab
#

does anyone know how to use photon?

raven pond
#

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.

nocturne vapor
#

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

raven pond
#

Ok, sounds good.

#

Thanks.

nocturne vapor
#

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

raven pond
#

Ok.

wanton oxide
#

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

wanton oxide
#

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)

weak plinth
#

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"

graceful zephyr
#

Usually

weak plinth
sharp axle
vagrant garden
sharp axle
brisk bluff
weak plinth
#

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

sharp axle
wanton oxide
#

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 PES_Hands

Think i'm gonna switch to Mirror and FizzyFacepunch

gray peak
#

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!
radiant dome
#

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

sharp axle
gray peak
sharp axle
gray peak
#

So, the weapon is a scriptable object, I instantiate the bullet and get the bullet script and set the values

jaunty owl
#

I hate this channel just throw it in the trash (pssโ€ฆ did u know i hate networking ๐Ÿ™‚

upper osprey
#

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 ?

spiral lark
#

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

brisk bluff
#

So netcode has built in listen server support and stuff?

sharp axle
brisk bluff
brisk bluff
#

Is it free?

sharp axle
sharp axle
brisk bluff
#

Isn't epics free if it's on their marketplace or som

sharp axle
nocturne vapor
#

Steams is free as well, if it is on their market place, which will cost you 100$

amber fractal
#

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.

graceful zephyr
sharp axle
amber fractal
#

does it have any obvious drawbacks for the simplicity it provides?

nocturne vapor
#

It does lack some features like prediction and stuff like that

amber fractal
#

hm, and when hosting as a server, will you have to run the server through the game?

nocturne vapor
#

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

raven pond
#

I take it that the NetworkStartPosition doesn't exist anymore?

wraith flax
#

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.

sharp axle
# raven pond I take it that the NetworkStartPosition doesn't exist anymore?

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.

sharp axle
wraith flax
#

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

sharp axle
wraith flax
sharp axle
wraith flax
raven pond
#

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?

sharp axle
raven pond
#

Ah, if I'd changed FOUR WORDS in my script I would have had that. I wondered why it wasn't looking normal. Thanks.

wanton oxide
#

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?

weak plinth
#

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

wanton oxide
#

you figured that out meanwhile? Also need to know ๐Ÿ˜„

radiant dome
#

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

vocal yoke
#

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

alpine pulsar
#

how would i go about changing the colour of connected players as they join (i.e. p1 is green, p2 is red, etc.)?

sharp axle
sharp axle
plucky snow
#

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

fervent pebble
#

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?

sharp axle
sharp axle
plucky snow
#

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

sharp axle
#

If it's been spawned then you can just send a NetworkObjectReference

plucky snow
sharp axle
#

in your RPC

plucky snow
#

i'm just not sure how a NetworkObjectReference works and didn't find any examples of its use

plucky snow
wraith flax
#

Is there a way to LoadSceneAsync through Unity's NGO Scene Manager?

sharp axle
plucky snow
sharp axle
plucky snow
#

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๐Ÿ˜‚

sharp axle
wraith flax
#

No way to do something like this though?

asyncOperation = SceneManager.LoadSceneAsync(nextScene.ToString(), loadSceneMode);```
plucky snow
wraith flax
#

for loading screens

sharp axle
plucky snow
#

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;
}

sharp axle
plucky snow
#

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

sharp axle
plucky snow
sharp axle
plucky snow
#

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.

sharp axle
plucky snow
#

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

sharp axle
plucky snow
summer shell
#

yo guys i just realized making a multiplayer game is prettyyyy hard

#

basically 0 tutorials on how to do it properly

sharp axle
faint cedar
#

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

plucky snow
# faint cedar Hello. I am trying to instantiate bullet objects for my players but only the hos...

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
------------------------------------------------------------------------------------------------...

โ–ถ Play video
#

he's doing exactly what you have problem with- spawns objects from different instances

sharp axle
kindred crest
#

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?

faint cedar
#

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

kindred crest
#

What should I use?

#

Cause projectile is a big part in my game

faint cedar
#

Im new to netcode still so im not sure

plucky snow
#

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]

wraith flax
#

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?

sharp axle
wraith flax
#

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? ๐Ÿ˜…

sharp axle
wraith flax
#

Gotcha, okay

woeful cradle
#

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)

nocturne vapor
#

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

tribal silo
#

Does anyone know how adaptive dejitter buffers work? Also I have a few questions regarding this

austere yacht
tribal silo
austere yacht
tribal silo
austere yacht
sharp axle
#

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

tribal silo
vagrant garden
#

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

austere yacht
vagrant garden
#

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.

tribal silo
austere yacht
#

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

vagrant garden
#

If you start with stuff like moving some players multiple time per ticks that's just asking for people to cheat.

tribal silo
tribal silo
austere yacht
tribal silo
#

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...

austere yacht
#

yes

#

you do not assume that the server tick and the client tick happen at the same exact real time

vagrant garden
austere yacht
#

you always assume that the client sees an outdated state

tribal silo
# austere yacht 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

austere yacht
#

i.e. the server synthesizes a "pressed" state from "up" and "down" events received from the client

vagrant garden
#

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

tribal silo
austere yacht
#

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

sharp axle
#

This seems to be getting into rollback which is a bit beyond anti jitter

austere yacht
#

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?

vagrant garden
graceful zephyr
trim axle
#

would Netcode for GameObjects handle 80 to 100 players? survival/space/crafting type of game.

#

or better off going with something like mirror?

sharp axle
orchid cave
#

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

sharp axle
orchid cave
#

Thanks, making another class to store player data sounds like a good idea to look into ๐Ÿ‘

late prairie
#

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?

wanton oxide
#

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];
}
atomic crest
#

Can I use PlayerPrefs with Photon Pun 2?

spring crane
# atomic crest 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

plucky snow
#

What is the right way to initialize NetworkList<NetworkObjectReference>? I've tried some stuff but get the "All NetworkVariableBase instances must be initialized" error

open phoenix
#

Hello, Can someone tell me the difference between SDK matchmaking and API matchmaking?

unborn gale
#

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

craggy garden
#

Does NGO support WebGL at this time?

sharp axle
sharp axle
sharp axle
wet compass
#

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?

sharp axle
unborn gale
#

It worked, thank you a lot

faint cedar
#

how can I destroy a network object?

wanton oxide
#

Wow, steamworks actually does not give you any possibility to kick members from a lobby, abut allows you to listen to the memberkicked event? wut

wanton oxide
#

And....wow, they suggest to send a custom packet and leave the lobby on the kicked client then LUL 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".

hard creek
#

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 ?

hard creek
#

Is it NetworkManager.Singleton.LocalClientId ?

radiant dome
#

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?

weak plinth
#

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

weak plinth
# radiant dome Guys in the method "OnNetworkDespawn()" how can i see the player who despawn?
    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

radiant dome
#

ok when i will return home i try it and i tell you how it goes

#

thanks

kindred crest
#

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?

radiant dome
#

it is like using these parameters i can not override the method

mighty wave
#

What could I use instead of broadcastsReceived, seems outdated in the new version of Mirror

radiant dome
#

Guys when the method "OnNetworkDespawn" is called is there a way to get the player info of the player who quit?

winged dome
#

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?

shrewd junco
#

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

wise fern
#

Same I don't know how and I can't start my game

shrewd junco
#

@wise fern dont dm me, just type in here.

sharp axle
# shrewd junco I get these errors when I install the package for client network transform, i in...

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;
        }
    }
}
shrewd junco
#

I ended up doing that, i was just concerned about why the samples were full of errors. thanks still

wise fern
#

@shrewd junco It doesn't let me put the script on the player how did you fix it

sharp axle
wise fern
#

I got it

wanton oxide
#

why did they removed the NetworkDictionary? First Network Variable type i wanna use, just to figure out it got removed :/

safe cloak
#

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 ๐Ÿ™‚

sharp axle
# wanton oxide why did they removed the NetworkDictionary? First Network Variable type i wanna ...
GitHub

Community contributions to Unity Multiplayer Networking products and services. - multiplayer-community-contributions/com.community.netcode.extensions/Runtime/NetworkDictionary at main ยท Unity-Techn...

radiant dome
#

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

alpine pulsar
#

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

hard creek
#

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.

heavy swan
#

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.

hard creek
#

@heavy swan your character is server authoritative ?

heavy swan
#

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

hard creek
#

@heavy swan What does mean "Character move itself" ? from client user input ? or by IA ?

heavy swan
#

I'm not sure what those two things mean.

#

In short, my movement method is pretty much transform.position += inputVector.normalized

sharp axle
heavy swan
hard creek
sharp axle
hard creek
#

@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.

spring void
open phoenix
#

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

sharp axle
craggy garden
#

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.

austere yacht
craggy garden
#

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.

austere yacht
craggy garden
#

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.

austere yacht
#

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

craggy garden
#

But all of those solutions are bad practice

austere yacht
#

who says?

craggy garden
#

Race conditions

austere yacht
#

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

craggy garden
#

Yes, but it's been designed to not have any way to accept any inputs before flying out the door.

austere yacht
#

idk what that means

craggy garden
#

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.

austere yacht
#

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.

craggy garden
#

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.

austere yacht
#

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

craggy garden
#

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.

austere yacht
#

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

craggy garden
#

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.

austere yacht
#

maybe, you can take that up with the NGO designers, personally i don't have an issue with the way it is

craggy garden
#

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.

open phoenix
#

Im trying to make a brawl stars-styled matchmaking system for my game and I don't know where to start.

silent flame
#

is there a way to sort by distance to client when searching for lobbies?

radiant dome
#

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?

sharp axle
sharp axle
silent flame
sharp axle
silent flame
#

cuz i set up relays from my lobbies also, but if cannot search by distance its still kinda meaningless

sharp axle
silent flame
sharp axle
silent flame
sharp axle
silent flame
#

or u mean thers a building region variable? As i dont see that one

sharp axle
silent flame
silent flame
marble cosmos
#

hello, Is that the right chanel for questions about netcode?

sharp axle
marble cosmos
#

nice thx

open phoenix
sharp axle
open phoenix
#

do i tho?

#

oh yeah

#

lol

#

ill get to that later

faint cedar
#

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?

nocturne vapor
#

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

faint cedar
#

thank you

gleaming knoll
#

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);
        }
    }
arctic iris
#

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;
    }
austere yacht
open phoenix
#

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.

gleaming scarab
open phoenix
#

but i have another problem

#

those two override functions are not being called

gleaming scarab
#

If there are no more errors, then maybe they're never occurring because their requirements weren't met - players leaving the room and whatnot.

weak plinth
#

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?

balmy basin
#

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?

sharp axle
weak plinth
#

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

sharp axle
balmy basin
sharp axle
balmy basin
sharp axle
spring void
balmy basin
sharp axle
charred abyss
#

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?

spring void
# charred abyss Hi, I am about to start creating a multiplayer game. I wanted to use a cinemachi...

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.

charred abyss
sharp axle
#

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

charred abyss
sharp axle
#

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.

charred abyss
sharp axle
#

The sample I posted has the local player assign itself to the camera's follow script

charred abyss
charred abyss
sharp axle
#

Different games have different requirements. There is no wrong way of doing things

spring void
thick valley
#

Using Photon Pun 2, and even though both gameobjects have Transform View Classic, the localScale of the canvas isn't synchronized between clients?

brisk bluff
#

So networking and rigidbodys don't really go hand in hand right? So would I just implement my own gravity?

sharp axle
brisk bluff
#

it had some delay when using it

#

if you werent the host

sharp axle
#

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.

nocturne vapor
sharp axle
#

You might have better luck over on the Photon Discord. Check the pinned message here for the link

wraith flax
#

Is it possible to send a client RPC to one client with Unity NGO?

wraith flax
#

This doesn't seem to work

olive vessel
#

Well that's how it is done

#

Feel free to show your attempts, code context

wraith flax
#
[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

sharp axle
wraith flax
#

Thank you two

steep loom
#

can any one give me some refrence iwant to make model under 2000 polycount

radiant dome
#

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

raven bear
#

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

sharp axle
nocturne vapor
# radiant dome Do you think it is a client-prediction problem?

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

radiant dome
graceful zephyr
#

or if one is the host, only the client needs to do full world prediction

radiant dome
graceful zephyr
#

to get this to be smooth

#

on all ends

radiant dome
wet compass
#

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

wet compass
#

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

wet compass
#

for sure,although its not working with the callback.

#

seems like their connection approval is broken when not approving a connection.

timber lava
#

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

calm granite
#

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

nocturne vapor
# calm granite how would I have code be called on all clients. im trying to make every client r...

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() {
}
faint cedar
#

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?

faint cedar
#

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

little violet
#

I get this error when I attach a network object to a prefab and instantiate that prefab. Does anyone know a fix?

austere yacht
hazy galleon
#

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

faint cedar
#

Destroyed via GetComponent<NetworkObject>().Despawn();

#

and their position is updated by changing their transform

#

transform.position += direction.Value * speed.Value * Time.deltaTime;

#

@austere yacht

austere yacht
faint cedar
#

the bullets have network transforms

austere yacht
faint cedar
#

whats the problem tho

sharp axle
# faint cedar 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.

rocky surge
#

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?

open phoenix
#

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

calm granite
#

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

grand salmon
#

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.

austere yacht
# grand salmon Hey I hope I'm in the right place I'm currently pretty desperate I think I have...

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.

grand salmon
#

Thanks for taking the time to answer I will look into fusion a bit more ๐Ÿ™‚

kindred crest
#

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?

compact fox
#

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.

lusty moat
#

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.

spring crane
heady breach
#

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

wide girder
heady breach
wide girder
#

If you're doing networking you should be able to answer that at least.

heady breach
#

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

wide girder
#

And if you're still learning, you should start with single player projects.

heady breach
wide girder
#

Wdym?

#

Did someone else write that code?

heady breach
wide girder
#

Ask the person that wrote the code. Or read through all the relevant code and try to guess.

olive vessel
#

LobbyEventCallbacks Have you stuck this into Google?

#

There's two forum posts with instructions, did you try them?

heady breach
wide girder
#

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.

sharp axle
# heady breach Anyone here to help me with multiplayer callbacks.. I have a CS0246 error.. Ca...

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

GitHub

A sample showcasing a minimal implementation of a lobby experience using the Lobby and Relay packages. - GitHub - Unity-Technologies/com.unity.services.samples.game-lobby: A sample showcasing a min...

weak plinth
#

Sound = Audio Source
PhotonV = Photon View

charred bough
#

How I can check if entered relay id exists when client is connecting to relay

wanton kernel
#

Hi guys, question, which networking method should I use to make a game like Tales of Pirates, Ragnarok Online, Nin Online, byond type games?

nocturne vapor
wanton kernel
#

Im calculating around a 100 player max for a server

nocturne vapor
#

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