#archived-networking

1 messages · Page 39 of 1

sharp axle
#

The player objects should be persistent between scenes by default.

fluid lintel
plain zenith
#

whats the best way to create prefabs for objects that players shoot that are similar to projectile, woulde it be to create scriiptable objectsm and load a database of the info after the player creates it, and use the scriptable object info to spawn it on every client. Or would it be to create like a network object prefab with synced network transforms via ;unitys built in network transform. I feel like unitys built in system for network transforms is not good when it comes to calculating precision collisions etc

sharp axle
hardy garden
#

Is it normal that any other scripts that are on the prefab spawned by the network manager are not owned by the player, despite the network object script on the prefab it self being owned?

sharp axle
livid grotto
#

If each client stores their selected materials in a singleton (StorePlayerSkin), and the server applies the materials to each player's prefab, shouldn't each player get their own unique material? Why are all player prefabs ending up with the same skin?

using Unity.Netcode;
using UnityEngine;

public class SkinApplier : MonoBehaviour
{
    
    
    /*
    No Inspector referênciar os Renderes
    */
    
    [Header("Mesh Renderer Reference(Partes, para aplicar as skins)")]
    [SerializeField] private Renderer headSkinRenderer;
    [SerializeField] private Renderer bodySkinRenderer;

    private void Start()
    {
        ApplySkinsServerRpc();
    }
    
    /*
    Cada função serve para aplicar o material guardado no singleton "StorePlayerSkin" no respetivo mesh.
    */
    
    
    public void ApplyHeadSkin()
    {
        if (headSkinRenderer != null)
        {
            headSkinRenderer.material = StorePlayerSkin.Instance.GetHeadSkin();
        }
    }

    public void ApplyBodySkin()
    {
        if (bodySkinRenderer != null)
        {
            bodySkinRenderer.material = StorePlayerSkin.Instance.GetBodySkin();
        }
    }

    [ServerRpc]
    private void ApplySkinsServerRpc()
    {
        ApplyBodySkin();
        ApplyHeadSkin();
    }
}

plain zenith
sharp axle
torpid stirrup
ebon thorn
#

Hey, this questions has probs been asked before but can anyone suggest any good courses / books / videos e.t.c to begin learning networking? I'm interested in doing a 2-4 player co-op kind of stuff, nothing too crazy.

sharp axle
#

Also the Code Monkey multiplayer courses are probably still the most comprehensive ones out there

agile python
#

hey guys! anyone seen this before?
i'm having an issue with Photon Fusion — was working fine, didn’t touch anything, and suddenly it started bugging out between test runs.
feels like a config thing but not sure 🤷‍♂️

```FieldAccessException: Field Fusion.NetworkBehaviour:Ptr' is inaccessible from method Twinny.System.NetworkedLevelManager:set_manager (Fusion.PlayerRef)'

fluid walrus
#

that looks like the access modifiers are different between what you built against and the actual library being loaded, maybe this access modifier changed in an update and you've got an old version cached somewhere or something?

livid grotto
sharp axle
white fable
#

posted this in advanced as well but then i saw there was a networking area anyway im making a multiplayer game and im trying to use Scriptable Objects but using NGO Scriptable Objects dont network. So I come to ask what is the solution to still using the modularity of Scriptable Objects but still be able to network them

sharp axle
waxen quest
#

Unity sent me bill, I didn't even exceeded the relay limits prev month

#

I was almost at 98% and still got charged

#

This made me cancel my Unity subscription

tame slate
sharp axle
tame slate
sharp axle
#

Bandwidth is separate from the CCU limit.

tame slate
#

I'm aware of that

sharp axle
#

At least it's listed separately

tame slate
#

is that 119 he's being billed for 119 beyond the 150?

#

Seems like it - just weird if it's listed like that as everything else lists the quantity with the free tier included

tame slate
#

If that's the case @waxen quest you were miles beyond 98% usage.

#

Either that, or there was a mistake in your billing - but that seems less likely

valid willow
#

What could be the cause of NetworkTransform.Teleport() still causing the player to interpolate, I can see on my clients that the player lerps towards the target position instead of appearing immediately (teleporter feature)? Netcode 2.3.2, Distributed Authority. The teleported object has no Rigidbody component or similar.

waxen quest
waxen quest
valid willow
tame slate
waxen quest
#

I cancelled it on May 1st

tame slate
#

The billing shows 119 GiB used which is either 119 over the free tier or 119 total - either way that’s 80% or 180% usage so I’m not sure how your dashboard usage was showing 98%

frigid mist
#

@old umbra same question here though

#

do you recommend any specific option for networking for my use case?

old umbra
#

Yes, of course, this is where you should be posting it

#

and not forwarding my message.

frigid mist
#

is there a particular recommendation for how to implement multiplayer? (as for the context of my use case: it's a turn-based board game)
it seems like there are several options, so I'm not sure which one would be the best for me

sharp axle
# frigid mist is there a particular recommendation for how to implement multiplayer? (as for t...

Really depends on the game. But the Unity 6 Multiplayer Center would recommend using Cloud Code for a turn based board game
https://github.com/Unity-Technologies/com.unity.services.samples.multiplayer-chess-cloud-code

GitHub

Contribute to Unity-Technologies/com.unity.services.samples.multiplayer-chess-cloud-code development by creating an account on GitHub.

crimson sleet
#

To confirm, [ghostfield] component variable on a ghost may only be changed by the ghost owner is that correct?

sharp axle
crimson sleet
#

Yeah server as well I mean

#

As well as the ghost owner

frigid mist
#

can someone help me understand what is causing this error? (is it repeatedly printed to debug log every 1s)

#

I don't know if this is enough context to figure it out so please tell me if you need more code/screenshots

#

the line that is causing the error is driver.ScheduleUpdate().Complete();, where driver is a NetworkDriver

sharp axle
frigid mist
#

when a server is running the client does not connect successfully, and when the server is not running the client starts logging these errors on trying to connect

frigid mist
sharp axle
#

Netcode for Gameobjects

frigid mist
#

also I don't need to send gameobject transforms over the network, only messages triggering certain events

#

maybe this is also possible with NGO but I don't know how to do it :P

sharp axle
frigid mist
#

I missed this documentation earlier so thanks for linking it

tame slate
waxen quest
tame slate
#

Would be curious for an explanation if you end up reaching out to support.

waxen quest
waxen quest
#

In first 10 days of May I had Bandwidth lower than CCU

#

Since it will consumed. Bandwidth surpassed the CCU. It's not that I am consuming a lot of bandwidth for low CCU

valid willow
#

I've got a funky issue with Netcode, Distributed Authority. If a player is joining a session and the host of the session leaves, the Sessions API tells me that the player joined successfully (I'm querying available sessions 1st and then join one via JoinSessionByIdAsync). Though after about 20s they get disconnected automatically as actually the connection was never established (the NetworkManager callbacks do not report a client connect).

I'm suspecting the once the host leaves, the network session gets yeeted and the joining player ends up in an invalid session. I've configured keep alive time for lobbies in Unity Dashboard to 2m, tho that doesn't seem to affect anything. Forums aren't that helpful also... Anyone have some tips?

P.S. I've also tried replacing JoinSessionByIdAsync with CreateOrJoinSessionAsync, though I get same results. I suppose the Sessions API thinks the network session is still valid and doesn't try to re-create it, while relay is actually another state 🤔

sharp axle
valid willow
#

This happens almost at the same time when the owner leaves. The session id is not changing as I'm looking at the logs - it's the same for the owner and the client that's connecting.

To clarify, while a new player is joining the session which only has the host in it (Sessions API is doing their thing), then the owner leaves. The player that's joining then fails connection (after connect_retries x connect_timeout), but the Sessions API gladly returns a valid ISession object before that happens and NetworkManager kicks in (Sessions API calls lobbies and other APIs before talking to NetworkManager).

TL;DR

  • Player A starts Session A and joins fully
  • Player B starts connecting to Session A
  • Player A leaves Session A
  • Player B retrieves a valid ISession object for Session A
  • Player B waits 10s and NetworkManager times out

...right now my workaround for this issue is to check NetworkManager.IsClientStarted after retrieving an ISession object with a timeout of 5s. If this fails, I leave the session (LeaveAsync()) and retry connecting to the session, but this adds a lot of extra time to the connection flow...

sharp axle
valid willow
#

I was assuming that Active Lifespan would alleviate this in DA 🤔

The game I'm designing works similarly to Gorilla Tag, where once you enter a specific area, you join a network session. Since the players will be running around all over the place, sessions will be destroyed and created, which means such race conditions will occur. Isn't there a way to keep the session active somehow?

sharp axle
valid willow
#

Regardless, why am I allowed to join a session from which the host has disconnected?

sharp axle
valid willow
#

Mhm, probably will do, thanks anyway

fast yacht
#

Hi all! Hopefully I'm on the right channel.

I am making a 2D card game (free-time project). The game features different cards, character and item artworks. You can interact with the character and items sprites, the cards are forming a properly working deck (you can draw, shuffle, place back cards etc.).

I want to make the multiplayer part of the game. I want the players to be able to self-host the game/session so the other player(s) can join them. Each card drawn from a deck should go the specific player (so for example after drawing a card that player can see what is the card, but the others should see the back sprite etc).

For authentication I want to use Discord, but I have no idea if it's a viable idea.

Regarding these ideas, what technology/package etc could you guys recommend me? This is a project made in my free time so far (just for fun) and because of that I want to use free solution (I'm willing to and see as an interesing challange to implement many things/logics if needed). Thank you advance!

sharp axle
fast yacht
#

So it's more about how I implement the things and anything (I mean any framework) could work instead of the framework itself restricting me?

sharp axle
fast yacht
#

And am I able to use a "third party" software as an authenticator/account manager such as Discord with these?

sharp axle
fast yacht
#

And Unity authentication is totally different/standalone from Netcode for Gameobjects for example, so I can combine both, right?

tame slate
fast yacht
#

Great, thank y'all!

twin grove
#

Hi all, how do I make a player lobby via Steam + netcode?

wind shoal
#

I am using netcode for entities, here is my bootstrapper:

using Unity.NetCode;
using UnityEngine;

[UnityEngine.Scripting.Preserve]
public class GameBootstrap : ClientServerBootstrap {

    public override bool Initialize(string defaultWorldName) {
        AutoConnectPort = 7979;
        return base.Initialize(defaultWorldName);
    }

}

here is my error (attached as file but basically socket creation failed)

#

it doesn't always happen, does that mean its an editor bug

sharp axle
sharp axle
wind shoal
sharp axle
wind shoal
#

Btw ty for your help

sharp axle
wind shoal
#

I don’t think I do because I took codemonkey’s early project and now I’m editing it I didn’t do anything with the bootstrapper

sharp axle
wind shoal
real monolith
#

Any idea why I'm getting this? NullReferenceException: Object reference not set to an instance of an object DevelopersHub.RealtimeNetworking.Client.Sender.SendTCPData (DevelopersHub.RealtimeNetworking.Client.Packet _packet) (at Assets/DevelopersHub/RealtimeNetworking/Scripts/Sender.cs:14) DevelopersHub.RealtimeNetworking.Client.Sender.TCP_Send (DevelopersHub.RealtimeNetworking.Client.Packet packet) (at Assets/DevelopersHub/RealtimeNetworking/Scripts/Sender.cs:39) DevelopersHub.ClashOfWhatecer.Player.Start () (at Assets/Scripts/Player.cs:81) I'm not getting any errors in VS, just Unity

#

I've tried asking AI for some help but Ai is of no help in this situation. I can't really test my game until this is fixed sadly

sharp axle
sharp axle
real monolith
wind shoal
inner stream
#

so when using relay for multiplayer, im having an issue where my a script running on my client is saying that IsOwner = false, and i was under the impression that if it was a script attached to their character, they were always owner.

sharp axle
zinc owl
#

Hey, I could use some help with spawning a game object through a ui button over a network where the button is only instantiated on client side and is a part of a prefab itself. Pressing the button should send an Rpc to the server to spawn the object but its not registering any clicks, but the button is being linked to the variable so its not null. Anyone have any ideas

inner stream
paper summit
#

Anyone know how long does it take for the ngo devs to respond to a github ticket?

#

After reading through the docs and the anticipation github sample, the sample is basically showing an example of a client authority anticipation where clients have fulll control of the anticipated value. It does not show examples of a server authoritative setup. Additionally there's a potential bug in the .Smooth() function which I've submitted a bug ticket yesterday.

tame slate
sharp axle
#

Hey, I could use some help with spawning

sharp axle
inner stream
#

from what im seeing in my print statements, yes, the host is considered owner and local player, while the client isnt consiered to be either. the thing i dont get is that my movement code runs a script attached to the same object, and somehow that works perfectly fine

inner stream
sharp axle
inner stream
#

owned client ids are 0 and 1 tho, so those are different

sharp axle
sharp axle
inner stream
sharp axle
#

Yes. You can also use networkObject.SpawnAsPlayerObject() if you want to spawn it manually

inner stream
crimson sleet
elfin token
#

Hey guys, I'm trying to do something simple in netcode. I'm using the 2d space shooter example's object pool(slightly modified) and all I want to do, is deactivate all of the objects that are in the dictionary of queues

sharp axle
# crimson sleet

Sounds like you deleted a ghost on the client and not the server

sharp axle
elfin token
elfin token
sharp axle
elfin token
#

The object pool code works flawlessly, but I can't seem to devise a functional way of deactivating my object pool whenever I change scenes.

sharp axle
elfin token
#

I may have an older version that doesn't

elfin token
# sharp axle Huh, it should do that automatically

My object pool is in a persistent scene and thats where all the objects stay. that way i never have to recreate the object pool. Simply destroying them with the active scene was generating tons of errors

sharp axle
#

dunno about that. spawned network objects have always been destroyed on scene change. Unless you specifically set it to do not destroy on load

elfin token
elfin token
sharp axle
#

lol, its only 9pm where i am

elfin token
crimson sleet
#

If you go to the forwarded message I put the logger there

#

It says the entity was deleted by blank system

sharp axle
paper summit
#

Most of the Rpcs are either SendToEveryone OR SendToServer and the value they are sending to the server, is used directly to set the authoritativeValue. That's what I mean by the samples being Client* Authoritative. A server authoritative approach would necessitate additional conditions in that ServerRPC or even (in my case) be required to be called elsewhere due to the setup. So in this regard, the samples either didn't showcase a more advanced approach OR it's limited to whatever they have included in it (where the Anticipate() must be called directly in the initial ServerRPC from the client, and cannot be called elsewhere). For this I believe no one here has the accurate answer at this point and we'll have to wait for the NGO team to get back.. Hence my initial question is how long would they take to respond to a git bug ticket (if anyone knows).

inner stream
#

@paper summit you good with unity relay?

paper summit
#

If this is because it's a sample that they are directly modifying the value in the ServerRPC and sending the actual Value from the Client (not input value), and that for the actual approach I should be directly anticipating in that initial ServerRPC, then I need to confirm if this is the only way to get it to work? Because this means that I can only Anticipate() whenever I send Player's Input data from the client but I can't guarantee that my AddForce will be executed before Anticipate() is called if i roll with what the Samples are doing. If so then it will mean that I have refactor my code just for Anticipation to work.. I hope this is not the case and there's more flexibility to this system.
My ServerRPCs are currently only used to send Inputs, not sending the position of the Client nor AddingForce and Anticipating() in it.

paper summit
inner stream
paper summit
inner stream
paper summit
#

You're trying to move the client on the client side?

inner stream
#

well im doing hotbar stuff but my issue is that when i call isowner on client its always false

#

i thought theyre supposed to spawn in with isowner and is local player

paper summit
#

E.g in Awake(), Start(), OnEnable(), OnNetworkSpawn()

inner stream
paper summit
#

You could try ChangeOwnership to see if it works for you

inner stream
#

yk i tried that before but had another bug i needed to fix first lemme give that another try

paper summit
inner stream
paper summit
inner stream
tame slate
# paper summit Most of the Rpcs are either SendToEveryone OR SendToServer and the value they ar...

It’s a generic sample showcasing anticipation. It’s not going to show advanced approaches.

This is like saying sending inputs makes things client authoritative just because the client has full control over the value being sent which dictates what movement values are being set.

It is up to the server to validate whatever the client is requesting the authoritative value to be set to and that’s almost always game specific and would not be covered in a sample.

#

at the end of the day the server is the only one that can directly set the value and sync that change to all connected clients. That’s what makes it server authoritative. Validation is another topic entirely.

paper summit
trim hedge
#

Is there any free networking library for ECS? For GameObjects you have things like Mirror, but I can't find for ECS.

fluid walrus
trim hedge
fluid walrus
#

you mean for bandwidth and CCUs? you're normally going to have to pay for that at some level regardless of what service you use, electricity costs money 😄

sharp axle
fluid walrus
#

well, free as in you have to sell your game on their storefront and give them the cut 😛

trim hedge
fluid walrus
trim hedge
fluid walrus
#

well you said you don't want the things that those libraries do, but the things they do cost money to do

sharp axle
#

Most services will have a free tier that a first time indie dev is very unlikely to surpass

trim hedge
#

AFAIK (haven't research much because it doesn't support ECS), Mirror is a networking library which is open source and free for example. They don't have server for lobby and stuff.

fluid walrus
sharp axle
fluid walrus
#

i guess it's worth mentioning that in unity's parlance there's a difference between the network library and the network transport, so you can use different transports (network backend) with the same library (multiplayer game code) , like you can run Photon or other third party libraries through NGO if you want to

#

i haven't tried it myself but i assume you can swap out the transport with Netcode for Entities like you can with NGO 🤔

trim hedge
#

Interesting

nimble crow
#

Is having one entity with ghost component for each item in a players inventory too expensive for performance? (in ECS, netcode for entities)

sharp axle
sharp axle
nimble crow
sharp axle
nimble crow
#

i think its because i didnt have a fixed size, maybe i will do that

static quest
#

guys i got a random question, if I make a game in unity with c# and then later on I realize i want to make it multiplayer, like networked. Am I essentially gonna have to redo the entire games code?

#

or only things that will need packets so cant be hacked

sharp axle
fluid walrus
#

it's possible to do (have had to do that before 🥲 ) but it's a big job and depends a lot on the type of gameplay, obviously it's much easier to make things multiplayer-friendly from the start

static quest
#

yikes ok, anyone able to link a little guide to kick start me in that direction? im doing 2d top down to just make a smaller game for practice with networking then to start.

sharp axle
fluid walrus
#

it'd probably be best to look at some of the sample projects for NGO (or your library of choice) first of all, get familiar with the structure required for multiplayer before you start applying it to the existing game

static quest
#

okay and any help i can come here?

#

@sharp axle is multiplayer for 3d and 2d the same ? or do i need indiviual learning methods

sharp axle
jade gust
#

Hi I am pretty new to unity but I’m trying to make a four player game. That’s very simple. It’s just a game where you walk around how would I network it?

lilac escarp
#

I am making a dungeon generator in Unity and keep running into the same error over and over when starting a Netcode for GameObjects host. I have treid re-adding the network objects on each of the room prefabs and have also tried restarting Unity, neither of those did anything. No prefabs with network objects are in the scene when starting the host.

Error:
Exception: Room_Corner(Clone) tried to registered with ScenePlacedObjects which already contains the same GlobalObjectIdHash value 272924042 for Room_Corner(Clone)!

Script that is spawning the rooms.

flat harbor
#

when using photonView.IsMine everything just blocks up

#

i cant move anymore but other scripts work just as fine

sharp axle
undone pulsar
#

Hello ^^
I'm making a 2d game where the camera is static for both players but each player start at a different location in the scene
I'm having a problem Initializing the cameras for each player
I tried to prefab the camera and have a script that is attached to the player have a reference to it
code: https://pastebin.com/tu2Kz300
Looking at the logs the ClientRpc does get called on the host and the client but for some reason it does not init the camera for client 2 at all

appreciate the help 🙏

lilac escarp
sharp axle
sharp axle
undone pulsar
sharp axle
#

Make sure there isn't a network transform on the camera

sharp axle
# lilac escarp No

Are you getting the error on the host as well as the clients? No dynamically spawned objects should be registering as scene objects

lilac escarp
#

I've only tested on the host plus the generation code only runs on the server.

lilac escarp
#

Anyone got any idea of what's happening?

lilac escarp
#

I think it's because my code is destroying rooms before it's finished properly spawning on the server.

jade gust
#

Hi I am pretty new to unity but I’m trying to make a four player game. That’s very simple. It’s just a game where you walk around how would I network it?

#

ple

#

i cant

#

do one my one

jade gust
#

ok

#

i will try

#

ty

wanton tartan
#

hello, im facing an issu with vivox where audio from other players in position channels is relatively low even when close up, how can i increase it? because in the Channel3DProperties class no value can be modified.

tame slate
wanton tartan
#

the IDE can't even find the values

tame slate
# wanton tartan

There’s a default constructor and then a constructor with 4 parameters. If you use the latter, none of the parameters seem to be optional so you’d have to pass in all 4. In your above screenshots you’re still technically using the default constructor

wanton tartan
wanton tartan
crimson sleet
#

Why are player ghost models always so stuttery

#

Like the transform pos moves smoothly

#

But the mesh stutters about

#

I saw some people online with this problem too but no solutions

sharp axle
crimson sleet
#

Order of which kind of systems

#

I’m fairly sure I’m changing player velocity only in a single player movement system

#

What other ones might matter?

sharp axle
# crimson sleet What other ones might matter?

if you look at the DOTS character controller sample
You grab your inputs in [UpdateInGroup(typeof(GhostInputSystemGroup))]
Then you apply those inputs in [UpdateInGroup(typeof(PredictedSimulationSystemGroup))] [UpdateAfter(typeof(PredictedFixedStepSimulationSystemGroup))]
anything with physics would be in [UpdateInGroup(typeof(PredictedFixedStepSimulationSystemGroup), OrderFirst = true)]

crimson sleet
#

Yeah I’m doing all of that though

livid grotto
#

I don't know why the rig in the hands doesn't sync between clients, and like the hand kind of moves but not right.
The prefab has a network transform and animator.

sharp axle
sharp axle
lilac escarp
#

Does Steamworks (with Facepunch transport) have a voice chat solution?

twin grove
#

Hey guys

#

no work?

#

I get an error when installing on version 6.1

sharp axle
twin grove
#

last version?

crimson sleet
#

I don’t think it’s lag at all

#

It stutters at regular intervals

#

Like every 1s or so

#

And by the same amount every time

sharp axle
crimson sleet
#

Yes but like I’m saying it’s the mesh only

sharp axle
crimson sleet
#

its one entity

silver burrow
#

Is it worth considering asset store solutions for networking like Fishnet or should I just put in the work to learn Unity’s Netcode? I’m not looking to do anything more intensive then 4ish players in a coop simulation type game

tame slate
silver burrow
sharp axle
#

Also depends on the assets. There are some really well done assets for Fighting Games or Online TCGs that could save you a ton of time and effort.

white fable
tame slate
#

!collab

raw stormBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

hybrid dew
#

Hi all,

I am a backend developer and I want to build my own backend that manages game sessions
chat
player profiles
player data
and so on

but the multiplayer itself, I want to use unity's netcode

is this doable or do I have to implement everything through netcode?

tame slate
sharp axle
upbeat summit
#

how do i stop my players from being able to shoot themselves in the back, if they are moving forward while fireing.
my current logic goes like

  • Player shoots and sends server RPC while moving forward
  • Server receives request, spawns in the bullet from the guns current barrel transform.
  • By the time the server has finished processing the request, the player is already infront of the bullet and dies
upbeat summit
long leaf
# upbeat summit how do i stop my players from being able to shoot themselves in the back, if the...

I want to help, but I'm really new to multiplayer coding. But here are some thoughts: are you using Raycast for bullets (maybe a good option); could you make it so that the bullet can't damage the object that instanciated it (this doesn't sound bad to me, although I'm quite sure how to do it. If you have a method for summoning bullets, you could and a parameter thats a GameObject where you send the player to the method. If the object hit is the player GameObject, do nothing/ignore the hit); you could maybe offset the bullet to spawn forward.

long leaf
#

are you using a Raycast?

upbeat summit
# long leaf are you using a Raycast?

i am using a hybrid, the location of the bullet is calculated sort of like physics, but it also raycasts one physics iteration forward to tell if its gona hit something

long leaf
#

So what the bullet hits is calculated with a Raycast?

#

wait no mb

upbeat summit
#

yes

long leaf
#

I think I understand

upbeat summit
#

idk how to explain

long leaf
#

is the bullet an actual gameobjekt that uses raycasting?

upbeat summit
#

the bullet isnt a gameobject, it is a position and velocity which is stored in a list

long leaf
#

and then you Raycast from that position in line with the unit vector from the velocity?

upbeat summit
#

oh wait nvm
i mixed up something this one actually is a gameobject

long leaf
#

the bullet is a gameobject?

upbeat summit
long leaf
#

alright, is there a method you call to spawn the bullets in?

upbeat summit
#

i use two projectile systems, one for bullets and one for shrap, which is why i mixed it up

#

yes

#

void ShootServerRpc

long leaf
#

do you call this from the player?

upbeat summit
#

yes, i think i could actually mitigate this by what you said earlier, i could just check if the bullet hit its own owner

long leaf
#

yeah, if you make the ShootServerRpc(GameObject owner)

#

I think, as I said, limited time with multiplayer in unity, but have coded Java before

delicate parrot
#

you mean NetworkObject as param

upbeat summit
#

each bullet is assigned an owner during runtime already, i just need to add a check

long leaf
#

alright, nice

long leaf
upbeat summit
#

Js dont run too fast 🙏🥀

long leaf
#

unintended speedCheck 🥀

upbeat summit
#

that was an easy fix lmao, thanks!

long leaf
#

😮 nice!

sharp axle
long leaf
#

can anyone help me with first-person movement / camera in multiplayer using Fishnet?

livid grotto
#

My bullet when shot in the client it spawns in a difference place instead in the place intended.
I use a server rpc that receives the transform position and rotation then spawns the bullet in that position. The spawn position has a network transform.

sharp axle
sharp axle
livid grotto
#

here's the script,

using System.Collections;
using Unity.Netcode;
using UnityEngine;

public class ShootScript : NetworkBehaviour
{
    private CharacterButtonsReference bt;
    
    
    [SerializeField] private NetworkObject bulletPrefab;
    [SerializeField] private Transform fireHole;
    [SerializeField] private float cd;

    private bool canShoot = true;

    private void Start()
    {
        bt = GetComponent<CharacterButtonsReference>();
        StartCoroutine(ShootCooldown());
    }


    private void Update()
    {
        if (!IsOwner) return;
        
        if (bt.PlayerButtons.Shoot() && canShoot)
        {
            canShoot = false;
            ShootServerRpc(fireHole.position, fireHole.rotation);
        }
    }

    private IEnumerator ShootCooldown()
    {
        yield return new WaitForSeconds(cd);

        canShoot = true;
    }
    
    [ServerRpc]
    private void ShootServerRpc(Vector3 position, Quaternion rotation)
    {
        var bulletInstance = Instantiate(bulletPrefab, position, rotation);
        bulletInstance.Spawn();
    }
}
sharp axle
sharp axle
fallow grotto
#

is there any way to output vivox voice chat to an audio source?

#

or do I need to switch to steam voice chat or similar

fallow grotto
#

Ok thanks

normal tulip
#

hey y'all, this might be a stupid question but,,,

how do you do networking. period. i've tried on like 5 different projects and have failed every time, my literal only goal is to get one computer to connect to a nother, just have two players running around on a screen together from two different computers, but I don't know how to do that.

could someone help me get started, if they have some free time?

mental jolt
# normal tulip hey y'all, this might be a stupid question but,,, how do you do networking. per...

i've been using this tutorial to get started:
https://www.youtube.com/watch?v=msPNJ2cxWfw

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

▶ Play video
#

Although I have an issue, if anyone has an idea. Using that ^ (Netcode & Unity Relay), I've been able to set up networking. I have an issue though. The client's player prefab isn't being created. I've confirmed that
1- Host's prefab is created
2- Client successfully connects to the relay (according to debug logs on client's side)

I'm not sure what would be stopping client's player prefab from spawning, if anyone has an idea

normal tulip
sharp axle
sharp axle
# normal tulip 6 hour course?

💬 Here is the Multiplayer Course! I really hope both of these FREE courses help you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Project Files, FAQ https://cmonkey.co/freemultiplayercourse
🎮 Play the game on Steam! https://cmonkey.co/kitchenchaosmultiplayer
❤ IF you can afford it you can get the pa...

▶ Play video
normal tulip
#

yoo

#

hey ty :D

long leaf
#

Which Networking solution would you guys recommend? I've been trying to learn some Fish-Net, but I find it quite difficult (if anyone is knowledgeable: I'd love to pick your brain). What solutions are you guys using/would reommend?

sharp axle
long leaf
#

I mean, if I understand it right, it's all based on the same stuff, just implementing different stuff. right?

sharp axle
#

They all use some form of network variables and RPCs for the most part

#

Some have client prediction built in. Some have distributed/shared authority models

long leaf
#

If I want to make a multiplayer fightning game for me and some friends, what attributes would I be looking for? Not a FPS, but swordfighting.

#

I'm pretty new to all of this, and the choices I can make are honestly overwhelming, never knowing whats right or whats wrong + everything feeling like it always goes wrong

sharp axle
lofty ravine
#

I'm making random generating platformer sandbox which allows for multiplayer and loads parts of the maps in sections/chunks.

All players should have the same map appear to them - I do this by having a list that should stay the same through all clients and the server at all times. Currently I'm using mirror with a synclist to try to accomplish this - but this only works if the host player (there is no single dedicated server) loads the section first.

If a random player is able to get further than the host and loads a new section on its end - it won't be added to the synclist and that area can appear different for the host and other clients. I'm using [Command] functions and everything.

lofty ravine
#

basically how do i add an element to the synclist on a client and have it sync to the other clients and host

sharp axle
lofty ravine
tame slate
#

Clients should be able to send the value they want added to the SyncList through a [Command]

sharp axle
#

The problem you'll run into is when 2 clients try to generate the same chunk at the same time. Unless it's deterministic through a shared seed value, it gonna cause issues

lofty ravine
#

of course at that point the client who generated the new chunk adds it to the synclist

#

(sorry for the ping)

sharp axle
mild shell
#

Hey guys, what are the steps you usually follow for leaving a server or/and shutting it down ? Answers on the internet are bit all over the place.

tame slate
#

Hello everyone, a game that I'm developing currently requires timers that are synced between all clients. I've currently only tried NetworkTransform and NetworkObject; as in literally just adding the component without any changes, since it seems to work with the draggable player object that I added, but none of them have managed to sync up the timers between clients. How can I accomplish this?

trail ibex
#

i dont understand why im getting a memory leak immediately after running my game, before i spawn in any players or anything.

Unity version 2022.3.18f1
Netcode version 1.7.1

tame slate
trail ibex
#

disabling/removing UI elements from the scene or any netwrok objects doesnt do anything either

sharp axle
sharp axle
trail ibex
sharp axle
#

You can go up to 1.13. NGO 2.0 requires unity 6

trail ibex
#

1.13 is newer than 1.7?

#

wait yup

#

i see that now

#

well i tried both, and they both hadnt worked

#

this is so weird, i closed and reopened unity, run it, down to one error, went to enable stakc trace, run it, no errors

#

i do not understand at all whats going on

tame slate
#

Normally I just use "ToString()" in order to convert a float into a string value so that I could put it on text, but for some reason the network variable just turns itself into "Unity.Netcode.NetworkVariable`1[System.Single]"

sharp axle
lofty ferry
#

Hey, can y'all help me as I'm trying to use netcode for game objects but I can never seen to execute it well and I can't find a tutorial good enough

#

It's for a 3d first person multiplayer stratigy game

tame slate
lofty ferry
#

Also can someone explain why prefabs don't like NetworkBehaviour scripts

lofty ferry
#

Will do

mild pawn
#

Hi =)

I'm very new to netcode and might have bitten off more than I can chew at this point.

I worked through code monkeys course on it and my players are synced, which is great. I can't, however, get moving platforms to work.

After a couple days of experimenting, it seems like those are a lot harder in multiplayer compared single player... I gave the Kinematic Character Controller from the asset Store a try and whole that one feels great and handles moving platforms incredibly well, I just can't get it to work in a multiplayer scenario. (in short: I struggle with assigning players characters to owners in particular)
I gave top down engine a look as well, but it seems like that one is limited to local coop.

Can somebody point me in the direction of people who managed to solve this moving platform kind of issue? I think I'm running out of things to keyword search for at this point.

sharp axle
# mild pawn Hi =) I'm very new to netcode and might have bitten off more than I can chew a...

Syncing physics is a very hard problem. With moving platforms, reparenting the player to the platform is the usual strategy. If you aren't using Rigidbodies, then check out this example
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/tree/develop-2.0.0/Examples/CharacterControllerMovingBodies

If you really need to use physics, then you might be able to NetworkRigidbody.FixedJoint

GitHub

Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer. - Unity-T...

mild pawn
#

Thank you! Already gave that a try and struggled, but there's a high chance I just made a ton of mistakes going from rotation to movement. I'll give it another try =)!

#

And glad to hear it's a hard problem oops I have done this in 2D and 3D without issues before, but now that it is Netcode, I feel like I'm running face-first into walls where I don't expect them.

#

.. I only just now see the elevator body in the example... Facepalm I somehow locked in on the Rotation one...

long leaf
#

Okay, I have a strange issue now. I'm building the game to simulate multiplayer with it + unity editor. However, the instance that doesn't open the server and only connects via client has altered rotational movement. Is this a common issue? What could cause it?
It has lowered Yaw, but increased Pitch. Super strange

sharp axle
long leaf
#
 private void Update()
 {
     if (!IsOwner) { return; }

     Vector2 moveActionValue = _moveAction.ReadValue<Vector2>();
     Vector2 lookActionValue = _lookAction.ReadValue<Vector2>();
     _horizontalInput = moveActionValue.x;
     _verticalInput = moveActionValue.y;

     _jump = _jumpAction.IsPressed();

     _isGrounded = _characterController.isGrounded;

     //Debug.Log(lookActionValue);

     if (_hasMoved) 
     { 
     _yawInput = lookActionValue.x;
     _pitchInput = lookActionValue.y;
     _horizontalInput = moveActionValue.x;
     _verticalInput = moveActionValue.y;

         _hasMoved = false;
     }
     else
     {
         _yawInput += lookActionValue.x;
         _pitchInput += lookActionValue.y;
         _horizontalInput += moveActionValue.x;
         _verticalInput += moveActionValue.y;

     }

     if(Time.deltaTime > 0.08)
     {
         Debug.Log("deltaTime was:" + Time.deltaTime);
     }

 }

 private void TimeManagerTickEventHandler()
 {
     if (IsClientInitialized)
     {
         ReplicationData data = new ReplicationData(_horizontalInput, _verticalInput, _isGrounded, _jump, _yawInput, _pitchInput);

         Replicate(data);
         //Debug.Log("Is ovner" + NetworkObject.ObjectId);
     }
     else
     {
        
         //Debug.Log("Isn't owner" + NetworkObject.ObjectId);
         Replicate(default(ReplicationData));
         
     }

 }

 private void TimeManagerPostTickEventHandler()
 {
     CreateReconcile();

 }

 [Replicate]
 private void Replicate(ReplicationData data, ReplicateState state = ReplicateState.Invalid, Channel channel = Channel.Unreliable)
 {
     float tickDelta = (float)TimeManager.TickDelta;

     Vector3 move = new Vector3(data.HorizontalInput, 0, data.VerticalInput);
     move = Vector3.ClampMagnitude(move, 1);

     Vector3 worldspaceMoveInput = transform.TransformVector(move);


     Vector3 desiredVelocity = (worldspaceMoveInput) * movementSpeed;



     _velocity.x = desiredVelocity.x;

     _velocity.z = desiredVelocity.z;

     if (data.IsGrounded)
     {
         _velocity.y = 0.0f;

         if (data.Jump)
         {
             _velocity.y = jumpSpeed;

         }

     }
     else
     {
         _velocity.y += Physics.gravity.y * gravityScale * tickDelta;
     }

     _characterController.Move(_velocity * tickDelta);

     Debug.Log("data.PitchInput:" + "" + data.YawInput + "" + "lookSpeed" + "" + lookSpeed + " for object " + "" + NetworkObject.ObjectId);

     _transform.Rotate(Vector3.up * (data.YawInput * lookSpeed));

     Debug.Log(Vector3.up * (data.YawInput * lookSpeed));

     _pitch -= data.PitchInput * lookSpeed;
     


     _pitch = Mathf.Clamp(_pitch, -80f, 80f);
     _head.transform.localRotation = Quaternion.Euler(_pitch, 0f, 0f);

     _hasMoved = true;



 }



}
#

The problem changes if I modify the TimeManagerTickEventHandler()

  1. i set the if (IsClientInitialized) to if(true) then the movement bug appears. I can demonstrate it if you'd like, but its just that the controlls are not the same for client and host.
  2. if i have an "if else" instead of "else" that doesnt let the client into the else statemnt, movement is fine, but position and movement is not updated on the hosts side
  3. as it is right now with the else it is the same as in 1)
sharp axle
long leaf
#

lookspeed is a constant, 0.1f. TimeManagerTickEventHandler() gets called once per tick

#

its FishNet

sharp axle
# long leaf its FishNet

I'm not familiar with Fishnet, but are you sending raw mouse position for the pitch and yaw input? Isn't that effected by screen resolution?

long leaf
#

its mouse delta

#

the problem is most likely with the Reconciliate or/and Replicate functions

#

We have tested with more than 2 players now

#

its all clients, because the "host" probably has a "isServer" tag, which grants it some sort of exception

#

so all clients have wonky movements, this is probably a fundamental error

nova yoke
#

Is it expected behaviour that adding a [GhostComponent] to a ghost entity in the Server Simulation World at Runtime in an ISystem will not replicate that component to connected clients in the client simulation world?

This is unlike any [GhostComponent] that exists at creation time during the authoring/baking process, which are correctly added and sync to the client.

Is there something behind the scenes I need to do?

Here is a short video showing the issue: https://www.youtube.com/watch?v=mdp6-avfK1g

Bearing in mind I've been working in Unity 6 w/ entities on this side project for just a couple of weeks. But curious about this behaviour!

sharp axle
nova yoke
# sharp axle I don't believe you can add GhostComponents at runtime. They have to be prefabs ...

Most unfortunate... In the event I wanted to influence an entity from the server side that the client needed to represent in some way.. what would be the approach if runtime components can't be synchronized?

Manually writing RPC calls to keep something 'up to date'?

Trying to design things such that the above scenario is never required? (this seems.. difficult)

I guess I would need to have everything added to the prefab and use server side tag components as indicators for server side systems to "act on" and remove those tag components when a given update has been performed maybe?

sharp axle
#

But Enablable Ghost Components are a thing as well

nova yoke
#

yeah.. just "thinking ahead" I can see use cases for both approaches.. maybe this will suffice. thanks for the input

ivory umbra
#

hey there
do you guys know if one needs to pay fusion photon for using they networking package for production even if one hosts the server build themselves?

ivory umbra
#

i couldnt find anything online

spring crane
ivory umbra
spring crane
#

That is the pricing for self hosted builds

ivory umbra
spring crane
#

Every user connects to the cloud even if they end up directly connecting to your server.

ivory umbra
#

why would we connect to their cloud if we dont need them

spring crane
#

It can also act as a relay

spring crane
ivory umbra
#

oh so its enforced?

spring crane
#

Afaik, yes.

ivory umbra
#

but still theres got to be a difference on pricing

#

whether we use their servers or deploy them on our own

spring crane
#

Afaik they don't provide gameplay servers

ivory umbra
#

no way man

#

thats their whole business model

spring crane
#

You can attach plugins to their relays for custom logic, but I don't believe they host Unity server builds.

ivory umbra
merry ravine
#

Hey, is it known how many CCU (in combination with entity culling) the Unity Dedicated Server can currently handle? I was told it only works for 300–500, but I need significantly more—at least 1,000 CCU.

sharp axle
merry ravine
sharp axle
merry ravine
sharp axle
weak plinth
#

when i attempt to get the game object of a network object that i gained using tryGet on a network object reference, the game object returns back as null

#

and i have no clue why

#
    [ServerRpc(RequireOwnership = false)]
    void NewGrabbableObjectOrderServerRpc(NetworkObjectReference grabbableObjectReference, bool isAddingToOrders)
    {
        if (grabbableObjectReference.TryGet(out NetworkObject grabbableObjectNetworkObject))
        {
            GameObject grabbableObject = grabbableObjectNetworkObject.gameObject;
            
            
            if (!isAddingToOrders)
            {
                grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>();
            }
            grabbableObject.GetComponent<GrabbableObjectScript>().allOrders.Add(orderMarker.transform.position + new Vector3(0, grabbableObject.GetComponent<Renderer>().bounds.center.y, 0));
            grabbableObject.GetComponent<GrabbableObjectScript>().sentToLocation.Value = true;
        }
    }
sharp axle
waxen quest
#

So, i have canclled my UGS subscription due to high cost. The free tier is'nt really free. Unity didnt auto stopped relay servers when it reached free tier. Instead i got this warning saying i have to forcefully move to pay plan otherwise services will stop on 26 June. So i technically still got billed.

#

And since unity does not immediately update usage in realtime so we never know if we reached 99% truly so we can stop players from creating allocationms

#

it still exceeding

#

There should be option to either let servers stop until it resets next month or this

tame slate
#

I think I understand the reason why they do it that way, but I agree it is not very user friendly and it's not well communicated

lofty ravine
#

so i'm making a function here for the host to load in a gameobject for all players to see - but when i call networkserver.spawn on the object i get an error on the other clients telling me that the object with netid x has no valid assetid or sceneid - basically telling me that it does not exist.

what i don't understand is why it's doing this when creating the object on these clients is the entire point of networkserver.spawn

here is my code https://pastebin.com/3Dq4KR1c

tame slate
#

You could also just use a [ClientRpc] to make all clients run that same code.

lofty ravine
lofty ravine
tame slate
lofty ravine
tame slate
#

You'd be better off going the prefab route I'd say. Making some generic prefab with a RawImage and then using SyncVars for tag, width, height, etc.

lofty ravine
#

alright, thanks

lofty ravine
lofty ravine
lofty ravine
#

i still can't figure out what it's only spawning my object on the host even when another client is connected

this is my current code that does this https://pastebin.com/Cwbp9NUH

unless i'm misunderstanding what the function does - but it seems pretty clear and says that it will spawn the object on all ready clients.

sharp axle
lofty ravine
#

Honestly, I wouldn't be sending image files in an rpc in any case
this is functionality for user mods

#

i checked in the editor and the object simply just does not exist where it does on the host

#

if it means anything - the prefab is a rect transform image under a canvas environment

sharp axle
#

In Netcode for Gameobjects, this is not allowed

lofty ravine
#

i'm using mirror - i'll try removing the network identity and i'll see what happens

#

and i'll spawn it in the root

tame slate
#

A Network Identity is required to spawn an object at runtime

lofty ravine
#

yeah i just read that

#

i'll keep it

weak plinth
#

which is literally defined as a new NetworkList() upon declaration

lofty ravine
#

thank you!

#

i had to spawn it in the root hierarchy

sharp axle
weak plinth
#

will try that

weak plinth
sharp axle
weak plinth
sharp axle
# weak plinth where?
if (!isAddingToOrders)
            {
                grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>();
            }
weak plinth
#

    if (!isAddingToOrders)
    {
        grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>();
        Debug.Log(grabbableObject.GetComponent<GrabbableObjectScript>().allOrders = new NetworkList<Vector3>());
    }

sharp axle
ivory umbra
#

they only provide some essential services to keep us dependent on them which is also how they keep track of our usage and charge us accordingly

weak plinth
sharp axle
#

How is allOrders declared in the grabbable script?

weak plinth
#

public NetworkList<Vector3> allOrders = new NetworkList<Vector3>();

sharp axle
keen vapor
lofty ravine
#

really weird thing happening to me right now
so if i host a server and another player joins, and i spawn a gameobject while that player is in the server and apply my image texture to it - it looks and works fine.

however if that player leaves and rejoins - my synclist states that the spawned object count is zero and i lose track of the objects that the host has spawned so i can no longer apply the textures and client-size customizations.

if the user was never in the server before and simply joins after the object has been spawned it also works fine the first time - unless they join again

twin grove
#

how to test my own game to display the lobby and enter the lobby on one computer I use FacePunch +netcode 480 appid

trail ibex
#

suspecting this is a networking issue.
Issue: the object is bouncing infinitely (vibrating).

Physics material bounciness is on 0.5
Code only gives a start speed
has network rb, network transform and network object components

hybrid dew
#

How can a client destroy a game object that was instantiated by the host?

tame slate
tame slate
lofty ravine
trail ibex
#

does it having a circular collider have anything to do with this?

#

are there any details i can provide to make arriving at a solution easier?

tame slate
sharp axle
woeful hinge
#

I need a networking programmer to help me out in ym game especially NGE

nova pier
#

how to make server picking random maps in mirror

trail ibex
trail ibex
elfin token
#

Hey yall, I've got a weird bug I am dealing with. So... I have a game... the game has vehicles... All of the vehicles move butter smooth on the client... Except when the client boards a vehicle.....Client moving the vehicle is jittery AF.... The NPCs and clients use the exact same code to move the vehicle.... The server moves all vehicles in fixed update....When clients board, they request ownership of the vehicle.... I thought that may be the issue; however, the problem is there with or without the client owning the vehicle... Has anyone encountered this?

trail ibex
wind shoal
sharp axle
sharp axle
trail ibex
#

but if not, then what is the issue? or do i take that to a different channel

sharp axle
barren lark
#

I am not sure how to describe this as I am pretty new to multiplayer/networking, but I notice a strange thing happening with Netcode for gameobjects and specifically the network transform/rigidbody, when pushing the other player on the host player (LEFT), it seems to apply the correct force (with enough distance), but then moves the player back to a closer spot slowly (which is also the spot on the client, but it is suposed to be further acording to the force), The correct position should be where it initially gets pushed to before moving back. But on the other player (client) it seems to work fine when pushing the host player (except maybe some interpolation needed on the other machine to make it look smooth). Does anyone have any ideas on where to look for what could be causing the host to move the Client to the wrong position? Also if helpfull, this is my current code: ```cs
private void OnCollisionEnter(Collision collision)
{
if (!IsServer) return;

    var other = collision.gameObject.GetComponent<PlayerController>();
    if (other == null) return;

    float myScale = _netScale.Value;
    float otherScale = other._netScale.Value;

    Vector3 directionToOther = (other.transform.position - transform.position).normalized;
    Vector3 directionToMe = -directionToOther;

    if (myScale > otherScale * 1.1f)
    {
        Debug.Log($"I am bigger. Knocking back {other.OwnerClientId}");
        Vector3 force = (directionToOther + Vector3.up * 0.5f) * _knockbackStrength * myScale;

        // Server applies knockback to authoritative object
        other.ApplyKnockback(force);

        // Tell client to apply knockback too
        other.ApplyKnockbackClientRpc(force);
    }
    else if (otherScale > myScale * 1.1f)
    {
        Debug.Log($"They are bigger. Knocking back me.");
        Vector3 force = (directionToMe + Vector3.up * 0.5f) * _knockbackStrength * otherScale;

        ApplyKnockback(force);
        ApplyKnockbackClientRpc(force);
    }
}

public void ApplyKnockback(Vector3 force)
{
    Debug.Log($"[ApplyKnockback] Player {OwnerClientId} applying force {force}");
        Vector3 cleanedForce = new Vector3(force.x, .25f, force.z); // Ensure no downward force
        _rb.AddForce(cleanedForce, ForceMode.VelocityChange);
}

[ClientRpc]
public void ApplyKnockbackClientRpc(Vector3 force)
{
    // Only apply locally if this is our object
    if (IsOwner)
    {
        Debug.Log($"[ClientRpc] Player {OwnerClientId} applying force {force}");
        Vector3 cleanedForce = new Vector3(force.x, .25f, force.z); // Ensure no downward force
        _rb.AddForce(cleanedForce, ForceMode.VelocityChange);
    }
}
tame slate
sharp axle
barren lark
# tame slate Looks like you’re applying the force twice. If you’re using Network Transforms a...

Yes you are right thanks, I now changed the logic to make the server tell which client should apply forces, after that it automatically updates the transform with network transform. One small issue still, how would I make it less "instant", currently it sort of looks like the other player gets teleported when hit. Could I make it actually fly away? my current code: ```cs
private void OnCollisionEnter(Collision collision)
{
if (!IsServer) return;
var other = collision.gameObject.GetComponent<PlayerController>();
if (other == null) return;

    float myScale = _netScale.Value;
    float otherScale = other._netScale.Value;
    Vector3 directionToOther = (other.transform.position - transform.position).normalized;
    Vector3 directionToMe = -directionToOther;

    if (myScale > otherScale * 1.1f)
    {
        Debug.Log($"I am bigger. Knocking back {other.OwnerClientId}");
        Vector3 force = directionToOther * _knockbackStrength * myScale;
        // Use RPC to tell the client to apply the force (if client-owned)
        other.ApplyKnockbackClientRpc(force);
    }
    else if (otherScale > myScale * 1.1f)
    {
        Debug.Log($"They are bigger. Knocking back me.");
        Vector3 force = directionToMe * _knockbackStrength * otherScale;
        ApplyKnockbackClientRpc(force);
    }
}

[ClientRpc]
public void ApplyKnockbackClientRpc(Vector3 force)
{
    // Only the owner should modify their rigidbody
    if (IsOwner)
    {
        Debug.Log($"[ClientRpc] Player {OwnerClientId} applying force {force}");
        Vector3 cleanedForce = new Vector3(force.x, .5f, force.z);
        _rb.AddForce(cleanedForce, ForceMode.Impulse);
    }
}
tame slate
barren lark
#

Ok I will give that a try thanks

hybrid dew
#

I am spawning enemies only on server/host
player1 starts the game, clicks start host, set itself in a Manager as a reference being the host player and enemies start spawning, take the reference from the Manager, and start following this reference on update

I let this run for a minute and it's fine
but when player2 joins as a client, for some reason it throws an exception on player2 console that the script EnemyFollowPlayer has a null reference of target player to follow
even though the enemies are set to only set to spawn on the server

any idea what's going on? please note this suddenly starting happening today it was running fine before

sharp axle
hybrid dew
tame slate
sharp axle
hybrid dew
# tame slate Kind of just sounds like clients shouldn't be running that code at all

they don't
the part where enemies spawn and are told to follow the host player is wrapped in if(IsServer)
but for some reason when the client join, he starts throwing exceptions that the EnemyFollowPlayer script has a null value of hostPlayer

//in SpawnManager.cs
void Update()
{
    if (!canStartSpawning || !IsServer) return;

    timer += Time.deltaTime;
    if (timer >= spawnRate)
    {
        SpawnInCircle2(GameManager.instance.GetPlayer().transform.position, _radius, 1, objectToSpawn);
        timer = 0f;
    }

}

 public void SpawnInCircle2(Vector2 center, float radius, int count, GameObject prefab)
 {
     Debug.Log("Spawn neemy called");
     float x = Random.Range(center.x - _radius, center.x + _radius);
     float y = Random.Range(center.y - _radius, center.y + _radius);

     Vector2 randomPosition = new Vector2(x, y);

     GameObject _enemy = Instantiate(prefab, randomPosition, Quaternion.identity);
     _enemy.GetComponent<NetworkObject>().Spawn();

 }


//in PlayerController.cs
public override void OnNetworkSpawn()
{
    base.OnNetworkSpawn();
    spawnManager = GameManager.instance.GetSpawnManager();
    Debug.Log($"Is server in player controller inside OnNetworkSpawn: {IsServer}");
    if (IsServer) GameManager.instance.SetPlayer(this);

    if (IsOwner)
    {
        _camera = Instantiate(CameraPrefab);
        _camera.GetComponent<FollowPlayer>().Init(gameObject);

        spawnManager.StartSpawning();
    }
}

//and finally we call this on trigger of OnClientConnectedCallback from NetworkManager
void HandleClientConnected(ulong clientId)
{
    if (!IsServer) return;

    // Prevent double spawn
    if (NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject != null)
        return;

    GameObject player = Instantiate(playerPrefab);
    player.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
    if (hostPlayer != null) hostPlayer = player;
}



#
//and start spawning is guarded with IsServer
public void StartSpawning()
{
    Debug.Log("Start spawning called");
    if(IsServer) canStartSpawning = true;
}
tame slate
sharp axle
#

Yea. if its a scene object, Update will get called a few times before the network connects

twin grove
#

 public void LeaveLobby()
        {
            if (currentLobby.HasValue)
            {
                var lobby = currentLobby.Value;
                lobby.Leave();
                currentLobby = null;
            }
            
            LobbyManager.Instance?.LeaveLobby();

            if (LobbyCreationUI.Instance != null)
            {
                LobbyCreationUI.Instance.ResetCreationUI();
            }

            if (NetworkManager.Singleton == null) return;
    
            NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnected;
            NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnected;
            NetworkManager.Singleton.Shutdown(true);
        }```
#

Player left the lobby, how do you update slots with the host?

modest elk
#

What solution could we use if we want 2 people to play together around the world in a coop game. The closest example game to describe it would be portal 2's coop mode.

tame slate
modest elk
#

(and what do you personally like?)

tame slate
modest elk
tame slate
#

I would probably choose NGO for the game you were described if it was my choice.

#

Oh yes, forgot about FishNet. Commonly used as well.

modest elk
#

Thank you very much i'll check a few examples of these

#

its a rather laidback game dont need stuff like valorant for anticheat etc..
just need the ease of starting a game with your friend and interactions like seeing eachother, walking around, triggering stuff etc etc

#

I guess I can do the "join code" thing with NGO as well like I saw it in Photon Quantum.. Just not sure about payment 🤔

sharp axle
nimble crow
#

Can entities which do NOT have the same archetype have shared component values?

slow geyser
#

Ok. I'm learning netcode and so far I'm extremely confused. It looks like a single server corresponds to a single game session. Like, I'm running a server, it starts a scene and all my clients are connecting to that scene, and I can't separate them into multiple sessions. Is this the intended way? I have to run multiple servers if I want to run multiple sessions? Then how do I make a lobby, matchmaking, etc?

tame slate
#

Lobbies and matchmaking generally happen before and outside of an actual game session.

#

Ones that happen in game are more complicated as they're going to have to direct you between different servers/game sessions.

sharp axle
long leaf
#

Hi, I'm trying to learn to code for multiplayer. I've tried out fishnet for a bit, but honestly. What's the difference between using Fish-Net, Mirror and NGO?

#

Fish-Net has poor documentation (imo), barely any tutorials online, and no one responds in their dc for days

#

Isn't every Networking solution build upon the same base? Would you not be able to achieve similar results with all solutions?

tame slate
sharp axle
long leaf
#

What do you guys prefere using?

#

All I really want is being able to connect some clients (<10) together and having it be somewhat secure

#

But without "a lot" of desync, which I'm experiencing now

sharp axle
#

NGO makes things really easy to start

#

But you will always have to deal with Latency and Lag at some point

long leaf
#

How do multiplayer games deal with that? I know rust, and tarkov, is built with Unity

tame slate
#

Yeah. Desync and latency are two different things.

tame slate
long leaf
#

Yeah, of course

#

But if they're built in unity, don't they have the same resources as I do?

#

just that they utilize it way better

sharp axle
#

I think you'll find that most games use a custom network solution specific to the game

real igloo
tame slate
#

There are a lot of ways to reduce the effect of latency on player experience, it's kind of a hard question to answer in a general sense.

sharp axle
long leaf
#

I just want to know what I can do, not how to do it

#

I'm pretty new, so a lot of issues arise because I don't even know how or where to start searching

sharp axle
long leaf
#

this documentation is more extensive than fishnets thats for sure

tame slate
#

You'd be best starting off small, and just researching how to tackle the problems you're facing as you go

long leaf
#

Will do, but will def save a ss of what you wrote for later

long leaf
#

Okay so I'm watching some tutorials and learning about NGO. So I understand that there is Server-auth movement, and also Client-auth movement. I want a "competetive" game. Therefore both choices come with drawbacks, i.e Server-auth gives latency, and Client-auth makes it exploitable. I have an idea, however, that I was wondering about. What if I do both? Say a client presses W. It both moves and sends it to server, which simulates what would happen, if the client's position etc matches with what the inputs say then nothing happens; client movement feels somther. If the inputs don't match what happened, the server intervenes.

sharp axle
grizzled peak
long leaf
#

fr? thats good then, no? cause people have done it before

#

F-student moment

rugged spire
#

Hi. for this. How many users can a single user create? is it one only? or he can create many? and if the player closed the game. will he be signed out?

long leaf
#

(the people I've watched haven't mentioned client-prediction, mbmb)

grizzled peak
sharp axle
long leaf
rugged spire
rugged spire
# sharp axle Sure

Great. for my other questions. will users be signed out when they close the game?

sharp axle
rugged spire
long leaf
#

I don't really understnad what "default physics" is refering to"

sharp axle
tame slate
# long leaf Why is it hard to get right?

Your predictions have to be pinpoint accurate. Even the smallest of mispredictions results in large amounts of desync over time.

It also technically requires rollback which means storing a history and being able to rollback to points in that history. Depending on how many things you're predicting, this can get more and more complicated.

sharp axle
#

There is also a Unity Physics and Havoc for DOTS

long leaf
#

yeah I can see why it's difficult, but I'm guessing client-prediction feels a lot better than just running server-auth

sharp axle
#

in general, yes. but also depends on your game. A card game is not gonna matter as much

long leaf
#

yeah, but if you imagine something similar to Mordhau, that's the kind of game I'm trying to build

tame slate
long leaf
#

whats the difference between prediction / anticipation

tame slate
#

It's discussed briefly at the top of this page

sharp axle
#

Client anticipation in NGO doesn't take physics into account and generally is only for individual objects/variables

twin grove
#

When a player leaves the lobby, for some reason the data slots are not updated why so?

sharp axle
sharp axle
valid willow
#

What are some ways to reduce latency issues in a VR collectathon game using DA? We started playtesting and the experience when players connect from different countries is sub-par, the delay when collecting objects is very annoying. I’m finding difficulties on how to do prediction as I can’t rely on player input due to each player being a rigidbody (our locomotion method is players flinging themselves with their arm movement, flying essentially). Would appreciate any tips or articles

tame slate
#

Also you shouldn't have to mess with any sort of prediction for player movement in DA as the movement would be client authoritative.

valid willow
# tame slate Can you describe the collection mechanics further?

Essentially you fly around with a set of players in a level and collect objects, demo here (imagine sonic rings). The difference between regular collectathon games I suppose is that the players are flying about really, really fast.

Now the issue issue is confirming collect actions and making sure these actions occur fast. Otherwise, you collect an object and there is a very noticeable delay in FX and similar, to the players it seems like they're missing objects some in cases.

When collecting objects I send a "request" to the owner of the object to confirm if an object can be collected, once confirmed I send back a "response" which updates score, triggers VFX & SFX locally. This is done to avoid race conditions during scoring, I thought about collecting objects immediately locally, but I can't think of a good way to "revert" collect events without messing with UX.

The player object itself is simulated on all clients and is able to trigger collect "requests" on all of them (it has a trigger that collects stuff and the same "request/response" logic), but the issue is that its always way far behind from the owner position-wise, so it doesn't solve the lag issue. The player objects are client authorative and are replicated using ClientNetworkTransform + NetworkRigidbody. Also, the collectable objects can also move due to powerup metchanics (players act as magnets), these are also synced using ClientNetworkTransform. The reason why I mention prediction, is that I'm thinking I could "move ahead" the replicated clients so that the collect action triggers sooner on the owner of the collectable (keep in mind that collectables are distributed between all players in the session).

I'm also thinking maybe DA is not the right choice for this type of game 🤔

tame slate
#

DA is most likely not a good choice for this unfortunately.

#

Too fast paced.

#

Something you could do for collectables is make your best attempt to keep switching the owner to the closest player so the majority of the time no request has to be sent.

#

Still wouldn't solve all issues though - so I'd say client-server is pretty much needed unless you sacrifice on the pacing of the game quite a bit.

delicate parrot
#

Does anyone know if autoproperties can work with networkvariables?

eg. [field: SerializeField] NetworkVariable<int> myNetworkedInt {get; private set;} = new NetworkVariable<int>

or no luck

tame slate
#
private NetworkVariable<int> _myNetworkedInt = new NetworkVariable<int>();

public int MyNetworkedInt => _myNetworkedInt.Value;

or something similar should work

delicate parrot
#

Was curious about doing it directly

tame slate
#

Probably not - most serialization systems don't allow for it

rugged spire
#

the door animation is not syncing when a client plays it. I did override the network animation

#

the player animation is syncing well. but the door animation isn't

#

this is the script that plays the animation. ani is refrencing the Animator

sharp axle
sharp axle
rugged spire
sharp axle
rugged spire
sharp axle
valid willow
rugged spire
sharp axle
sharp axle
rugged spire
sharp axle
rugged spire
rugged spire
#

I have no idea what is it. but the game works fine

tulip egret
#

if the gameObject is inactive in the scene to which the above Script(CreateLobbySettings) is applied. and i am running this function in another script with different gameObject which is active. Will the function still work ? As it is not updating the lobby list in my scene, i thought there might be a problem.

#

OK. Fixed it by attaching script to an active gameobject. ✅

long leaf
#

I'm working with NGO, I'm connecting 2 players, 1 host, 1 client. But what is weird is that there is a "remnant" hitbox where both player-instances started (when both connected). And the two players dont actually have hitboxes that collide with each other. I'm using a CC as well

tulip egret
#

Can anyone tell what is the issue here

#
    private void StopClient()
    {
        if (NetworkManager.Singleton == null)
            return;

        if (NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsHost)
        {
            RequestDespawnServerRpc(NetworkManager.Singleton.LocalClientId);
        }
    }
    private System.Collections.IEnumerator LoadLobbyAfterShutdown()
    {
        yield return new WaitForEndOfFrame();                                              // LET COMPLETE SHUTDOWN
    }
    [ServerRpc(RequireOwnership = false)]
    private void RequestDespawnServerRpc(ulong clientId)
    {
        foreach (var obj in NetworkManager.Singleton.SpawnManager.GetPlayerNetworkObjects(clientId))
        {
            obj.Despawn(true);
        }
        NotifyClientDespawnedRpc(clientId);
    }
    [ClientRpc]
    private void NotifyClientDespawnedRpc(ulong clientId)
    {
        if (clientId == NetworkManager.Singleton.LocalClientId)
        {
            StartCoroutine(FinishShutdown());
        }
    }
    private IEnumerator FinishShutdown()
    {
        yield return new WaitForSeconds(0.2f);
        NetworkManager.Singleton.Shutdown();
        StartCoroutine(LoadLobbyAfterShutdown());
    }

This code for disconnecting client. Is there any error here ?

#

How can i fix it

sharp axle
sharp axle
tulip egret
#

Ok.

long leaf
sharp axle
long leaf
#

I tried to write " characterController = gameObject.AddComponent<CharacterController>();" inside of the character controller and now the player spawns at y = 0 and then gets swapped to some other

#

But they sitll do not have hitboxes

sharp axle
carmine geyser
#

Hello! Would it be possible to invoke an RPC method event if the user is offline (aka not connected to any server, not even itself)? Right now, if I go into offline mode and try to call this method, nothing happens, I would like it to run if not connected.

    void DoSomethingRpc()
    {
        Debug.Log("Do Something");
    }```
rugged spire
#

When I pair netcode for gameobjects with lobby and relay. Where the player prefab gets spawned the moment he join the game. Which scenario should I implement?
1- Main menu and game in a single scene. Handling lobby, relay and connection
2- Main menu and game in separated scenes. Where main menu handles lobby and relay data and then load the game scene. Through a playerPrefs I know if I startHost() or startClient()
3- another approach not mentioned?

#

I don't want the lobby to get destroyed unless the host leaves. I want to allow players to join mid game

sharp axle
sharp axle
exotic geode
#

We just put our demo out, and for the most part things are going well. But we have some lobby/connection/NetworkManager bugs that we need to sort out asap.

Are we allowed to hire and recruit contract work here? We’re looking for a veteran with experience, someone who knows exactly what they are doing and have shipped live games using Netcode for GameObjects, Relay, and Lobby.

raw stormBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

robust wave
#

I'm trying to make a physics based box that you can push around, but only the host can move it, clients just run into it. i have a network object, network transform, and network rigidbody on both the player prefab and the box prefab. Anyone know how i can get the clients to be able to push it?

sharp axle
robust wave
sharp axle
robust wave
#

@sharp axle is there not a way for multiple clients to own the same network object? all players need to be able to push around the boxes

#

or maybe i could change the ownership to whatever player hits it right when they collide?

sharp axle
robust wave
sharp axle
robust wave
#

oh i see

long leaf
#

why does the "authority mode" default to "server"? Nothing seems to work when its on that mode instead of "Owner". Does that mean I'm doing something wrong, or does this have do with client- vs server-auth movement?

long leaf
#

If I have the CC disabled, then enable it. The hitbox tps to where the clone was standing when enabled, however, this hitbox doesnt move with the charcter

#

The CC, network-object script and the transform is all on the same root, which is parent to all the player objects (for 1 player)

tame slate
sharp axle
sharp axle
long leaf
#

this is how I move the char

#

it is using cc.move

#

this makes no sense to me. There is an invisible hitbox that I can't move through right infront of the selected capsule

long leaf
#

I feel so incredibly lost it actually hurts

tame slate
#

tl;dr - you should be checking IsOwner in OnNetworkSpawn and before your movement code, so that only the authority is driving the movement and syncing it to all others

long leaf
#

is this not enough?

tame slate
sharp axle
#

The non local player objects will need their character controllers disabled so the network transform can sync their positions

long leaf
#

I assume theres more that I'm missing

sharp axle
#

you can have a separate collider if needed.

long leaf
#

If I'm getting this right, its about server vs client auth movement. In both cases you need to disable the cc-component of other clients (please tell me this isn't wrong). Client-auth: clients CC needs to be enabled for the specific client, disabled for other. This way, he moves directly through recorded input through the CC. For server-auth it's a bit more confusing to me. You disable the clients CC and make the server listen to the inputs and move the player through Network transform.

#

This line in the article linked by Dylarno, is hard to understand "Enable the CharacterController on the server instance and disable it on the client instance(s)."

#

Does this mean that the server has "copies" of the players which has cc's that are enabled and that is simulated. Then that movement is applied to the actual client?

tame slate
#

The server runs the application just like the clients do. Server authority is not much different from Owner authority in your current case. CC enabled on the authority, disabled on all others.

#

The only difference is that with Owner/Client authority, you can perform the movement locally and immediately. With Server authority, the client has to send a message to the server who is the authority, sending information on how to move the object for the server to perform.

long leaf
#

If I want "the server to drive the CC" (assuming this is equiv. to server-auth movement). What would that set up look like? Would you have a manager-script that existed in the world that read a players input and moved them?

tame slate
# long leaf If I want "the server to drive the CC" (assuming this is equiv. to server-auth m...

a very barebones example of a client requesting movement to be performed on a transform with server authority

void Update()
{
    Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
    if (input != Vector2.zero)
    {
        MoveServerRpc(input);
    }
}

[ServerRpc]
void MoveServerRpc(Vector2 input)
{
    Vector3 movement = new Vector3(input.x, 0, input.y) * Time.deltaTime;
    transform.position += movement;
}
long leaf
#

😮 wow, thanks for writing that out. So the Server exists within the player script?

#

Or is it meant as in: the two methods are in different scripts

sharp axle
#

RPCs are sent to the server

long leaf
#

wait. No yeah im stupid, sorry

#

[ServerRPC] Means that the client is sending a RPC to the server

tame slate
#

Just like I mentioned above, it runs the same as the clients do unless told otherwise. This is what the IsOwner, IsClient, IsServer flags are for, as well as the [Rpc] attributes, to send specific messages to specific connections.

long leaf
#

Well, shit. Thanks for helping me. Understand if it feels frustrating trying to, essentially, explain calculus to a toddler. I'm going to bed and then reading a lot of doc tomorrow, hopefully understanding some of this better

meager lynx
#

Hey everyone, so I have script A being the one with the singleton, and it has a method MethodA. The Instance is set upon Awake.

Script B contains a Start method where I attempt to call script A's methodA. Why is scriptA's Instance null?

wild mortar
#

https://www.ghostbin.cloud/soo55 hi this is my first time with multiplayer. i was wondering why the player cant see the bullet come out of the gun? but the host can still see the bullets after the client clicks, the bullets just dont show for the client. any help appreciated, thank you!

tame slate
wild mortar
tulip egret
#

Can someone tell why this error comes, when i call NetworkManager.Singleton.Shutdown() on a client.

sharp axle
sharp axle
sharp axle
tulip egret
wild mortar
tame slate
#

I see there's a return in your ShootGunServerRpc which could be unintentionally getting called

wild mortar
#

lemme check rn

wild mortar
#

even removing the return, though, still doesn't work

sharp axle
wild mortar
#

yea it has a networkobject component

tame slate
# wild mortar yea it has a networkobject component

Have you tried storing bullet as a GameObject? This is the example of how to spawn things in the docs

var instance = Instantiate(myPrefab);
var instanceNetworkObject = instance.GetComponent<NetworkObject>();
instanceNetworkObject.Spawn();
sharp axle
#

I think you need to explicitly type NetworkObject for Instantiate()

wild mortar
#

lemme try

#

client still cant see bullets spawning

sharp axle
#

That's odd. Are you using GetComponent<NetworkObject>()?

wild mortar
#

yes

sharp axle
#

You could also try using InstantiateAndSpawn()

wild mortar
#

okl ill try

#

wait what do i pass for parameter tho

sharp axle
# wild mortar yes

If NetworkObject.Spawn() isn't getting called then something else is wrong

wild mortar
#

oh

#

i put a debug at end of method and its not getting called

delicate parrot
#

No longer relevant advice for this one but in the future another thing to check is if the thing running that code is correctly spawned too

wild mortar
#

good point

#

its on my player tho

#

which has network transform and object and stuff, and both can see each other so it should be fine

tame slate
wild mortar
#

i can check again

#

yep no error

tame slate
wild mortar
#
var bulletClone = Instantiate(bullet);

        bulletClone.transform.position = bulletSpawnPos.position;
        bulletClone.transform.rotation = cam.transform.rotation;
        bulletClone.GetComponent<Rigidbody>().AddForce(cam.transform.forward * bulletSpeed, ForceMode.Impulse);
        bulletClone.GetComponent<NetworkObject>().Spawn();
#

i did this

#

i got networkcomponent and spawn

delicate parrot
#

heads up regardless

#

The add force you do is potentially wrong

#

Since that line of code won’t fire on the clients spawned bullets

wild mortar
#

oh really

#

why

#

oh do i need to use networkrigidbody

sharp axle
#

If it has a network transform then it should be fine

wild mortar
#

ye it has network transforrm

sharp axle
#

You might need to attach a debugger to see where in the RPC it stops executing

delicate parrot
#

Basically NGO has a big list of networkobject prefabs and when you do .Spawn() that just finds the list index of that prefab, and tells the clients to spawn the prefab at that index.

If you have a network transform your fortunately fine here but any code run on the instanced prefab from the host like that won’t inherently sync with the clients one

sharp axle
#

as long as the prefab has an active network object there is no reason it won't spawn

sharp axle
tame slate
#

The other thing to try is just spinning up another NetworkBehaviour script and another Network Prefab and seeing if you can get that to spawn

sharp axle
wild mortar
#

o i see it

#

i clicked it

tame slate
#

I've seen NGO mix things up under the hood in editor before, and sometimes remaking scripts or prefabs from scratch can fix problems like this

sharp axle
delicate parrot
wild mortar
#

ok added one

tame slate
wild mortar
sharp axle
wild mortar
#

but the debugger didnt do anything

#

it didnt do anything when the client was in the inspector though

#

it worked when host was in inspector

timid viper
#

I'm on the Unity 6.2 beta and I'm having quite a few issues with Netcode for GameObjects. My scene is very simple, it simply has a NetworkManager which I've left purely on the default settings. I have a button which calles NetworkManager.StartServer() and another button which calls NetworkManager.StartClient(). After the connections finish, another scene is loaded. In that scene, I have the following extremely simple component on the same GameObject as the NetworkManager:

    private NetworkManager _networkManager;

    public void Start()
    {
        _networkManager = GameObject.FindFirstObjectByType<NetworkManager>();
        Debug.Log($"Is server: {_networkManager.IsServer}");
        if (_networkManager.IsServer)
        {
            _networkManager.OnClientConnectedCallback += ClientConnected;
        }
    }

    private void ClientConnected(ulong id)
    {
       
        Debug.Log($"Client connected {id}");
        TestRpc();
    }

    [Rpc(SendTo.NotServer)]
    public void TestRpc(RpcParams param = default)
    {
        if (_networkManager.IsServer)
        {
            Debug.Log("SERVER Test");
        }
        else
        {
            Debug.Log("CLIENT Test");
        }
    }

The server is correctly logging "Is server: True" and the client is correctly logging "Is server: False", but TestRpc is only ever getting executed on the server despite the fact that it's marked SendTo.NotServer. I tried to debug this by using SendTo.SpecifiedInParams and then calling
TestRpc(RpcTarget.Single(id, RpcTargetUse.Temp)); but when I do that, I'm getting Cannot access non-static method 'Single' in static context as a compile time error.

This is a fresh project, this is literally the only code that exists in it. I'm just trying to play with Unity's RPC to compare to Godot RPC.

sharp axle
timid viper
sharp axle
#

IsServer won't be properly set because its doesn't know if its a server by then

timid viper
sharp axle
#

If its in a new scene that might be OK then. But i believe OnClientConnected is too early to call a RPC. is should be done in or after OnNetworkSpawn()

timid viper
# sharp axle If its in a new scene that might be OK then. But i believe OnClientConnected is ...

I can pretty much confirm this isn't the issue. Before I stripped this code down to its basics, the server was running a coroutine which called an RPC to the client every 5 seconds for a minute. None of those RPCs got called on the client, they all got called on the server, again despite the RpcTarget.NotServer attribute. I stripped the code down to its basics to be able to come explain it more simply here.

tame slate
#

They won’t work properly unless they’re in one.

long leaf
#

Can anyone explain this? This is a barebones setup with a script that checks if (!IsOwner), then lets the player move the capsule with some basic code. What's weird is that if I change a variable in the inspector (even to the already existing value), the capsule stops responding to inputs. Can confirm inputs are not even going through from Debugging. But am still Owner of the script

timid viper
tame slate
timid viper
tame slate
timid viper
tame slate
timid viper
# tame slate NetworkObjects in the scene hierarchy should spawn automatically and be able to ...

I would think so too, but that doesn't seem to be the case. I've noticed that when my Server starts up, the NetworkObject which is trying to do the RPC calls has a "Spawn" button on it instead of the normal info, which leads me to believe it's not spawning properly. When I click that button, the client then throws an error saying it couldn't spawn the NetworkObject. Which is weird because even after it throws that error, the server then shows that the client has registered as an observer.

#

I think I'm just going to wipe all this out and go back to tutorial land. It's been a bit.

#

Thanks for your help folks

sharp axle
timid viper
# sharp axle If you are switching scenes then you have to make sure you are using network man...

I redid the whole thing from scratch this morning and I got to a working product thanks to your and @tame slate 's help.

The keys were:

  • Changing scenes with networkmanager's scenemanager
  • not having any network objects in the same scene as the networkmanager and instead deferring adding those to the hierarchy until after the networkmanager had been connected
  • Doing setup stuff in OnNetworkSpawn instead of on Start
  • I have no idea what fixed RpcTarget.Single, it just mysteriously works this morning in the exact same context I was using it yesterday
keen hatch
#

honestly ngo is not as hard as i thought as long as you know basic network conecepts its easy to get into

#

all requires minimal code

long leaf
# sharp axle If you are switching scenes then you have to make sure you are using network man...

sorry for late reply, hda to go to bed (3am)

using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerNetwork : NetworkBehaviour
{


    [SerializeField]
    private float mvmtSpeed = 10f;

    [SerializeField]
    private InputActionMap playerActionMap;

    private InputAction moveInput;




    public override void OnNetworkSpawn()
    {
        if (!IsOwner)
        {
            Debug.Log("WAS");
            enabled = false;
            return;
        }
    }

    private void Start()
    {
        

        playerActionMap = InputSystem.actions.FindActionMap("Player", true);
        moveInput = playerActionMap.FindAction("Move", true);
    }
    void Update()
    {
        Move();

        
    }


    private void Move()
    {

        Vector2 readMoveInput = moveInput.ReadValue<Vector2>();
        float moveX = readMoveInput.x;
        float moveY = readMoveInput.y;

        Vector3 moveVector = new Vector3 (moveX , 0, moveY);
        moveVector.Normalize();


        transform.position += moveVector * mvmtSpeed * Time.deltaTime;

        Debug.Log(readMoveInput);


    }

}

#

I tried debugging by Loging the MoveInput values, after I edit a variabel in the inspector related to this very script, the MoveInput values (Vector2) is (0 , 0)

#

Its any [SerializedField] Variabel actually. I just put another one in the script that doesn't even get used for anything. If I change it, inputs stop being read. I tried changing other properties of the object (i.e its transform) and that didn't ruin anything

long leaf
#

Okay, I found the problem. With some help from GPT I found out that I CAN NOT, and I repeat, CAN NOT [SerializeField] on the InputActionMap

#

Removing this completely solved it. Why? GPT tells me its because of something called "Domain reloads", is that correct?

hybrid dew
#

Do you need to wrap Rpcs with if(IsServer)
or does it automatically run on the server only?

sharp axle
long leaf
#

Yeah, sure you dont think so. But I like seeing what goes where and what values everything has.

sharp axle
sharp axle
long leaf
#

hm, didn't know that was a thing

sharp axle
#

3 dot menu next to the lock

long leaf
#

thanks! thats really usefull

wild mortar
sharp axle
# wild mortar whats the difference betwwen that and [ServerRpc]

[RPC] is the newer version. it does the same thing but is more flexible

Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...

wild mortar
#

o ok

#

thx

shadow wagon
#

Hey, um... I wanna make a LAN game, and I know Unity can be kinda tricky with multithreading. So I was wondering if you guys know any libraries or something that already handles the connections? Like, I just wanna manage the packets myself, from reading them to serializing them to send. You know, a library that takes care of the basic stuff

fluid walrus
muted sorrel
#

I saw that there were these buttons as well for hosting but I wanted to go trough the lobby (well I could remake everything but I just wanted to try out the existing Unity options first) @spring crane

#

This function only gets called when I use these buttons but not when I use the provided Unity Widget UI

muted sorrel
#

Sorry, thank you for the link !

spring crane
muted sorrel
#

I'm mostly familiar with traditional Client/Server stuff but not the whole setup in Unity

#

If needed then I'll just go trough a bunch of tutorials but I thought that the widget would at least ease the whole process since it's provided with the Multiplayer Center

sharp axle
muted sorrel
#

Yeah I see

sharp axle
muted sorrel
#

Got it, thank you !

rugged spire
#

What does this error means?
It happened when I tried executing this function

fluid walrus
rugged spire
#

if you are talking about PCID. each one has a unique PCID from 0 to 7 (lobby has a max of 8 players)

#

and on start the player with localClientID will have OwnerShip of the object with the same PCID

#

all of it's data stored on PlayerPrefs

#

So when trying to access one which is not yours. you should get the data from the owner's playerPrefs

#

when I open mine it works fine. but when opening someone's else I get the error

fluid walrus
#

if you add/remove components dynamically anywhere, it can mess things up

rugged spire
#

I don't add or remove components during runtime

#

so they are the same

sharp axle
rugged spire
#

how does the system work? there are 8 pcs each with id from 0 to 7. and they are disabled until a player join and have the same id as one of them. then they are enabled. the player prefab is instantiated once he joins the game (host or client)

sharp axle
rugged spire
#

and when he joins he sends an rpc to update the isOpen for all clients

#

it is not when he joins instantly. it is when he do certain action

#

to be exact. when a player do a certain action. his NetworkManager.Sinlgeton.localClientId is used to change the value of isOpen in PCScript that match the same PCID

#

So I'm pretty sure it is executed after the network spawn

sharp axle
rugged spire
#

the SetPcStatus is called by an rpc function. Rpc(SendTo.ClientsAndHosts)
while the SetPcStatusAnimation is called by the owner

#

Since the animation is a network animation. it is automatically synced

#

The FileSystem is a MonoBehaviour

sharp axle
rugged spire
#

It is in the scene and part of the map. It is not a network object

#

Does the parent have to be a network object?

sharp axle
rugged spire
#

Or do I have to add it to the room parent too?

sharp axle
#

Not if it's a child object. Network object parenting is rather complicated

#

Only the root object should have the network object

rugged spire
#

Wait a moment. I guess I forgot to add the network object to the pc

#

I will check later. Thanks for he help

rugged spire
#

I found the reason and fixed it

halcyon girder
#

Does view.IsMine work right with how im making these 3 scripts? Sorry if I make a dumb mistake I'm trying to get into networking haha! FirstPersonMovement.cs: https://hastebin.com/share/itokeqahuf.csharp Jump.cs: https://hastebin.com/share/iceqafijiv.csharp Crouch.cs: https://hastebin.com/share/gagoloboce.csharp

sharp axle
halcyon girder
#

Hey! Thanks for the help, is there going to be a performance issue with it being 3 different files?

sharp axle
halcyon girder
tame slate
twin stone
#

how hard would it be to make peer to peer multiplayer in unity? i looked into it with ue5 and it would be kind of hack work to make it function

tame slate
wild mortar
#

https://www.ghostbin.cloud/sukr0 hello i have a problem where when the player shoots it does not shoot the right direction. i am using a raycast but it doesnt seem like the bullet is actually going the right direction

wild mortar
tame slate
#

Like it's not completely wrong?

wild mortar
#

it is pretty close but still somewhat to the right

tame slate
#

I'm guessing you're just experiencing the effects of latency. By the time the server receives the message to shoot the gun, the client can already be looking somewhere else.

wild mortar
#

ah

#

is there a way to reduce it

tame slate
#

You can calculate throwDirection in this block

if (IsOwner)
{
    if (playerInput.actions["Shoot"].triggered)
    {
        ShootGunServerRpc();
    }
}

and send it through the ServerRpc

wild mortar
#

oh

#

that makes sense

tame slate
#

It still may look off in some regard, but at the very least the bullet will be shot in the direction the client was looking when they clicked shoot

wild mortar
#

ok cool thank you

sharp axle
twin stone
sharp axle
twin stone
tame slate
#

NGO is largely designed for smaller scale cooperative games. The closest you can get to prediction with built in features is with Client Anticipation.

Building a custom prediction system is not a trivial task and becomes much harder if your game uses physics based movement as Unity's physics system is not deterministic.

sharp axle
#

Its not impossible but it will take a lot of work to do it properly

#

I don't think Quake ever had client prediction.

#

But there are other ways to deal with latency

#

huh, maybe Quake 3 did have it

tame slate
#

The original Quake did not have it. It was just fully server authoritative with no prediction system. And this was largely fine as the game was commonly played on LAN.

sharp axle
#

It's not an absolute requirement. Many games don't have it

#

it just doesn't take physics into account. Its not a full rollback solution

tame slate
#

It really depends on your end goal. If you want a production level of competitiveness and security, you're looking at making something almost entirely custom on top of a low-level networking library. Netcode for Entities boasts a lot of the systems you're wanting, but if you're not familliar with ECS/DOTS that's going to be a bad time.

But I would tend to agree with evilotaku is saying. Unless you truly truly want what I described above, you can get 90% of the way there with other techniques and by making some clever gameplay choices.

sharp axle
#

DOTS for the most part is completely different from OOP design. Data Oriented Design takes a bit of getting used to but its actually very well suited for networking

#

If you want to dip your toes in, there is a Competitive Action Multiplayer template you can take for a spin

#

Photon Fusion has client prediction but you are stuck using their Photon Cloud service. Fishnet also has prediction that is locked behind a paywall.

tame slate
#

Yeah that’s been on the roadmap for several years now. While it might come someday I can’t imagine it’ll be any time soon.

sharp axle
#

This is a number of years away. Unity 7 or later

tame slate
#

That being said, definitely exciting nonetheless.

blissful jay
#

Hasn't this article been published for 6 years now?

sharp axle
valid willow
#

I'm trying out different interpolation types for network transforms and am curious, what is the actual difference when comparing Smooth Dampening vs Lerp (non legacy). Which one is more preferable in which situations?

Testing locally with network simulator I notice that dampening is more jittery, however I can't confirm if its more accurate or not 🤔

slow geyser
#

Hey everyone. Please explain, does Unity use TCP+UDP or UDP with selective reliability?

spring crane
slow geyser
spring crane
sharp axle
# valid willow I'm trying out different interpolation types for network transforms and am curio...

This goes into a little bit more detail on the different Lerp options
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/pull/3355

GitHub

After doing some testing I noticed a few anomalies with the updated BufferedLinearInterpolator&lt;T&gt;. As it turns out, there are more than one approaches a user might need depending upon...

waxen quest
#

@tame slate So they told me this.

Here is the free tier limit from the UGS Pricing page:
 
3 GiB per CCU for free up to a max of 150 GiB / month (combined US/EU/Asia Australia)

 
I have done some investigation in your Cost and Usage page of the Unity dashboard. Unfortunately, it looks like the confirmed Relay bandwidth usage exceeded the free tier limit in April 2025.
 
Relay CCU: 11
Relay Bandwidth APAC: 1.7
Relay Bandwidth US + EU: 133.54
 
While you may not have exceeded the 150 GiB bandwidth free tier limit, it appears that you exceeded the 3 GiB per CCU free tier limit.
#

The last para

#

I was under 150 gib they confirmed, charged me because of exceeding the per CCU 3 gib limit

waxen quest
#

But how do we know if we are exceeding per CCU bandwidth limit?

tame slate
#

I thought it was 3GiB for the first free 50 CCU you get. But if you only average 11, your bandwidth usage can only be 33 GiB to remain in the free tier.

waxen quest
#

This seems very restricted.

#

3 gb is very low

tame slate
#

I mean it all depends on the type of game and how optimized it is. There’s plenty of genres of games that wouldn’t even come close to that limit.

waxen quest
#

When I was not subscribed to Unity services. I used to hit 80% of relay usage with 15-20 CCU. But I got never charged

waxen quest
tame slate
#

I would definitely profile your game to see what is using so much bandwidth.

waxen quest
#

For bandwidth

#

I also have chat made with rpc. Is it that causing this?

tame slate
#

This package should have a Network Profiler which you can use to monitor bandwidth.

waxen quest
#

Thanks

waxen quest
#

Thanks, I'll check these out

waxen quest
#
    private void UpdateTransport()
    {
        int maxPacketQueueSize = networkManager.ConnectedClientsIds.Count * 32;
        int maxPayloadSize = (networkManager.ConnectedClientsIds.Count + 10) * sizeof(float) * 3 * 3 * 10;

        if (maxPacketQueueSize > transport.MaxPacketQueueSize)
        {
            transport.MaxPacketQueueSize = maxPacketQueueSize;
        }
        if (maxPayloadSize > transport.MaxPayloadSize)
        {
            transport.MaxPayloadSize = maxPayloadSize;
        }
        // Utils.DebugLog("Updating values " + transport.MaxPacketQueueSize + " and " + transport.MaxPayloadSize);
    }
#

is this okay?

tame slate
upbeat summit
upbeat summit
# upbeat summit

how would i reliably move the player for all clients to assume that if the player is seated, it will always be located at the seat

upbeat summit
sharp axle
upbeat summit
sharp axle
#

Yea ParellSync was used before Multiplayer Play Mode

long leaf
#

I'm using parellsync rn, is it inferior to mpm? From what I could see, I like the dual-editor setup more

tame slate
tame slate
#

Because?

sharp axle
tame slate
#

Building is a perfectly acceptable way of testing. I’ve completed an entire project doing so. I would also assume there’s not much urgency for them to build an in-house solution when there’s a production level plugin available to the community that does the same thing.

sharp axle
#

There was already a free open source tool that did the same thing. I wouldn't waste the development time reinventing that wheel either

reef comet
#

I have a strange issue using the PlayerInputManager while also using Unity Netcode for Game Objects.

It seems that whenever a device joins as a client (not a host or server), their PlayerInputManager picks up the other player's (owned by other devices) player inputs and calls OnPlayerJoined() on these.

The only way I can currently think to stop this behaviour is to have a menu before the player connects where players can join and then I disable the player input manager after this, but is there another way I can stop the PlayerInputManager from detecting the networked objects as "joining players"

sharp axle
reef comet
sharp axle
reef comet
#

My issue is more assigning the specific controller to that object's player input

#

I have managed to get the whole spawning with ownership part working

#

Just how do I let players press a button on their controller and detect the input device(s) it came from and then I call JoinPlayer() on it?

sharp axle
reef comet
#

Eugh that's annoying I really need it to not be automatically joined lol

#

I guess if there's a way to join players without the PlayerInputManager that'd be the best course of action to take

#

But I'm also guessing not many ppl have done that so it might be hard to find stuff about it