#archived-networking

1 messages · Page 35 of 1

stoic crypt
#

or on the player?

#

the positions of player 1 (the host) sync with the view of the 2nd player

#

the 2nd player just has no input

sharp axle
stoic crypt
#

shouldn't I?

#

was unsure if i had to have one Main camera attached to each player or just have a child camera for each player

sharp axle
stoic crypt
#

do i have to change the ownership of something?

#

add client authoritative movement? I don't really get it

sharp axle
stoic crypt
#

or should it be 1

sharp axle
#

Client ID should increment by 1 with each new connection

glacial totem
#

Any idea why I would be getting error during runtime on a Dedicated Server platform build but not on my normal builds?

#

The line throwing a NullReference exception is just accessing a gameobject through a Singleton patter
GameObject faceoffPosition = GameServer.Instance.GameState.GetFaceoffPosition(Team, Position);

tame slate
glacial totem
#

I'm using LiteNetLib and it's technically happening when the packet comes in.

#

Behind the scenes that might be on a difference thread, but I guess the focus is that this code works perfectly fine when I run the server in normal Windows platform mode

#

If I compile to default, it works. If I compile to Dedicated Server, it doesn't

#

@tame slate tagging since I forgot to reply

tame slate
glacial totem
#

I'm not sure how the answer then question then haha

#

I'm calling it from a function?

#

It's on another MonoBehaviour

#

Both of them are in the scene from launch

tame slate
# glacial totem I'm calling it from a function?

Awake, Start, an event callback?

Unity tends to execute with slightly different timings on different platforms, sometimes just switching up the order you initialize and access things can fix issues like this.

glacial totem
#

The singleton is initilized during startup

#

and the function call happens from a network receive event

#

So timing wouldn't make sense at all here

#

I can wait however long I want before I trigger this

sharp axle
dapper zinc
#

Does anyone have a example for using this type of RPC?

[Rpc(SendTo.SpecifiedInParams)]
#

What is a BaseRpcTarget, how do i use it

#

I currently have the following function i want to call:

    [Rpc(SendTo.SpecifiedInParams)]
    private void AttackRpc(RpcParams rpcParams = default)
    {
        var sender = rpcParams.Receive.SenderClientId;
        var senderObject = NetworkManager.Singleton.ConnectedClients[sender];
        
        Debug.Log($"AttackRPC");
        var direction = (transform.position - senderObject.PlayerObject.transform.position).normalized;
        _components.Movement.AddVelocity(direction * 10f);
    }

How would i call this RPC to a specified target, it asks for a LocalDeferMode and a BaseRpcTarget

#

Can't find a example in the docs or google

keen dove
#

trying to use photon fusion 2 to make a 1v1 fps game, im currently making my movement script work with fusion 2, but when i try to jump, it doesnt work more than half of the time. the grounded check works fine, its just the input isnt right.
player control script: https://pastebin.com/WfTu1Jq2
input handler script: https://pastebin.com/5ZQD81Xg

#

could someone please help me with this?

fallen beacon
#

Can anyone please link to a guide on using the NetworkManager, but specifically with a dedicated server that exists separately to the client?
All I've been able to find are tutorials where they'll add a "start server" button and have all the logic exist within one scene
I'm looking to have a dedicated server build that can be distributed separately and works by itself

sharp axle
# dapper zinc I currently have the following function i want to call: ```cs [Rpc(SendTo.Sp...

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

languid smelt
fallen beacon
#

thanks guys

undone aspen
#

Any of you guys doing XR ?

Important: You should never have more than one active XR Origin in a scene
https://docs.unity3d.com/6000.2/Documentation/Manual/xr-origin.html

Im using fusion framework in shared mode so the first thing I did was to spawn a XR origin every time someone joins, so I have multiple XR origins in my scene and the game behaves weirdly

I think I have to do something about the main camera that is coupled with the Move locomotion controller, but I wonder if there is a more simple solution

#

SO far I have added this to my XR origin prefab


    public override void Spawned()
    {
        if (HasStateAuthority)
        {
            GetComponent<XROrigin>().enabled = true;
        }
    }

Like only the local guy enables the XR origin component that manages the MainCamera thing, but then other guys on the scene are still coupled to that one main camera, so I guess I have to unlink my rig from the main camera, but again am I doing it wrong

dapper zinc
#

I think i was looking into the older NGO docs

sharp axle
#

The XR Rig should not be networked. Keep that local. The VR Avatar can be your spawned player object.

Check out how the VR Template does it

undone aspen
#

As long as I dont have the full hierarchy of the xr origin prefab I shouldnt have any oddities and conflicts between maincameeras and xr origins right

dreamy condor
#

In netcode for GameObjects is there any way to spawn a Player in DontDestroyOnLoad?

tame slate
dreamy condor
sharp axle
dreamy condor
blazing arch
#

I've got a syntax question.

Here is my code:

// PlayerController inherits from NetworkBehaviour
 var player = collision.GetComponent<PlayerController>();

 if (player?.NetworkObjectId == shooterID) return;

However, chatgpt keeps changing my code from that to this:

 var player = collision.GetComponent<PlayerController>();

    // Ignore the collision if it's the player who shot the bullet
    if (player != null && player.NetworkOjbectID == shooterId) return;

I don't see anything wrong with my syntax

sharp axle
pure geode
#

Hi!
I have a problem: for late-joining clients, OnValueChanged event doesn't trigger (for other players' GOs whose value have changed) upon connecting (value itself is synced).
Upon connection I expect all of the local GameObjects to receive updated values of their NetworkVariable and thus call OnValueChanged but it doesn't seem to work.
Here's the relevant code.

public NetworkVariable<int> coin_count = new NetworkVariable<int>(0);
public override void OnNetworkSpawn()
    {
        coin_count.OnValueChanged += OnCoinCountChanged;
        // OnCoinCountChanged(0, coin_count.Value); # this works but i dont like it. Think I'm missing something
    }
public void OnCoinCountChanged(int previous, int current)
    {
        int interface_coin_count = CountChildrenWithName(coin_panel, "Coin(Clone)", 0);
        int change = current - interface_coin_count;
        for (int i = 0; i < change; i++)
        {
            Instantiate(coin_prefab, coin_panel);
        }
    }

I found the solution of manually calling callback function but i believe there has to be a better approach.
Any knowers?

pure geode
#

Also when debugging networked games, scripts dont pause on breakpoints for every instance of the script. I would expect every instance of a script to pause first on server, then - on clients. Is there settings/documentation regarding this?

zealous hound
#

Hey i need some guidance...
Goal: I want to create multiplayer game where players interact only via chat and they can just see each other characters but thats it... no other interaction. every one have its own mobs spawned, item dropped etc. + i want to make it little bit harder to cheat thanks to server authority.
My Current Idea is to handle server with dots and netcode for entities but i want client side to avoid dots where possible. I want game to build for dedicated server and dont support host as client at all.

I have some problems finding some nice and not outdated examples or good guides how to handle netcode like that :/

i wanna start with implementing some basic core feature: Mob spawning!
Idea: On servers there are placed entities that are templates for spawned mobs. for individual players it pools mob from pool with reset stats. when player defeat a mob than template on server will count down respawn time for it.

i am not sure how to handle pooling in this mixed dots/gameobject & server/client context

sharp axle
bright coral
# zealous hound Hey i need some guidance... Goal: I want to create multiplayer game where player...

If you want to simulate individual client worlds on the server, that aren’t shared, that’s going to be a lot of simulations to run in parallel.
I would maybe consider splitting them up into two instances- One server instance that only syncs chat and player transforms, and one per-client instance that is in charge of world simulation / gameplay. The latter could be made with DOTS, and the former in something like Go, since you wouldn’t need the overhead of Unity to simply sync transforms and chat.

sharp axle
#

Personally, I wouldn't try to mix Entities and Gameobject logic. The server could definitely use the job system with gameobjects if you have loads of NPCs

zealous hound
zealous hound
onyx lotus
#

Anyone have any idea why my packets sent sometimes spikes to 1k/s when connecting to the host on the second window?

#

I only have some small codes going, movement, 4 slot inventory and pickupable objects

sharp axle
onyx lotus
sharp axle
onyx lotus
sharp axle
bright coral
# onyx lotus Is there any way to know if I’m implementing things in a wrong way that uses way...

Usually you'd calculate the size of the data types you're sending to get a feel for what range you expect your bandwidth usage to be in, based on what you believe you are sending.
https://learn.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-170
(and strings are usually int (count) + number of characters (char).

Depending on the framework or library you use, the documentation will often times mention the base size of your packets. Some frameworks will tack on player ids, packet sequence numbers, network time etc, before you've added any data at all yourself.

onyx lotus
onyx lotus
bright coral
#

If you get queue warnings on connect it almost sounds as though you're trying to send data before the connection is fully established. This could be a non-issue if your queue gets full and then on connection established it's flushed back to the client- since it's a one-time purge of the built up queue (I'm not sure what framework we're talking about here so keeping it general)

#

I'd only worry if the warnings were continuous

onyx lotus
#

I’m using Netcode for game objects. That could be the case, I’m early in the development stage so I only have a host and client button that instantly spawns the player prefab with all the scripts on when connected.

#

As far as I’m aware the packets drop after the spikes, which can range from 200 packets/s to 1k packets/s. but I’ve not tested that much so far.

#

It also varied who got the warning messages, sometimes the host and sometimes the client got them.

sharp axle
bright coral
#

I would expect the bundled components (NetworkTransform, NetworkAnimator etc) to only send after a connection has been properly established (but they might not)-
but could it be that you have custom send logic that's sending data without checking the connection, when perhaps it should? (Although again I'd expect NGO to not let you send to an unresponsive client)

#

Although I suppose the queue might just be for that- letting you queue up messages in case the client is momentarily unresponsive

onyx lotus
onyx lotus
bright coral
#

But assuming you have a tick rate of 20hz, and you peak at 1k/s,
that's still only 50 bytes per tick, which is hardly a lot all things considered.

onyx lotus
#

Yeah it’s not a lot after all, the data getting sent so far doesn’t exceed 3kb. But I still got unsure due to the warning messages I get

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

strange current
#

Hello, I am in the process of discovering NGO. I've been following the CodeMonkey tutorial (https://www.youtube.com/watch?v=3yuBOB3VrCk) and I pretty much understand how setting up NGO works. But I'm running into a silly problem. I can't spawn an object and make it the child of another.
I've created a GameObject called NetworkObjectSpawner. I've associated it with a script called NetworkSpawner, which is as follows:
https://codefile.io/f/BKIUa3ETRt
It takes as parameters the transforms of 3 prefabs. "Player" representing the player, "spawnedSword" representing a sword and "swordContainer" representing the location where the sword is contained in relation to the player.
When I run it and I'm in host, the player, the spawnedSword and the swordContainer objects appear correctly in the scene, but swordContainer doesn't become the child of player. I know this because parentResult returns false.
To make things clearer, here are some screenshots to give you an idea of the architecture of my project:
The first represents my project when it's not running with the NetworkManager next to it.
The second shows it when it's running as a host. You can see that both the sword and the players appear. The swordContainer also but only visible in the hierarchy since it is empty.
Could someone please help me?

shy canopy
#

I want to create a multiplayer game but when I use the Competitive Action Multiplayer I get a whole bunch of errors

tame slate
devout yacht
#

For a simple Peer to Peer (I am not doing a server, the scope is a simple Peer to Peer Multiplayer game, maybe Steam if that is free) game what Multiplayer framework is the simplest?

I'm not doing anything competitive, Co-Op PvE is the ultimate goal with this.

tame slate
#

That being said, I would personally recommend NGO. Staying within Unity's ecosystem can be a good thing simplicity wise, especially if you end up using other UGS packages to pair with NGO

dusty hill
#

I have a class that contains all the players stats and is a networkvariable in another script that is attached to each player. It seems to correctly synch names and the health changes when they take damage, but it seems to get de-sync'd and will show different health values for different players if the test damage object is touched. Is there a trick to keep a NetworkVariables variables better synced?

tame slate
dusty hill
#

This is the RPC I used to set the variables I feel like I'm missing something for sure
`[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
SetCurrentAttributes(attributes.Value);
}

public void SetCurrentAttributes(AttributeContainer attri)
{
    attributes.Value = attri;
}`
tame slate
#

Currently you're just ignoring the value sent through the RPC and setting the NetworkValue to its existing value

dusty hill
#

I changed it to `[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
SetCurrentAttributes(attributes);
}

public void SetCurrentAttributes(NetworkVariable<AttributeContainer> attri)
{
    attributes = attri;
}`
#

but it still seems to get desynced with a spammy damage thing

strange current
tame slate
#
  • Send the value to the server with an RPC
  • Take that value and apply it to the NetworkVariable by setting .Value
dusty hill
#

I understand now, it seems to be working. I did get an issue sometimes where the clines health would flicker between two numbers for all players but the numbers are synced ... even the new bug is sync'd, which is a mixed bag.

sharp axle
shy canopy
sharp axle
shy canopy
blazing arch
#

How should I be using object pooling, specifically the Despawn() method?

I copied this object pooling code off github. It was originally for the boss room game.

I have a player, who is shooting bullets.

This is how I'm currently spawing the bullets from the pool:

void ShootServerRPC(shootDirection)
{
    var net_Obj = NetworkObjectPool.Singleton.GetNetworkObject(BulletPrefab, transform.position, CalculateRotation(shootDirection));

    if (!net_Obj.IsSpawned)
        net_Obj.Spawn(true); 

    Bullet bullet = net_Obj.GetComponent<Bullet>();
   
    bullet.Initialize(NetworkObjectId, shootDirection);  // Provide the bullet with the id of the person that shot it. 
}

And when I want to return the object to the pool, I use NetworkObject.Despawn(), and the code looks like this:

// this is in the bullet class
 private void OnTriggerEnter2D(Collider2D collision)
 {
     if (!IsServer)
         return;
      // Some logic
      
     NetworkObject.Despawn()
}      

Does this return the object to the pool, or just delete it?

--- Other things I'm still debugging but would appreaciate help on ---

I don't really understand inferfaces, so I'm a bit confused on how everything works.

I do also have another error, when I try to despawn the network object, saying this [Netcode-Server Sender=0] Object is not spawned!. This happens even with the IsSpawned check.

dense flame
#

Why might player and camera movement not be working on connected clients in my game? (netcode for gameobjects)
I have an owner-authoritative network transform component on the player.
Everything works perfect on the server, but on the client, the player cant move their cinemachine freelook camera or move around
The cinemachine camera is inside the player prefab which should be owned by the client

devout yacht
#

Does anyone know of a good Tutorial over NGO? Preferably one that either does Peer to Peer or goes through Steam (I am not going to run my own / cloud servers / whatever Unity offers unless it is completely free of charge.)

tame slate
# devout yacht Does anyone know of a good Tutorial over NGO? Preferably one that either does Pe...

Most NGO tutorials just cover NGO itself and test locally, or they cover NGO with Unity Relay. There are probably a few tutorials here and there for Steam integration.

Unity Relay's free tier is very generous, and you wouldn't pay a cent until you have a player-base in the thousands (most likely).

Also worth noting that while Steam Relay/P2P may be "free", you are paying $100 to publish your game on Steam and they take 30% of your game sales.

bright coral
#

Epic Online Services dogjam

devout yacht
devout yacht
#

I guess it doesn't have to be NGO as well. Any framework works.

bright coral
#

FishNet is supposed to be pretty neat. But I'd go with NGO - It's quite robust.

dreamy condor
#

Is there any way i can sync the player Object in netcode for GameObjects other than Scene managment or dontDestroyOnLoad?

sharp axle
dreamy condor
sharp axle
dreamy condor
sharp axle
dreamy condor
sharp axle
full perch
#

Does anyone know what kind of error is this? I have no dictionary, and if I remember correctly, a pretty similar error pops out when you use a NetworkBehaviour without a NetworkObject, but its not the case here.

KeyNotFoundException: The given key 'BombAbility' was not present in the dictionary.
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <8ce0bd04a7a04b4b9395538239d3fdd8>:0)
Unity.Netcode.NetworkBehaviour.__endSendServerRpc (Unity.Netcode.FastBufferWriter& bufferWriter, System.UInt32 rpcMethodId, Unity.Netcode.ServerRpcParams serverRpcParams, Unity.Netcode.RpcDelivery rpcDelivery```
tame slate
full perch
blazing arch
#

I have a bullet, which I want to sync the fire direction once upon firing, but not the transfrom.

Will it be easier to use NGO, or just use MonoBehaviour?

sharp axle
crimson sleet
#

Hi gang anyone know of some tutorial / resources I can look into to making client hosted lobbies in N4E

#

or just point me in the right direction of how to start

crimson sleet
#

its annoying that the n4go docs are so incredibly elite and then n4e is like pretty mid

#

is the session workflow for both the same?

crimson sleet
#

this is just about basic setup of n4e and dots its not really anything to do with lobbies and remote connection

sharp axle
jaunty stirrup
#

does anybody know about a netcode for entities tutorial that is good for making a first person shooter??

jaunty stirrup
sharp axle
#

There are not a whole lot of DOTS tutorials in general

jaunty stirrup
#

yea Ik😔 but I've seen others create an fps game in dots so I gussed there must be a tutorial out there

full perch
#

Does anyonwe know how to enable Distributed authority withour losing access to server rpc?

sharp axle
full perch
sharp axle
full perch
#

And if I use RPC with sendTo.Server?

sharp axle
full perch
sharp axle
full perch
#

Appreciate it

dreamy condor
#

When i join the server with the first client its ok but when i join on next the second client cant see the first player. (The player get added into the DontDestroyOnLoad at the start of PlayerController script) any solution please? (I just need the way to transport the player object through the scenes)

dreamy condor
#

Or is there any way i can use the scene management without the server's scene sync?

sharp axle
full perch
#

Yo @sharp axle sorry to bother you again, but is it possible to use Distributed Auth below Unity 6?
The last UNET package availiable in my editor is 1.11.0 and Distributed auth comes with 2.2.0 with seems to be only present in Unity 6

tame slate
full perch
tame slate
full perch
#

thats the issue, im not using Unity 6 XD

tame slate
bitter rune
#

Hey, I have a Network Transform on my player prefabs with Server Authoritative Mode and synchronized position and rotation axis. I now implemented an aiming mode where the player can cast a spell to a target area and the hero´s rotation follows the mouse cursor. this works fine on a host but does not work an a client as the rotation from my code is immediately overwritten by the server authoritative network transform. I have tried implementing a rpc call but its still the same. Is there an easy solution to this problem?

#
        if (!IsAiming) return;
        if (!aimingHero.IsOwner) return;  // Ensure we’re the local owner

[...other code...]

        Ray ray = Camera.main.ScreenPointToRay(PlayerInputManager.Instance.MousePosition);
        if (Physics.Raycast(ray, out RaycastHit hit)) {
            Vector3 targetPos = hit.point;
            Vector3 lookDirection = targetPos - aimingHero.transform.position;
            lookDirection.y = 0f; // Only horizontal rotation

            if (lookDirection.sqrMagnitude > 0.001f) {
                // Compute the target rotation based on the mouse position.
                Quaternion targetRotation = Quaternion.LookRotation(lookDirection);

                // Store the current rotation.
                Quaternion currentRotation = aimingHero.transform.rotation;

                // Smoothly interpolate locally.
                Quaternion newLocalRotation = Quaternion.Slerp(currentRotation, targetRotation, Time.deltaTime * heroRotationSpeed);

                // Determine the angle difference between the current rotation and the new rotation.
                float angleDifference = Quaternion.Angle(currentRotation, newLocalRotation);

                // Update the hero's rotation locally.
                aimingHero.transform.rotation = newLocalRotation;

                // Only send an RPC if the difference is above a threshold (e.g., 5 degrees)
                if (angleDifference > 5f) {
                    RequestRotationServerRpc(newLocalRotation);
                }

[...other code...]
    }```
#
    [ServerRpc(RequireOwnership = true)]
    private void RequestRotationServerRpc(Quaternion newRotation) {
        // Update the hero's rotation on the server.
        if (aimingHero != null) {
            aimingHero.transform.rotation = newRotation;
        }
        // Broadcast the updated rotation to all clients.
        UpdateRotationClientRpc(newRotation);
    }

    // Called on all clients to update the hero's rotation.
    [ClientRpc]
    private void UpdateRotationClientRpc(Quaternion newRotation) {
        if (aimingHero != null) {
            aimingHero.transform.rotation = newRotation;
        }
    }```
blazing arch
#

@bitter rune
Is this a Monobehaviour or NetworkBehaviour? Monobehaviours shouldn't have a network transfrom.

If you are intending to use the NetworkBehaviour class, do not use RPCs for rotation. It will sync automatically (Do it through one of the network components).

If you are using MonoBehaviours, you shouldn't have a network Transform.

As for which to use, I think Monobehaviours will be easier to reduce latency, but I'm not too sure myself.

Quick note: You should add the word "csharp" after the triple backticks. That gives your code some color.

like this:

if (someStatement)
{
    // Do something
}
haughty berry
#

is there a mirror server link somewhere in this server?

blazing arch
#

Do you mean the networking Mirror? UnityChanHuh

haughty berry
#

yes

blazing arch
#

i can't send invite links here

haughty berry
#

send me in pm if you want?

bitter rune
blazing arch
sharp axle
jaunty stirrup
#

does anybody know about a netcode for entities video tutorial that is good for making a first person shooter??

tame slate
# jaunty stirrup does anybody know about a netcode for entities video tutorial that is good for m...

There aren't many videos for DOTS and NfE as they are pretty new, but Unity has some good templates and samples that give more than enough to get started and build off of.

https://docs.unity3d.com/Packages/com.unity.template.multiplayer-netcode-for-entities@1.0/manual/index.html

https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Samples/onlinefps.md

GitHub

Sample projects for the Unity.CharacterController package - Unity-Technologies/CharacterControllerSamples

jaunty stirrup
#

I tried to learn from these templates

#

but it's impossible jk it's just really hard for me

#

Idk where to start

#

and I wanna build of it after I understand all of it

tame slate
# jaunty stirrup and I wanna build of it after I understand all of it

Then personally, I wouldn't be looking for tutorials specifically about NfE for making an FPS game. Start smaller, as there a a handful of tutorials that go over the basic of DOTS and NfE. Spending some time on those first might give you a better shot at going through the templates and samples.

visual sandal
#

I'm using Unity Netcode for Gameobjects and Steamworks.NET. Is it worth to make a Custom SteamTransport with Steamworks.NET or is there someone who has already done so?

dusty hill
#

Is there a unique player ID that is persistent across sessions, or does that need something like Steam APIs?

tame slate
# visual sandal I'm using Unity Netcode for Gameobjects and Steamworks.NET. Is it worth to make ...
GitHub

Community contributions to Unity Multiplayer Networking products and services. - Unity-Technologies/multiplayer-community-contributions

tame slate
#

Something simpler would be just using something like device ID to recognize repeat players

dusty hill
#

It's mostly just to know which save to load for a player when they are connecting so the device ID might be fine

full perch
#

Does anyone know how to make a client network animator stop animating to allow a ragdoll to happen without rpc?

Tried disabling it with _animator.enabled = false but that doest sync

If I transition to a emtpy state with no motion I will just stay in the base position, but not really stop animating.

tame slate
sharp axle
#

Yea. I usually just swap out the animated object for the ragdoll

full perch
#

In that case Id rather just use the rpc no disable the animator in the network too

#

Thats why Im asking if is it possible just by calling the animator or something similar

#

In terms of design and structiure Id prefer not to use a RPC here

sharp axle
full perch
#

I can add a listener to the animator so check wheter a state is active or not right?

#

So if the animator transitions to the death state I jut disable it locally

#

wouldnt that work?

sharp axle
# full perch wouldnt that work?

I suppose it could. I personally wouldn't trust the clients to manage their own death state. But no reason it can't technically be done

full perch
#

Thanks tho UnityChanThumbsUp

hardy basin
#

Im coding a netcode game but my player object falls through the floor on the other players screen , I have my network transform y syncrinzation on but the player still falls through

sharp axle
dapper zinc
#

Hi, shouldn't a network variable be automatically synced with late-joiners?

#

I have a problem where my late-joining clients are not seeing player skins, even tho i'm subscribing to the OnValueChanged event on OnNetworkSpawn/Despawn as in the docs

#

The only way i got it to work is by calling the callback manually before registering to this event, which looks odd

sharp axle
weak plinth
wild radish
#

Hey

bitter rune
#

Can I temporarily disable the rotation sync in a network transform component by code?

sharp axle
bitter rune
bitter rune
weak river
#

guys is comparing tags diffrent in network bc host and client don't detect the tag they collided with pls help me

sharp axle
# weak river guys is comparing tags diffrent in network bc host and client don't detect the t...

If you are using NGO, then by default physics collisions will only fire on the server. Triggers will fire on all clients however.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/

There are many different ways to manage physics simulation in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.

weak river
#

thanks

keen dove
#

could someone help me try to solve this issue?

tight rapids
#

anyone else encounter an issue where if you play an animation on the client, the whole clip plays but on the other client's side, only the later part of the clip plays.

player 1 |-----------| full clip
player 2 |xxxx------| only the end part of the clip plays to maintain the sync

#

was tryna get a player to punch another player but realized that the later half of the swing gets shown so that they end at the same time

#

nvm clearly my dumbass didn't read this section

drowsy nexus
#

I'm using Networking.Transport for my multiplayer game and I got it working correctly on my local machine, but how would I get it working online?
Like, how do I figure out which IP address to connect to?
I'm currently using doing this for the server:

NetworkEndpoint endpoint = NetworkEndpoint.AnyIpv4;
```and this for the client:
```cs
NetworkEndpoint endpoint = NetworkEndpoint.Parse("127.0.0.1", port);
endpoint.Port = port;
sharp axle
spring crane
charred umbra
#

Hi. I'm receiving an HttpException1: (429) HTTP/1.1 429 Too Many Requests error very rarely when periodicly calling GetLobbyAsync. I have a RateLimits Class in-place to mimic the actual rate limits set out at https://docs.unity.com/ugs/manual/lobby/manual/rate-limits. I can't see how my implementation could cause too many requests. I suspect an obvious mistake 🤨 . The console logs show the printed time for each request. Here is my code (Class shortened) http://paste.mod.gg/cvetgxbogyvg/0

tame slate
#

I would also recommend implementing Lobby Events instead of manually updating lobbies every x seconds.

charred umbra
#

That's a good idea. I do plan on optimizing data transfer more. The Serverless multiplayer sample is where that code is from and that ran a 1.5s delay. Events sound far more efficient. Thanks

red garnet
#

hi all, I am using relay and lobbies in unity and wondering how I can detect when the lobby the player is in is closed (for example the host quits), so I can make the main menu canvas active. any ideas?

sharp axle
#

You'll also get a ClientDisconnect ConnectionEvent when the host leaves

red garnet
#

I can listen for that with something like LobbyManager.ClientDisconnect += OnClientDisconnect; right?

tame slate
# red garnet I can listen for that with something like `LobbyManager.ClientDisconnect += OnCl...

When you need to react to connection or disconnection events for yourself or other clients, you can use NetworkManager.OnConnectionEvent as a unified source of information about changes in the network. Connection events are session-mode agnostic and work in both client-server and distributed authority contexts.

sharp axle
red garnet
#

That did it, thanks!

edgy glen
blissful spire
#

What would you guys suggest for networking I've checked out Netcode for Entities but it seems new so im not sure if theres a whole lot of resources on it, and that i havent worked with ECS before

edgy glen
#

I would recommended learning ECS first then when your comfortable learn NetCode for entities

blissful spire
edgy glen
#

What game are you making?

blissful spire
#

a small extraction shooter

edgy glen
#

NetCode for entities has client prediction which prevents people using teleport hacks

#

Which it’s important for an extraction shooter

blissful spire
#

yeah thats my main consideration

edgy glen
#

Unless your just doing coop then it’s not important

blissful spire
#

Alright ill look into learning ECS

edgy glen
#

Learning ecs is gonna take a bit of time but trying to implement your own client prediction I think will take even more time so using NetCode for entities might be quicker if you need client prediction.

Also then you get the benefits of better performance

#

Once you get the hang of ecs it’s just as easy to implement features compared to game objects

blissful spire
#

ive already been messing around with ECS just to try out netcode for entities but sometimes i get stuck and there arent enough resources i can find

#

i can get a entity set up as a ghost but then i cant figure out why it wont visually replicate

#

i can find it on the hierachy and see its values changing but it wont appear

edgy glen
#

is the movement logic inside "PredictedSimulationSystemGroup" ?

#

or is it just running on the client

blissful spire
#

just on the client

edgy glen
#

That’s why it’s not replicating to other clients

blissful spire
#

i have the client as "inGame" so i thought it would automatically replicate it

blissful spire
#

im just gonna fully learn ECS first then tackle networking

hexed pollen
#

Hey everyone! 👋

I’m Nonso, a full-stack dev & smart contract engineer looking for a game dev to team up for a Web3 hackathon! I’ll handle smart contracts (EVM), backend, and Web3 integration—you bring the game to life.

If you’re into Web3 gaming and want to build something awesome, let’s team up! 🚀🎮

worldly birch
#

How would one implement a hit stop in a co-op game? Can’t simply slow down the game on the client, can I?

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

#

: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

blissful spire
blissful spire
worldly birch
#

It should only occur on the client that does the damage, no need to sync it across the network anyways

#

Rubberduck moment

#

Thanks for the options tho

fast briar
#
private void FireWeapon()
    {
        ...

        RequestFireWeaponServerRpc(hitPoint, hitNormal, didHitProp);

        ...
    }

    [ServerRpc]
    private void RequestFireWeaponServerRpc(Vector3 _hitPoint, Vector3 _hitNormal, bool _hitProp) {
        FireWeaponClientRPC(_hitPoint, _hitNormal, _hitProp);
    }

    [ClientRpc]
    private void FireWeaponClientRPC(Vector3 ___hitPoint, Vector3 ___hitNormal, bool __hitProp) {
        ...

        // Apply force if the object has a Rigidbody
        if (shotObjectRb != null)
        {
            // Direction = from shooter (gun position) to the hit point
            Vector3 direction = (___hitPoint - transform.position).normalized;

            // Apply force in the correct direction (use Impulse for an instant effect)
            shotObjectRb.AddForce(direction * 3f, ForceMode.Impulse);
        }

        ...
    }

The issue is that the gameobject containing the rigidbody only moves on the host. The object that gets shot has a rigidbody, network object, network transform and a network rigidbody.

I realize that the rb is kinematic on clients, and can only be moved by the server and then synced to all clients. But this is what I am currently doing, no?

Kinda stuck here

sharp axle
fast briar
sharp axle
fast briar
#

I am using client auth on my players

fast briar
#

still only get the movement on the host.. The rigidbody addforce is in the serverrpc @sharp axle

#

So annoying since everything has been going great until this part lol

sharp axle
fast briar
sharp axle
fast briar
edgy glen
#

Does anyone else have the issue of prediction smoothing (NetCode for entities) working in play mode but not in a build?

dusty hill
#

I've been having an issue where the health value for the client flickers between two numbers. I have a network variable containing a custom class that has a health value inside of it. Has anyone encountered this before and know some fix? Everything seems to work most of the time it's just if the value tries to change very fast it seems to get confused.

tame slate
dusty hill
#

Looked at this earlier:
`[Rpc(SendTo.Server)]
void SetCurrentAttributesRPC(AttributeContainer attri, ulong sourceNetworkObjectId)
{
attributes.Value = attri;
//SetCurrentAttributes(attributes);
}

public void SetCurrentAttributes(AttributeContainer attri)
{
    SetCurrentAttributesRPC(attributes.Value, NetworkObjectId);
}`

And this is where it sets the health/does damage:
[Rpc(SendTo.ClientsAndHost)] public void DamageRPC(int damage) { int HP = attributes.Value.Health; HP = HP - damage; attributes.Value.Health = HP; UpdateHUDDisplay(); SetCurrentAttributesRPC(attributes.Value, NetworkObjectId); }

#

oh I'm not pasting that correctly

karmic ether
#

hey does anyone know a tutorial or anything that could show how to set up photon fusion 2 dedicated servers? Ive been looking into it and I cant find any specific help for dedicated servers and it would be really appreciated if u could let me know

analog tide
#

I have a question if i want to link a command drom discord to my unity can i make it or not ? I'll probably need to use an API ? or having a server to send the instruction ?

sharp axle
analog tide
#

Ohh that’s game changer

spring crane
split hedge
#

Hey!
When I create a new lobby this error pops up hundreds of times, what should I do? I tried reinstalling NGO as well

stiff ridge
hazy hollow
#

hi, im in the process of creating a multiplayer mobile game, and have gone through the Unity Dashboard for multiplayer hosting and set up a matchmaker for it, but im not sure I set everything up correctly. I have 2 phones im testing it out on and have installed the apk file on both, I was able to create a session to host on one and used the created code to join on the other, and the visuals are there but I cant move either player at all. Also the analytics don't show anyone being in the server, they just say theyre available. Ive created fleets and all that and just followed the process the Unity site laid out for me. Any suggestions ?

#

ooh update: so i closed the game on the hosting phone, and the player (players? cant confirm since I cant move them and theyre overlapping atm), they despawned. So its just the background.

sharp axle
sharp axle
split hedge
hazy hollow
#

the networking topo is client hosted btw

#

not sure if theres a different approach with client hosted

sharp axle
sharp axle
hazy hollow
#

Im a little confused by the difference in Sessions and Matchmaking then. Is there a difference? I want to be able for players to "quick match" join, and also being able to create individual matches. Would Matchmaking be for the quick play and Sessions for individual matches ?

#

Also, yea I just checked and the matchmaking > queue > pool is set up alrdy to client to client

sharp tundra
#

hey, does anyone know any good tutorials for unity 6 multiplayer w/ netcode?

#

ones that explain it very well and are relatively recent?

#

nvm i'll go with codemonkey's network for entities

karmic ether
sharp axle
#

Make sure your VR Rig is not being spawned as a player. There should only be one camera in the scene.
Check out the VR Multiplayer Template

spring crane
#

@misty tendon !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

fast briar
#

So synchronizing a rigidbody based playermovement system is horrible as I've understood it..

Created a quick test and the host can move it, and it gets synced to clients instantly, but clients are not allowed to move their rigidbodies, which is quite annoying. Can I just change some small thing to allow clients to do this?

#

The player has the rigidbody in question as a child of themself. It moves and syncs if the host does it, whilst the client is not allowed to move it by adding force. Is this because the ownership is not setup right?

#

Synchronizing the movement and interactions of two rigidbodies, owned by two different players seems awful as well haha

sharp axle
fast briar
# sharp axle Network Rigidbody sets non owners rigidbody to be kinematic. If you set the netw...

Yup, that was the issue. Sorry for even posting the question before testing my theory.

For anyone wondering, this solved it:

[ServerRpc]
    private void SetParentAndOwnerShipServerRpc(NetworkObjectReference propReference, ulong clientID)
    {
        if (propReference.TryGet(out NetworkObject prop, NetworkManager))
        {
            prop.TrySetParent(NetworkObject, true);
        }

        prop.GetComponent<NetworkObject>().ChangeOwnership(clientID); // Give ownership to the player
    }

This sets the networkobject as a child of the transform (needed for my game) and then changes ownership

hazy hollow
#

soo just an open question if anyone's willing to answer, how come the Create Sessions.cs script that im assuming comes from some multiplayer package in the package manager is using old input system code if in Unity 6 forward it seems theyre trying to have the "new" input system be the default ?

public override void OnServicesInitialized()
{
    m_InputField.onEndEdit.AddListener(value =>
    {
        if (Input.GetKeyDown(KeyCode.Return) && !string.IsNullOrEmpty(value))
        {
            EnterSession();
        }
    });
    m_InputField.onValueChanged.AddListener(value =>
    {
        m_EnterSessionButton.interactable = !string.IsNullOrEmpty(value) && Session == null;
    });
}

Im basically doing a double whammy with both mobile and a networked game and running into issues in the backend from some of these things

#

atm running into an issue where the keyboard doesnt open when I switch to the old input system if I wanna type something in the APK build but the networking stuff is using that old input system but if I stick to both in the player settings' input handling then it talks about potential performance issues and possible lack of input. Just been circling around basically

fluid walrus
hazy hollow
#

found it: namespace Unity.Multiplayer.Widgets
hah

fluid walrus
#

i've never used that package but it looks like it's meant for testing only, if it's not intended to be production ready code i imagine upgrading it is a low priority if it works fine with the old system

spring pilot
#

quick question, do I need to rewrite all my lobby code or can I just remove the lobby package entirely?

tame slate
#

Change any usage of Lobbies.Instance to LobbyService.Instance is the only step besides switching packages, basically

hazy hollow
tame slate
#

Says so in the description of the package

hazy hollow
#

well snap, I missed that in this sessions link : https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-your-first-session

So if it's for testing purposes, is that supposed to only work on the editor? It makes sense that the keyboard doesnt pop up with the build on my phone.

So currently to my understanding, Id have to use these code snippets the docs provide to manually create a menu myself instead of the one that the widgets one provides ? : https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session#Find_a_session_using_Unity_Matchmaker_service

tame slate
#

The specific docs link you sent is for pairing Sessions with the Matchmaking service. The only two sections you really need to worry about to start are Create a session and Join a session

sharp tundra
#

hi, i have the code

private async void CreateRelay()
    {
       await RelayService.Instance.CreateAllocationAsync(3);
    }

which spits out the error: error CS0433: The type 'RelayService' exists in both 'Unity.Services.Multiplayer, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Unity.Services.Relay, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
can anyone please tell me what this means and how i may be able to fix this?
V: Unity 6 (6.000.0.32f1)
Visual studio 2019 (if it's important)

I added csharp Using Unity.Services.Relay at the top too and it still throws the error.
Any advice?
Thanks in advance.

tame slate
sharp tundra
#

oh. thanks!

#

i hate to be that guy

#

it just wont let me remove it

tame slate
# sharp tundra

Don't think I've ever seen that. Would just try restarting.

sharp tundra
#

will do

#

well it works now

hazy hollow
# tame slate The specific docs link you sent is for pairing Sessions with the Matchmaking ser...

I just started with setting up the Unity matchmaking and using the Unity cloud server stuff, so I was wondering how that widget just automatically "networked" it. But it looks like its not, you have to manually use these "StartSessionAsHost()" and "CreateOrJoinSessionAsync()" and set up a menu and network it urself. thank you! This makes a lot more sense, i was curious how I was gonna get to editing that widget menu but I guess I gotta make it myself!

sharp tundra
#

thanks!

sharp axle
agile python
#

I have a networked propertie in Photon Fusion 2, even minutes after spawned still display "Networked properties can only be accessed when Spawned() has been called." This is called inside the public override void Spawned() method also! WEIRD!!!

sharp tundra
#

hello all, i have come with yet another query,

is there a way to get all the users in one relay lobby and put them all into a different scene at the same time?

thank you,
Nate

#

nvm i think i know how

sharp axle
sharp tundra
#

thanks!!

half quarry
#

Does anyone know why I need to set the compiler flag UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT to work with native lists for serialization? Like, whats the logic for not including it in the base netcode? Is there some downside (Aside from possibly crashing your game if you use them wrong) for enabling this flag?

tame slate
half quarry
#

Ah, for dependencies. That makes sense

#

And for clarity, the restriction of no nested native containers applies even if the containers are wrapped in another class? For example, I have a 'Geometry' object that has a native list / array of network serializable coordinates. If I was to put these Geometry objects into a native list/array, say a GeometryCollection, it would kill the netcode serializer right?

river gazelle
#

Anyone who can help me adjust my FishNet settings for my game? It's a semi-fast paced top down 2d rpg
I've just added basic movement, copying most of the prediction docs they have.
It works really smooth on the client itself, but looks jumpy when watching from another client.
So far the only way I've been able to fix it is setting my tick rate to 128, but I'd prefer to keep it at 64.
It's not extremely jumpy, but noticable.

Here's my full movement code:
https://paste.mod.gg/lkwzdvgcextp/0

I've tried adjusting all the settings mentioned in the docs, but nothing completely fixes it.
Prediction Manager: State Interpolation, tried everything from 1-5, both inserted and appended.
Time Manager: Tick Rate: 64 - Allow Tick Dropping is on - Update Order: before tick
Player Network Object: Enable Prediction is on, type Rigidbody 2D, enable state forwarding is on, graphical object, tried to add/remove it and change all the settings, but it's always better without a graphics object set.

haughty berry
#

you guys recommend learning mirror for learning multiplayer

river gazelle
haughty berry
river gazelle
#

hehe yeah same, I went with fishnet, it has some ok-ish beginner tutorials and pretty easy to use

#

but again, it really depends on what type of game you want to make

haughty berry
#

allright thanks maybe i will also look into fishnet

river gazelle
#

get the pro version from their github, it's only $10

sharp axle
river gazelle
#

Photon has literally 0 documentation

river gazelle
#

Their business plan literally seems not providing tutorials/documentation and then sell support packs

spring crane
tame slate
ocean wadi
#

Hi! I was just wondering, are there any significant disadvantages using a velocity setting movement system for networking? I was wondering if I should be swapping to a different style of movement such as AddForce and I was wondering if certain ones were more suitable and easier to work with when it comes to networking.

tame slate
tame slate
# ocean wadi Gotcha tyty ^^

In terms of networking, most of the popular Unity solutions and their components disable physics components for non-authorities/owners. So the authority does the physics simulation, and the resulting position change is just synced to everyone else.

#

That may be different for certain solutions, especially with more complex systems.

ocean wadi
tame slate
#

I believe NGO just sets non-authoritative instances of Rigidbody to Kinematic.

ocean wadi
blissful jay
#

networked physics is not easy, especially when using a broken networking solution

river gazelle
#

I'm using client side prediction for my player movement.
Should I also use it for player attacks?

sharp axle
past relic
hazy hollow
#

how do I connect the Unity multiplayer hosting and relaying services into my project? I was using sessions before but was told it was for testing purposes only and doesnt actually connect anything but im not sure how to set that up. I starting looking through this: https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo

It did mention about linking the project in the unity editor to the actual server stuff I set up on the unity cloud site but is this done automatically? I dont need to add the specific server IPs or IDs that were made ?

tame slate
#

If you're using Multiplay Hosting, you would not use Relay. You would use one or the other.

hazy hollow
#

oops meant widgets. Whats the difference between the two ? Relay is for client hosting vs multiplay would be for server hosting ?

tame slate
# hazy hollow oops meant widgets. Whats the difference between the two ? Relay is for client h...

Unity Relay exposes a way for game developers to securely offer increased connectivity between players by using a join code style workflow without needing to invest in a third-party solution, maintain dedicated game servers (DGS), or worry about the network complexities of a peer-to-peer game. Instead of using DGS, the Relay service provides connectivity through a universal Relay server acting as a proxy.

#

Multiplay Hosting would be dedicated game servers.

sharp axle
#

There are some scenarios where might want to use Relay with Multiplay Servers like if your client is webgl

final flax
#

[Multiplayer] Is there a "Relevancy" system in Unity like in Unreal Engine ?

Coming from Unreal, is there any equivalent to the "Relevancy" setting where synced data is sent only to relevant players (a.k.a players being close to the object having that data being updated to not spend bandwith for players that aren't close to where the change happened) ? Or does it send the synced data to everyone everyone it changes even if the players are far away (aren't relevant) ? 🤔

Please ping me if any answer 🙂

final flax
final flax
sharp axle
tame slate
final flax
hazy hollow
#

I found this tut from the unity docs for setting up lobbies but im getting an error on some lines regarding lobbies. I tried installing the package (which is deprecated ?)

        var lobby = await Lobbies.Instance.QuickJoinLobbyAsync();

Doesnt recognize Lobbies.instance , And its sprinkled throughout the script

#

is there some sort of migration with using Unity6 and the new multiplayer packages in the package manager

final flax
#

I have another question :

[Multiplayer] Can we not mix server and client code in the same script (NGO) ?

I keep seeing most of the tutorials mix server and client stuff in the same script, is it possible to put client stuff together in a script and server stuff together in another script for organization purposes ?

Because I find it hard sometimes to know where the code is executed when mixing both client and server stuff in the same script 😄

tame slate
hazy hollow
#

ppreciate it

sharp axle
final flax
final flax
sharp axle
final flax
#

I have another question :

What does it mean to own an object ?

sharp axle
final flax
sharp axle
#

But each object can only have one owner. either a single client or the server

final flax
sharp axle
final flax
sharp axle
final flax
tame slate
sharp axle
final flax
#

@tame slate @sharp axle Thank you 🙂

fluid lintel
#

I know I'm doing something dumb here... But why isn't this changing the text for everyone and is only doing it for the peron who makes the call?

[Rpc(SendTo.Everyone)]
public void SendYesVoteRpc()
{
    yesVotes++;

    // Update text
    mainNavUiYesText.text = "<u>Y</u>es - {" + yesVotes + "}";
    miniNavUiYesText.text = "<u>Y</u>es - {" + yesVotes + "}";
}
#

The text elements are assigned in the playerp prefab's inspector and spawned in at the start

#

The method is part of a local method that is called off a button press (code of which I can provide if you'd like)

sharp axle
fluid lintel
sharp axle
fluid lintel
#

I figured out that I needed to find a way to grab the local instance of my player UI and call that not from itself. I don't fully understand it, but it works 😄

red garnet
#

Looking into adding sound fx to my net code for game objects game. Can't find many tutorials out there, only tutorials for single player games. for multiplayer would I take a similar approach to a single player game, but make the audio manager live in the player prefabs?

hazy hollow
#

she's alive!!!

tame slate
red garnet
#

I guess my main question then would be should my sound manager live in the scene, or in the player game object?

#

also maybe I am over complicating it in my head lol

tame slate
red garnet
#

you would still need clientrpc and serverrpc method for that solution right?

tame slate
# red garnet you would still need clientrpc and serverrpc method for that solution right?

That goes back to my first reply. You may need extra networking communication depending on what exactly the sound is. But generally speaking, what is already networked can just be used to play SFX at the appropriate time.

Examples:

  • NetworkAnimator that's on another players object syncs their footsteps for me, and I can use that already synced information to play a footstep sound.
  • A NetworkVariable boolean that tells me whether or not a door is opened or closed. I can play the door SFX inside of that NetworkVariables OnValueChanged
  • An RPC that plays a particle effect for smoke coming out of a gun that just shot can double as a spot that I can play a gunshot sound.
red garnet
#

Thats good info, I will continue looking into my options. Thank you!

half quarry
#

I have a bit of an odd one. I have a tool that lets players create objects in the multiplayer scene. Part of this is I have a network variable that stores the recipe for each object, as they're pretty dynamic. I want to allow the users to set the model that the object will have. I already have all the models loaded into the projects addressable system. Do you think it would be efficient to build some direct serialization of AssetReference? Or should I just have a lookup table that maps a primative uuid to the asset?

#

Ah, looking closer, Ill have to do the lookup table. For some reason I though AssetReference was a GUID of some kind, rather than a raw string

limber gorge
#

Hi there guys! I've recently been working with Netcode for GameObjects using the Steamworks package via the facepunch transport system. I've set everything up now and I have working connection between two different steam accounts that can join the same game. However now that I have the basics done, I need to check things like a friends list of lobbies for example. I've run into an issue where I can't actually check if one of my friends is currently in a lobby and then get the lobby data. Instead the only workaround I've seen is to request every single lobby and then check each lobby to see if any contain my steam friends.

That solution cannot possibly be sustainable or the best way to handle such a thing. Is there any way to check my friends list directly for if they have a lobby and subsequently retrieve the lobby data?

Update: Found out I can use SetRichPresence and GetRichPresence to store data when I create lobbies - this has solved my issue!

hazy hollow
#

when instantiating a prefab such as a bullet projectile, is there a way to get the object that instantiated? Im spawning from a script attached to the player prefab that gets instantiated so I can have the projectile spawn in from that player's transform.position:

public void Fireball()
{
    GameObject spawnedFireball = Instantiate(fireballPrebab);
    spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
}
sharp axle
hazy hollow
#

smort

hazy hollow
#

sooo i might have done it wrong but I updated the button that calls the Fireball() to:

public void Fireball()
{
    GameObject spawnedFireball = Instantiate(fireballPrebab);
    spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
    spawnedFireball.GetComponent<SpellbookScript>().SetSpawnPoint(transform.position);
}

And have SetSpawnPoint on a script on the prefab that initializes that provided transform.position from the player and set it on start() (I also tried OnNetworkSpawn() since the start() didnt work):

void Start()
{
    transform.position = finalPosition;
}

public override void OnNetworkSpawn()
{
    transform.position = finalPosition;

}


// Update is called once per frame
void Update()
{
    transform.position += transform.up;

}

public void SetSpawnPoint(Vector3 pos)
{
    finalPosition = pos;
}

But the projectile is still spawning from the center of the screen instead of where the player was every time

sharp axle
hazy hollow
#

It is on the player object, although this is p2p, I don't actually have like a server class

#

Movement itself has been working fine without something like that so I assumed i could keep working building the "client script(s)" until I ran into a snag... which would this be it? Lol

#

anyways I think its because of the order of when it spawns that it didnt read the transform.position of the player correctly so i edited the instantiate() with that player position but it still going to 0,0,0:
GameObject spawnedFireball = Instantiate(fireballPrebab, transform.position, Quaternion.identity);

tame slate
hazy hollow
#

well the spawning works for projectile prefab, just not the position. It doesnt spawn from the player, it spawns at 0, 0, 0

sharp axle
#

The host has to instantiate it in the correct position. By default everything gets instantiated at the origin.
You should have the clients send an RPC to the host in order to cast the fireball

#

Clients can't spawn anything only instantiate

hazy hollow
#

🫡

tame slate
sharp axle
#

Just make sure that only the host/server is calling it

hazy hollow
# sharp axle Just make sure that only the host/server is calling it

about that... since its p2p thats confusing me. How do I seperate these restrictions from clients and hosts if its all run on the same project ? Im assuming if I dont restrict to only the host/server it will spawn multiple prefabs? Or a prefab per client even though only one client pressed the fire button ?

hazy hollow
sharp axle
hazy hollow
#

i see. Project structure wise though, would having a dedicated script "acting as a server", such as keeping track of player stats like health, to simulate some sort of server authority, be the best / usual approach then ?

#

for p2p

#

cuz I see a lot of tutorials having like a game manager script and object itself on projects that arent networked. So having this game manager act as a server almost

sharp axle
tawdry trench
#

hello im using fishnet and relay system for p2p hosting however it lets me host the server but when i go on my other game build and type the code it wont let me in.

waxen quest
#

I have an in scene placed network object and I am using the NetworkObject.Despawn() method on server to destroy it. This object also gets destroyed on connected clients but if a client joins the game after the despawn call, the object still appears in the scene. This is what unity netcode should have handled itself

tame slate
#

All you would have to do is disable the visuals of the object in the inspector, and reenable them in OnNetworkSpawn of the object.

#

You could also just spawn this object at runtime as well.

waxen quest
frigid minnow
#

Hi, I'm in process developing backend for my chess game, currently I have client part where game is board of tiles and lists of balck and white pieces. Should I simulate the game on the sever each time new game started or just store last position? The simulation will allow to validate moves but it can take more of server performance and maybe I will need to refactor my game logic to make it run without visual part (visual part is to heavy for server if many games will be played same time).

sharp axle
frigid minnow
#

@sharp axle thank you I think they use fen notation to store position on server, I was thinking about this option too. I'm try to use low level but this example contain a good example of net messages(Requests/Responds).

eternal heart
#

Hello, what is the best network solution for a fast game racing top-down ?
Photon Fusion 2 Shared mode is not fit for that (cf video)
Does the official Unity networking system allow this to be done at best ? or Mirror is fit for that ? or Photon Quantum ? or another ?
i need to be sure this time, i just lost one month of full development to try to make this game in Shared mode (it was advice to me...)

austere yacht
spring crane
#

You need to identify what you need out of the networking solution to make an educated decision. Doing the same thing in different networking frameworks is unlikely to solve your problem.

eternal heart
eternal heart
eternal heart
spring crane
spring crane
#

I don't know what is already going under the hood with these samples, but I imagine you can do better with more aggressive prediction and/or input lag on the client

eternal heart
eternal heart
# spring crane I don't know what is already going under the hood with these samples, but I imag...

This is my point in the sense that for me a solution must precisely propose this kind of settings by itself to respond to this kind of problem.
I mean that they are made for non "network gurus", who do not necessarily have this kind of skill otherwise they would not call on their services but would have created their own network system
But I note that, in this case "Photon 2 Shared Mode" has nothing like that
I dare to hope that Quantum or other (hence my initial question) has this kind of "dev friendly" features

eternal heart
tame slate
#

Of course some solutions offer things like client-side prediction out of the box, but even with those solutions you’re still going to have to do the heavy lifting to implement what is needed specifically for your game.

eternal heart
# tame slate I think to kind of summarize the advice you’ve been given thus far: Any of the ...

I understand every solution are not ready to use, there are need to be setting specificly for the respective project, but somes are more fit for somes project.
Seriously you think a game like Rocket League ( fast movement and collisions and very fast ball movments and collisions) could be are made in every solution ?
I think your answers are tot generic and you had not really works on this problematics, seems more like you would like less more facts/concrets
Im seriously curious if you have an exemple of a fast racing game made with PUN 2, Fusion 2 Shared or Host mode , or anything else Quantum or Dedicated server

eternal heart
tame slate
#

Seriously you think a game like Rocket League ( fast movement and collisions and very fast ball movments and collisions) could be are made in every solution ?

I think you could make it with a wide variety of solutions. And even with the ones you couldn't, you could make something very close.

#

But I don't really want to go down that rabbit hole. I'd rather try and answer your original question.

#

I think Fusion is a suitable choice for your game, but you'd want to be using dedicated servers. Not Client-Host or Shared Mode.

#

So I guess that's more my point, it's really more about the Network Topology in the solution that you choose, rather than the solution itself.

#

You can see here that Shared is not really what you'd want to choose for your game.

#

So I think Fusion (Dedicated Servers) and Quantum are both suitable options. However, I saw you mentioned wanting things to be "dev friendly" and I wouldn't say Quantum really fits that bill.

austere yacht
# eternal heart Do you know a fast racing game made with all solutions or you just say something...

I understand how netcode works and that all libraries do effectively the same (dealing with exactly the same limitations and having the same set of solutions available) so there is no reason to assume any would be better over another. But I suppose you are asking whether one of those frameworks includes a readymade solution for exactly your game. That I don’t know but would guess, none does. Maybe one has a similar example or a bit of code that saves you a week of DIY. Regardless, if you understand anything about netcode it is that the library doesn’t matter once the fundamentals are in order. Which they are in all frameworks you mentioned. The genre of the game is largely irrelevant.

eternal heart
tame slate
#

Dedicated Server is still Fusion, so it would be very similar to what you've been doing - just some differences in ownership and a pivot to server authoritative movement would be required changing from Shared Mode.

eternal heart
eternal heart
# tame slate Just a fair warning - Quantum requires you to use their physics system, as Unity...

Yes i started to look the tutorial https://www.youtube.com/watch?v=uRKrryg-fVU&list=PLyDa4NP_nvPdMnNr34LjHL_6D3KyXxGTR&index=20&t=967s , i will look the entire series and judge after that
But yes the documentation/support are very poor.. :/

Download complete Unity project 👉 https://www.patreon.com/posts/tutorial-photon-94186666
📍 Support us on Patreon and help us make more videos like this one ⏩ https://www.patreon.com/prettyflygames

This is a new tutorial series were we will cover Photon Quantum 2 which is used by Stumble Guys, Battlelands Royale, LEGO Brawls, LEGO Star Wars Ba...

▶ Play video
eternal heart
tame slate
balmy rose
#

following issue

i made a custom service called SessionService which has 2 methods JoinGame and HostGame

the issue lies inside the HostGame method, where im trying to load a scene

im injecting this service later into a monobehaviour and calling the StartHost method but it logs a not set to an instance of an object error at the CustomManager.Instance line

does scene management just not work with dependency injection or does it lie on the actual networking part?

balmy rose
sharp axle
balmy rose
austere yacht
# eternal heart I think that these solutions can help any type of developer to implement a multi...

the bit that is "optional" when it comes to understanding is solved by all libraries, anything on top of that is, in most cases, not generalizable and expecting a framework to enable a non-expert to make a (release worthy) multiplayer game is a fantasy. There are many frameworks that promise to "abstract" networking away from the game-dev-team an just give you options to "toggle which parameters to sync" in some inspector... all of those eventually break down and you have a crappy system that half uses the library and half uses some awkward shims the team made themselves to solve problems that the "neat architecture of the library" couldn't solve (surprise).

sly echo
#

How does this actually work cant other players just decompile the code and remove the isMine part?

sharp axle
viral ether
#

hi chat

blissful jay
# austere yacht the bit that is "optional" when it comes to understanding is solved by all libra...

this is not true at all, plus your other statement about all networking solutions being equally capable of doing the same things

it looks like you haven't touched any of the new libs in the last 6 years

photon fusion/quantum can easily enable average devs to make games with networked physics and whatnot easily without having solid networking knowledge, which are considered the holy grail of multiplayer games

sharp axle
shut solstice
#

Hi all, I'm running into some trouble hitting my server from local (using fishnet)

My error: Unable to lookup LocalConnection for 1 as host.

What I've tried:
Set up an ubuntu vps and ran a headless server. Seems to be running properly
Set up network manager with tugboat component (pointing to my server address)
Verified I can ping my server on the correct port with tcp and udp

#

I'm new to unity but it seems like my client address isn't configured correctly. Just not sure where to look

#

the number in the error also iterates each time I run eg. 1 as host, 2 as host...

shut solstice
#

edit: I had client and server addys mixed up lmao

hazy hollow
#

hii trying to spawn a projectile on the scene and have a function set up to fire when a button is pressed which calls the RPC that spawns the object:

 public void Fireball()
 {
     SpawnFireballRPC(finalPosition.x, finalPosition.y);
 }

[Rpc(SendTo.Server)]
 public void SpawnFireballRPC(float x, float y)
 {
     Debug.Log("Fire");
     GameObject spawnedFireball = Instantiate(fireballPrebab, new Vector2(x, y), Quaternion.identity);
     spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
 }

Im getting a null exception tho on a networking script:
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.NetworkMetrics.GetObjectIdentifier (Unity.Netcode.NetworkObject networkObject) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Metrics/NetworkMetrics.cs:527)

I have the script inhereting from Networkbehaviour and the button has a network object attached to it since thats what code monkey said!

alpine mauve
#

How to get mac address of the laptop using my software on windows? I know SystemInfo helps you achieve most of the related information but no clue about Mac address. Help me out if anyone can

rapid crater
#

i'll say what i said in the other room, after directing you here:
'although, that is usually not something you would need, so may be shyed away from telling you how. it sounds 'hackerish' '

#

so i suppose the first question is Why do you want the MAC address?

#

@alpine mauve ^

alpine mauve
#

So basically I am using this approach instead of proper licensing. Fetching the device hash and adding that in my json file which will then allow that device to open my app. So i'll get information about the device trying to open my software without permission.

#

Do you want more clarity?

#

@rapid crater ^

#

It's okk if you can't help

rapid crater
#

and how would you intend to handle hardware changes?

alpine mauve
#

no hardware changes needs to be done!

#

I am just taking the info

rapid crater
#

no, i mean the users hash would change, if they changed any hardware in their machine.

tame slate
#

Why do you need the mac address specifically?

#

SystemInfo.deviceUniqueIdentifier doesn't work?

alpine mauve
#

I am a begginner, I was using deviceName, model and such basic things. I wasn't aware about this UniqueIdentifier. I was not aware that getting Mac is such a big thing, I'll refrain from doing so

sharp axle
# alpine mauve I am a begginner, I was using deviceName, model and such basic things. I wasn't ...

MAC spoofing is a technique for changing a factory-assigned Media Access Control (MAC) address of a network interface on a networked device. The MAC address that is hard-coded on a network interface controller (NIC) cannot be changed. However, many drivers allow the MAC address to be changed. Additionally, there are tools which can make an opera...

full perch
#

Yo is it somehow possible to network serialize classes instead of structs?

#

like, this actually works

#

but his doesnt

#

everything else in the code is the same, but I need it to be a class to use inheritance and having unique hashes

full perch
sharp axle
sleek helm
#

Hello, I'm not sure what I'm doing wrong. I have a simple netcode for entities with unity physics scene set up. And I am trying to spawn a number of simple prefab cubes into the scene. This prefab has both a Physics Body and a Physics Shape authoring component. I also set Physics World index to use 1(not the predicted world), However, when the netcode package is installed Unity Physics seems to either break, or I have not setup the packages correctly. Physics Body does not seem to be authored on the resulting entity, and the cubes are marked as static. Does anyone know why this is happening?

hazy hollow
#

You might find it useful to add a GameObject property in a NetworkBehaviour-derived component to use when assigning a network prefab instance for dynamically spawning. You need to make sure to instantiate a new instance prior to spawning. If you attempt to just spawn the actual network prefab instance it can result in unexpected results.

https://docs-multiplayer.unity3d.com/netcode/current/basics/object-spawning/

What's this excerpt mean? Have an empty GO with a sole network object component be the parent with the prefab being a child of this GO ?

In Unity, you typically create a new game object using the Instantiate function. Creating a game object with Instantiate will only create that object on the local machine. Spawning in Netcode for GameObjects (Netcode) means to instantiate and/or spawn the object that is synchronized between all clients by the server.

sharp axle
sharp axle
sleek helm
hazy hollow
# sharp axle This just means that if you are spawning an prefab then you need to Instantiate(...

i see, im alrdy doing that then. I tried using an RPC to spawn my fireball like u suggested the other day but for some reason im getting a null exception (using a button to trigger the fireball() which then calls the rpc:

public void Fireball()
 {
     SpawnFireballRPC(finalPosition.x, finalPosition.y);
 }

[Rpc(SendTo.Server)]
 public void SpawnFireballRPC(float x, float y)
 {
     Debug.Log("Fire");
     GameObject spawnedFireball = Instantiate(fireballPrebab, new Vector2(x, y), Quaternion.identity);
     spawnedFireball.GetComponent<NetworkObject>().Spawn(true);
 }
#

the player prefab, projectile prefab, and even the UI button that just calls fireball() has a network object though

#

these functions are on the player's script

sage saffron
#

Question; Lets say two games are synced, to players in the scene. I as a player spawn a blue cube which is synced > the other player sees it. Now, as the other player lets say my game unlocks a new red ball and I spawn it > will the other player see it or will it be invisible? Does the red ball prefab need to be a object installed on the other clients game build?

#

The use case is the fact that I have TONS of DLC, which I dont want to be installed on all of the game builds, but such models and textures need to be seen by other players who dont have the DLC

tame slate
sage saffron
tame slate
sage saffron
tame slate
bitter rune
#

Hello! When loading scenes in a networked game, is there any way to "grab" the loading progress and display it in a progress bar? I have not found any exposed values regarding the actual loading progress of the scene transition.
NetworkManager.Singleton.SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
When not using networked code, I could typically load scenes asynchronously using Unity’s SceneManager.LoadSceneAsync This returns an AsyncOperation object that provides a "real" progress value (between 0 and 0.9 during loading, and 1.0 when the scene has been fully loaded). I could use this value to update a real progress bar. However, I have not found any way of doing this using the Networked Scene Manager.

fluid walrus
sharp axle
dire cosmos
#
private void interactCheck()
{
    foreach(KeyValuePair<ulong, NetworkClient> clientInfo in NetworkManager.Singleton.ConnectedClients)
    {
        NetworkObject p = clientInfo.Value.PlayerObject;

        if(Vector3.Distance(transform.position, p.transform.position) < interactionRange)
        {
            print("In range!");
            if(Physics.Raycast(transform.position, (p.transform.position - transform.position), out RaycastHit hit, interactionRange))
            {
                if (hit.transform == p.transform)
                {
                    print("hit a player");
                    p.GetComponent<Player>().showInteractionButton();
                    return;
                }
            }
        }
        p.GetComponent<Player>().hideInteractionButton();
    }
}

im trying to check if another player is close enough to interact with another, how should i go about this? since connectedclients is apparently server only? im very new to this

tame slate
#

Some people do the same with the IDs and use the ID to get the player objects when needed - either works.

dire cosmos
tame slate
sharp axle
dire cosmos
tame slate
dire cosmos
#

alright

#

is there a difference between Awake() and onnetworkspawn?

tame slate
sharp axle
dire cosmos
#

so the gameobject gets spawned on the client, then awake calls, then it gets spawned on the network and then networkspawn calls

fluid lintel
#

Do you guys know if something changed from Unity version 6000.0.23 to 6000.0.38? The automatic scene migration isn't working for my clients that connect after a game has started. It previously brought them to the correct scene that the host was in, but now it doesn't.

sharp axle
dire cosmos
#
private void interactCheck()
{
    foreach (NetworkClient client in PlayerManager.playerClients)
    {
        NetworkObject p = client.PlayerObject;
        //nullreferencerror next line
        if(Vector3.Distance(transform.position, p.transform.position) < interactionRange)
        {
            if(Physics.Raycast(transform.position, (p.transform.position - transform.position), out RaycastHit hit, interactionRange))
            {
                if (hit.transform == p.transform)
                {
                    p.GetComponent<Player>().showInteractionButton();
                    return;
                }
            }
        }
        p.GetComponent<Player>().hideInteractionButton();
    }
}```
```cs
public class PlayerManager : MonoBehaviour
{
    public static List<NetworkClient> playerClients = new List<NetworkClient>();
}
    public override void OnNetworkSpawn()
    {
        PlayerManager.playerClients.Add(NetworkManager.Singleton.LocalClient);
        print(PlayerManager.playerClients.ToString());
        base.OnNetworkSpawn();
    }

i now have this, but it gives a null error

#

for p.transform.position

fluid lintel
tame slate
tame slate
#

Then you can also expose that list to inspector to find your player objects easily when testing as well

dire cosmos
fluid lintel
sharp axle
sharp axle
fluid lintel
#

And like I said, it works for everyone on the initial load.. It's just when a client disconnects and reconnects that it has this issue.

viral ether
#

hello chat, I have questions on how to structure combat in my game
(I want it to be peer to peer pretty much, don't care about hacking or nothing, I rather want it to feel responsive for the player)

#

so running everything locally as much as possible~

#

so I have 2 functions, one to apply damage and one to receive damage

#

I wanted to know if I should make them (and which)
[Rpc(SendTo.Everyone)] or [ServerRpc]

#

[ Thread to not flood this chat ]

fluid lintel
#

Scene Sync Issues

#

Started a thread as well

viral ether
#

what reads as false

#

oh but you're only setting that on the host

#

you could maybe put that on StartClient / JoinGame or whatever your function is

viral ether
#
void UpdatePing()
{
    if (_networkManager.IsClient && _transport != null)
    {
        ulong serverId = NetworkManager.ServerClientId; // Get Server ID
        _currentPing = (int)_transport.GetCurrentRtt(serverId); // Get RTT in milliseconds
        _pingText.text = $"{_currentPing} ms";

        _pingIcon.sprite = PingIcon(_currentPing);
    }
    else
    {
        _pingText.text = "N/A";
        _pingIcon.sprite = PingIcon();
    }
}```
#

is that the current ping? or should I split it in half (_currentPing/2)

tame slate
viral ether
#

oh

#

so I should divide it by 2

tame slate
#

If that's what you wish to display, yeah - although the ping you usually see displayed in games is RTT

viral ether
#

oh yeah? hmm

#

is that true? 🤔

#

in League, Counter Strike, GunZ I get like 20-50ms I would be surprised if that's RTT

#

and not (RTT / 2)

sharp axle
# viral ether in League, Counter Strike, GunZ I get like 20-50ms I would be surprised if that'...

those times are likely to be RTT.

Multiplayer games operating over the internet have to manage adverse network factors that don't affect single-player or LAN-only multiplayer games, most notably network latency. Latency (also known as lag) is the delay between a user taking an action and seeing the expected result. When latency is too high, a game feels unresponsive and slow.

viral ether
#

or do I really have 70ms with my friend that lives close to me 🤔

#

which is not much, that's like 2 frames or less

tame slate
#

would have to disagree with ChatGPT on this one lol

#

especially since I can get it to say the exact opposite of what you just sent 😛

viral ether
#

🤔

#

well

#

whatever it is

#
void UpdatePing()
{
    if (_networkManager.IsClient && _transport != null)
    {
        ulong serverId = NetworkManager.ServerClientId; // Get Server ID
        _currentPing = (int)(_transport.GetCurrentRtt(serverId) / 2); // Get RTT in milliseconds
        _pingText.text = $"{_currentPing} ms";

        _pingIcon.sprite = PingIcon(_currentPing);
    }
    else
    {
        _pingText.text = "N/A";
        _pingIcon.sprite = PingIcon();
    }
}```
#

do you guys think it's bad if I put it in half?

tame slate
#

It's not bad perse, I just don't think it's relevant.

#

Because if those games do display one-way latency, I would guess that number isn't calculated by taking RTT/2

viral ether
#

that is true XD

#

I bet they do show send and receive separately

sharp axle
# viral ether ```csharp void UpdatePing() { if (_networkManager.IsClient && _transport != ...
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...

viral ether
#

nice wth

mint anvil
#

i probably already asked but forgor,
if i want to have a list with 2 ints (dictionary/keyvalue pair)
there is no networkdictionary or smth, right? (rpc's are problematic, if someone joins, the inventory of, for example a chest is not synced)

sharp axle
mint anvil
sharp axle
mint anvil
crimson sleet
#

Hi gang getting this error in n4e
[ClientWorld] RpcSystem received non-approval RPC Rpc[15394532049276111354, GoInGameRequestRPC] while in the Handshake connection state, from NetworkConnection[id0,v1]. Make sure you only send non-approval RPCs once the connection is approved. Disconnecting.
I was under the impression connection approval was an optional feature, which I have not knowingly enabled; is this not the case?

#

Also this only occurs when playing properly online to another pc

#

Multiplayer play mode is fine

tame slate
mint anvil
tame slate
#
public struct InventoryItem
{
    public int ItemId;
    public int Amount;
}
mint anvil
sharp axle
sharp axle
mint anvil
#

Kk!

viral ether
#

hello chat

#

so I have a damage cube for testing

#

[ Script here ]

#

and I was wondering how I could make it sync between all players... actually nvm

#

I can just turn this into an rpc function I assume

#

would it be like this?

mint anvil
viral ether
#

to make this toggle the same, for all players

sharp axle
crimson sleet
#

there are 3 references to goingamerequestrpc in my entire solution

#

once in the declaration

#

once in the server simulation foreach

#

and once in the client simulation to send it

viral ether
#

took me some time to figure it out but

#

this is what I ended up for my apply damage and receive damage

#

[ Script here ]

#

that is for my players, now for entities and environment hazards

#

the server will calculate the damage

#

This is on my environmental damage test cube

public void ApplyDamage(IReceiveDamage hit, IBlock block = null, IParry parry = null)
{
    if (!NetworkManager.Singleton.IsServer) return;

    float damage = Random.Range(1f, 5f); // Monster attack power

    bool wasBlocked = block != null && block.IsBlocking();
    bool wasParried = parry != null && parry.IsParrying();

    DamageData damageData = new()
    {
        DamageAmount = Random.Range(1f, 3f),
        Knockback = 1f,
        HitStun = 2f,
        DamageSource = transform.position
    };

    // Send damage to all clients
    hit.ReceiveDamageRpc(damageData, wasBlocked, wasParried);
}```
sharp axle
crimson sleet
#

yeah i tried running again and im getting the same error but says server world

#

not sure wtf happened tbh

#

but i get that error on the host

#

and this error on the client trying to connect

#

[ClientWorld] RpcSystem failed to deserialize RPC 'Rpc[10468798105839974107, Unity.NetCode.ServerRequestApprovalAfterHandshake]', as bits read (0 [0B] did not match expected (136 [17B])! Be aware that the incorrectly deserialized RPC may have still executed, but this connection will soon be closed.

#

Looking at the scripting api i can find no Unity.NetCode.ServerRequestApprovalAfterHandshake idk dafuq is happening and idk how to find out

umbral ivy
#

Hi all - asking a probably very common question but is mirror or photon best for my project? (multiplayer online card game) Does it matter? If not I'd probably go with Mirror but just wanted to get the feb 2025 opinion from ppl (or if theres a better 3rd option pls let me know)

viral ether
#

mirror is fine

#

or unity gaming services

#

better pricing and no need for Photon features,
except you could get practice using photon if you wanna make other games that could be better with it

#

TL:DR; Mirror imo is better for that project

#

I used Unity's Gaming Services to make mine, and felt super comfortable with good results

tame slate
sharp cliff
#

What's everyone's thoughts on supporting optimistic updates in a mobile game?

I think in web dev it's the norm, but all the mobile games I've tried out doesn't seem to utilize optimistic updates (e.g. Archero and Pokemon Go) -- for things like equipping items, leveling up items, consuming items, I see there's always a slight delay which indicates it waits for the server response and not doing any optimistic update.

I don't know if the added complexity/work of having to keep server logic and client optimistic logic in sync is worth it, and it also sort of removes the possibility of doing quick backend adjustments to logic, as the client will also need to be updated to change the optimistic update logic accordingly.

Is it common practice/industry standard for mobile games? I feel it isn't as I haven't seen many mobile games before that have optimistic updates.
(Talking about like "main menu" interactions, such as inventory management, etc, not real-time gameplay.)

sharp axle
sharp cliff
# sharp axle This sounds kinda like client prediction. It doesn't really seem worth it for me...

I think client prediction is another term (but more-so I think for real-time context). Optimistic updates are common in web dev, for example pressing "like button", immediately shows the button is liked and the like count is increased, before the server actually processes the request.

When optimistic updates fail, it will cause a rubber-band or roll-back effect, for example "like button" will revert to the state before you tried to like it.

Or if the backend logic and client prediction logic is not correctly aligned, it will cause a brief strange effect since the client expects something different then what the server does in the end.

I'm wondering if it's popular at all for games. I haven't played many mobile games, but from what I can tell, majority of them don't do optimistic updates. (again talking about UI/menu interactions and not real-time gameplay).

frosty hull
#

Hey guys, I'm having a little issue with Relay Services when using Unity Netcode for Entities. I've thrown together a small demo where I'm attempting to connect 4+ players to the same relay. I start the lobby, populate say 4 players, then set one client as the host and join the relay, then all other clients connect to the relay using the relay join code. All is well, it works great with 2 or 3 players ... but when I use 4 or more, the 4th client and any other client beyond that, fail to connect and I receive a Relay Allocation not found error. It works fine, the other two clients connect to the host, but the fourth onwards do not ... is this a limitation in Unity Relay or can anyone shed any light on why this might be happening?

Here's the output from the 4th client, the other 3 are working fine, no errors (host, client 1, client2) ... client 3 (4th player), gets this message. All other players beyond player 3 get this message too if they try to connect. The relay and lobby are both set to 4 players in this example.

TIA for your help.

snow imp
#

what do people use for servers usually with unity is it aws?

umbral ivy
haughty berry
#

I am making a multiplayer game and i would like to use both a model for client side (for example just arms and legs) and a server side what other players will see so (the full body) what would be best way to tackle this just make two gameobjects under the player and make one visible for server and one for client or is there another way?

haughty berry
#

allright so actually nothing to complicated?

ashen coral
#

easier way to think of it is having a togglable first person / third person view. It's exactly the same

obsidian mason
#

Hello

sharp axle
sly echo
#

Can i just delete the component from the game object if it isnt the owner instead of adding !IsHost on the code?

fluid walrus
#

network objects needs to have the same components on client and server usually

sly echo
#

Why is that?

#

They wont even run any code

fluid walrus
#

if you're on NGO, iirc the index of the component within the gameobject is part of how it identifies which component an RPC is sent to, so if you remove one that won't match

sly echo
#

Oooh

#

Ok thank you

#

What about disabling it tho?

sharp axle
sly echo
#

Ok thank you

sly echo
#

İt gives 400 bad request error when joining lobbies?

frosty hull
frosty hull
# snow imp what do people use for servers usually with unity is it aws?

I personally use Azure Playfab. There's a cool little package in Unity called CBS Cross-Platform Backend System which has a pretty comprehensive RPG example attached to it which uses Azure Playfab and Azure Functions to offer things like battle pass, inventory management, prize systems, authentication, cloud data and so much more ..... it's abcsolutely awesome. Even if you dont use the whole system, it's completely modular so take the parts you want, and negate those you dont.

frosty hull
frosty hull
charred pumice
#

Hi there, new to unity and trying to make 3d card game but for some reason trySetParent doesn't work and card instantiates in main scene rather than in hand anchor:
[SerializeField] GameObject cardPrefab;
[SerializeField] Transform handAnchor;

[ServerRpc]
void DrawCardServerRpc()
{
if (!IsServer) return;
GameObject newCard = Instantiate(cardPrefab);
NetworkObject netObj = newCard.GetComponent<NetworkObject>();
netObj.Spawn();

netObj.TrySetParent(handAnchor)
frosty hull
#

Are you setting the parent AFTER spawning the card?

#
[ServerRpc]
void DrawCardServerRpc()
{
    if (!IsServer) return;

    GameObject newCard = Instantiate(cardPrefab);
    NetworkObject netObj = newCard.GetComponent<NetworkObject>();

    netObj.Spawn(true); // Ensure the object is spawned properly before parenting

    // Attempt to set the parent
    if (!netObj.TrySetParent(handAnchor.GetComponent<NetworkObject>()))
    {
        Debug.LogError("Failed to set parent!");
    }
}```
charred pumice
#

let me try it

sharp axle
frosty hull
#

Just use child objects

sharp axle
#

I handle cards data as a network variable List and then instantiate the visuals locally

frosty hull
#

Or create an object which holds all references already and then just SetActive the child object that holds that image you want to show.

charred pumice
#

yeah i have something similar in the code, but hand anchor is nice so that you can do card fanning around 0 0 0 rather than global coordinates and you can move all of the card at once too

#
{
    [Header("Fan Settings")]
    [SerializeField] float maxArcAngle = 60f;  
    [SerializeField] float radius = 1f; 
    [SerializeField] float cardSpacing = 0.5f;

    private List<Card> cards = new List<Card>();

    public void AddCard(Card card)
    {
        if (card == null)
        {
            Debug.LogError("Tried to add null card to hand");
            return;
        }

        cards.Add(card);
        UpdateCardPositions();
    }
    public void RemoveCard(Card card)
    {
        cards.Remove(card);
        UpdateCardPositions();
    }

    private void UpdateCardPositions()
    {
        float totalWidth = (cards.Count - 1) * cardSpacing;

        float actualArcAngle = Mathf.Min(maxArcAngle, totalWidth * 2f);

        float startX = -totalWidth / 2f;

        if (cards.Count == 0)
        {
            Debug.Log("No cards to position");
        }
        else if (cards.Count == 1)
        {
            cards[0].MoveToPosition(new Vector3(0, 0, 0), Quaternion.Euler(0, 0, 0));
        } else {
            for (int i = 0; i < cards.Count; i++)
            {
                float xPos = startX + i * cardSpacing;
                float angle = Mathf.Lerp(-actualArcAngle / 2f, actualArcAngle / 2f, i / (float)(cards.Count - 1));

                Vector3 pos = new Vector3(xPos, 0, 0);
                Quaternion rot = Quaternion.Euler(0, angle, 0);

                pos.z = -Mathf.Abs(Mathf.Cos(angle * Mathf.Deg2Rad)) * radius;
                pos.y = Mathf.Sin(angle * Mathf.Deg2Rad) * radius;

                cards[i].MoveToPosition(pos, rot);
            }
        }
        
    }

i have this code for hand management, so should i just make it networkBehaviour

#

and sync only list of card?

sharp axle
# charred pumice and sync only list of card?

Card would also need to implement INetoworkSerializable. I usually just will sync a list a Card Ids. I can use a list of all cards in the game in a CardPool list/dictionary for lookups

charred pumice
#

yeah i have it

#

i have smth like this for cardManager

{
    if (_cardDatabase.TryGetValue(cardID, out CardData data))
    {
        return data;
    }

    Debug.LogError($"CardID {cardID} not found!");
    return null;
}

and network Serializable:

public class NetworkCard : NetworkBehaviour
{
    public NetworkVariable<NetworkString> CardID = new NetworkVariable<NetworkString>();

    public override void OnNetworkSpawn()
    {
        if (!IsServer) CardID.Value = "default_card";
    }
}
#

thank you for help

sharp cliff
uneven mural
#

I think I got a pretty easy problem to fix for you guys. I'm making a game with mirror & fizzysteamworks. If I play the game inside unity I can host a lobby when I got my steam open and start the game. However, I then send a copy of the game to my friend to test the lobby. He can open the game but can't click the host a lobby button. If he joins my lobby the spacewars games opens for him and he joins in a lobby there. Can someone help me with this?

viral ether
#

what do you guys think would be best for my enemies HP, I switch scenes and they respawn if I come back to the room where they are, like in old castlevania games and probably even mario lol

#

HP as a network variable, or syncronize the hp by the server to all players

#

as a local variable

sharp axle
sharp axle
viral ether
#

networkvariables = persist?

sharp axle
viral ether
#

^ cool!

#

so using networkvariable sounds like a good option

#

if one player gets in the scene, I want the scene and all enemies to load, so if another player also enters that room things are synchronized~

#

now if no player is in the room, I want to unload the scene and all enemies can respawn if I re-enter that room~

#

Network variable, floats are the way then?

sharp axle
viral ether
#

any example to that?

#

this is in my old project

#

so I would put LoadSceneMode.Additive

#

and that will only switch the scene to my current player?

sharp axle
viral ether
#

so I would be better off making all clients be in the same scene?

#

that would sacrifice my gameplay a lot but it's doable if needed

sharp axle
viral ether
#

so all in the same scene

sharp axle
#

Right. Then you could use network objects visibility if you need to hide rooms from other players

viral ether
#

thanks evilotaku

uneven mural
#

There should be something called "steam_appID.txt" with the steam app id 480 in it for replacing spacewars when testing

#

I think the problem is that I can't find that

sharp axle
uneven mural
#

It used to work fine tho, a player could join me in my lobby with the that app ID

#

The fizzysteamworks just changed, the appID used to be in the fizzysteamworks script and you could change it in the inspector in the script

#

now it is supposed to be in a text file

#

but I can't find the text file

sharp axle
#

Dunno anything about that. Might have to find the Fizzysteamworks discord server

frosty hull
#

You could use something like this example which would take groups of 'x' amount of players (I used 10 for this example), and when they connect they're assigned a group ID. These groups of players are then allocated a specific subscene to view when they are playing the game. This helps avoid the cost of 100+ players all interacting or instantiating projectiles etc, within the same scene, and instead creates multiple instances of the same subscene (or other subscenes if you wish), and then allocates them accordingly. Was this what you were looking for? Example below.

#

Matchmaker:

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

public class MatchmakingManager : NetworkBehaviour
{
    private static MatchmakingManager instance;
    public static MatchmakingManager Instance => instance;

    private void Awake()
    {
        if (instance == null) instance = this;
    }

    private List<ulong> unassignedPlayers = new();
    private Dictionary<int, List<ulong>> groups = new();
    private int groupCounter = 0;

    public void AssignPlayerToGroup(ulong clientId)
    {
        unassignedPlayers.Add(clientId);

        if (unassignedPlayers.Count >= 10)
        {
            // Create a new group of 10 players
            List<ulong> newGroup = new List<ulong>(unassignedPlayers.GetRange(0, 10));
            unassignedPlayers.RemoveRange(0, 10);

            // Store the group
            groups[groupCounter] = newGroup;

            LoadSubsceneForGroup(groupCounter, newGroup);
            groupCounter++;
        }
    }

    private void LoadSubsceneForGroup(int groupId, List<ulong> groupPlayers)
    {
        string subsceneName = $"GameSubscene_{groupId}"; // Unique scene name


        SceneManager.LoadSceneAsync("GameSubscene", LoadSceneMode.Additive).completed += operation =>
        {
            Scene loadedScene = SceneManager.GetSceneByName("GameSubscene");
            if (loadedScene.IsValid())
            {
                foreach (ulong playerId in groupPlayers)
                {
                    MovePlayerToSceneClientRpc(playerId, loadedScene.name);
                }
            }
        };
    }

    [ClientRpc]
    private void MovePlayerToSceneClientRpc(ulong playerId, string sceneName)
    {
        if (NetworkManager.Singleton.LocalClientId == playerId)
        {
            SceneManager.MoveGameObjectToScene(NetworkManager.Singleton.LocalClient.PlayerObject.gameObject, SceneManager.GetSceneByName(sceneName));
        }
    }
}
#

Modify the player connection handler

void Start()
{
    NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
}

private void OnClientConnected(ulong clientId)
{
    if (IsServer)
    {
        MatchmakingManager.Instance.AssignPlayerToGroup(clientId);
    }
}
sharp axle
tame slate
#

Kind of sounds more like he's designing the dungeon scenario. And unless these rooms are massive in file size and complexity, there's no reason to have them as scenes instead of prefabs.

ripe phoenix
#

Hi, does anyone know this error when I'm trying to StartHost using Netcode + Facepunch? The scene only has 1 NetworkManager

ripe phoenix
#

Will do when I get home

split hedge
#

has anybody dealt with this error?
Happens when you create a lobby

white pivot
#

Hello

#

I don't know where to put this question

#

but anyone here know how to apply unity editor personal license headless in unix?

sharp axle
sly echo
#

How can i get relay player from lobby player or thr opposite

#

İ have set the allocation id on the lobby player but what do i do next

sharp axle
sly echo
#

Ye but how do i do it

#

İn order to do that i have to get the relay player from lobby player

sharp axle
# sly echo Ye but how do i do it

I usually save the PlayerId as a Network Variable on the Player Object. Then when the player spawns I use its OnNetworkSpawn() to save itself to the Dictionary<clientID,PlayerID>

sly echo
#

Ok thank you

frosty hull
viral ether
#

sup chat

#

I'm trying to use Unity Transport for my player connection

#

and the host starts fine, however when I try to join I get this error

#

DisplayLobbyCode ~ means the player joined the session fine,
and it is displaying the code on both players

#

however, the player doesn't spawn, and in my unity client I'm getting that on the console

#

[tried with a friend also same issue]
tried all ways,
Unity to Client
Client to Client
Both ways in the same computer, as well as my firend in his computer and me in mine

#

[Thread with the whole script]

viral ether
#

I tried making it where it only uses Relay when needed

viral ether
#

but I get that error in the thread (only on the client, as a host it will start fine)

#

I went back to relay, like I had before, but this approach is somethiing I would love to have...

  • I'm not forwarding ports, maybe I have to?
sharp axle
viral ether
#

my code uses directconnect?

sharp axle
viral ether
#

hahahahah

#

I thought I was NAT holepunching

#

which is a term I heard that can be done

sharp axle
#

That is what relay is for

viral ether
#

so no freebies solution for me

jade ocean
#

Im trying to connect to the league API
Theyre telling me to add --insecure to it. But how does that translate to unity code?

sharp axle
viral ether
#

I'm at 7ccu already, maybe I'm doing something wrong lol

viral ether
#

Epic online services, would only work if I put my game in epic I assume

#

Which, I would only change the way a player create and join the lobby, everything else would stay the same?

tame slate
viral ether
#

👀 oh

#

I have another game up on steam

#

I think the ccu comes from that one

#

But if I get close to the limit, and still can't afford it with my games generated income

#

Switching to steam p2p shouldn't be too hard, I hope

tame slate
#

Relay: First 50 Average monthly CCU (approximately 2,160,000 connectivity minutes)

Averaging 50 people being on your game concurrently for a whole month means you likely have a player base that's at least 1,000+ if not more.

#

And you can see from the connectivity minutes that that's a lot of people playing your game for a considerable amount of time

viral ether
#

👀

#

1,000 playing for 36 hours a month on average

#

Yeah that's a lot lmao

#

Okay maybe relay is okay

#

So 1 ccu equals

#

720 hours of playtime pretty much?

tame slate
#

1 monthly average CCU, yeah

sharp axle
#

Yea. they really need to change those docs

alpine moss
#

I've got this code in a ability base class being inherited for each ability, but it's only running for the last ability instead of each attached to the character, I'm using mirror, does anyone know how to fix this?
the StartCooldown runs ok, but everything involved in TurnSystem_OnDecisionTurn only runs for the loast ability

weak plinth
#

I've only used Mirror some but it's been a few years

alpine moss
weak plinth
weak plinth
alpine moss
weak plinth
snow imp
#

can you just have colliders and some logic on the server

carmine geyser
#

Hello! I might need a bit of help I am having trouble wrapping my head around some logic (Netcode for GameObjects):

  • I have a game where players can have cosmetics
  • Theses cosmetics need to be networkobjects because some of them have transform that I want synched (like bones)
  • The way I was thinking about it was that the player instantiate their own skin, and it is reflected on other clients (like spawning a hat child of a head gameobject)
  • But you can only spawn network prefab on the server
    I am stuck there, is there a best practice for this type of need ?
crimson sleet
#

The concept of instantiating your own skin sounds rather macabre

tame slate
carmine geyser
tame slate
carmine geyser
hazy hollow
hazy hollow
#

love u

hazy hollow
#

public PlayerController GetPlayer(ulong? clientId = null)
{
    PlayerController[] players = FindObjectsByType<PlayerController>(FindObjectsSortMode.None);

    foreach (var player in players)
    {
        if (player.IsClient && !player.IsHost)
            return player;

        if (player.IsHost)
            return player;
    }

    return null; // No matching player found
}

Im having trouble with getting the correct player for a networked object to follow. It always seems to follow the host despite the client spawning the GO:

  [ServerRpc]
  public void SpawnShieldRPCServerRpc(ulong clientId, Vector2 spawnPosition)
  {
      if (shieldPrefab == null)
      {
          Debug.LogError("shield prefab is not assigned!");
          return;
      }

      GameObject spawnedShield = Instantiate(shieldPrefab, spawnPosition, Quaternion.identity);
      NetworkObject networkObject = spawnedShield.GetComponent<NetworkObject>();

      if (networkObject == null)
      {
          Debug.LogError("Spawned shield is missing a NetworkObject component!");
          return;
      }

      PlayerController player = GetPlayer(clientId);

      networkObject.SpawnWithOwnership(clientId);

      // Assign the shield to the player
      ShieldScript shieldScript = spawnedShield.GetComponent<ShieldScript>();
      if (shieldScript != null)
      {
          shieldScript.SetOwner(player);
      }
  }

sharp axle
viral ether
#

it's kinda crazy I'm getting 134ms (RTT)

#

on the same computer

#

should I look into something to improve this?

tame slate
viral ether
#

ye

#

(it's actually relay, it changes when I play)

tame slate
# viral ether ye

That's not the craziest RTT for Relay, but could be better. Have you checked where QoS is assigning your Relay server?

viral ether
#

who

viral ether
#

I don't see where it's being hosted here

viral ether
#

ehm

#

thanks

#

I was looking into that, I don't know how to change it however

viral ether
#

yeah, I was looking at that one XDDDDDDDDD

#

but still don't know how to change it... 90% of the time I don't understand documentation, even if I read it 3 times

tame slate
#

Just looks like a string parameter of .WithRelayNetwork()

viral ether
#

I see

#

I'm putting all the regions in, then I will test

#

thanks Dylarno

#

well that seemed to work nicely, thanks a lot 😄 let me test the ping now

#

XDDDDDDDDDDDDDDDDDDDD

tame slate
#

Nice

#

-40ms

viral ether
#

true

#

is there any way to verify the region I'm on?

#

something like this

tame slate
#

I don't think so. I thought QoS logged it somewhere when it does the autoselect, but I guess not?

viral ether
#

before, there was a reference to that in the RelayService

#

on the allocation of the relay server

#

but after the big multiplayer update I don't see it

#

well it does work, tried with Europe region~

sharp axle
viral ether
#

I think it is

#

but it's crazy, getting 130ms

#

on the same computer xD

sharp axle
#

its not too crazy to be honest. even on the same PC, both clients have to go through the relay server

viral ether
#

I thought relay was like this

#

both players will cross the relay bridge

#

to be on the same island

#

and then the bridge will be of no use anymore

sharp axle
#

Its actually really good for testing real world condition of your game

viral ether
#

wym

viral ether
sharp axle
# viral ether wym

Internet Service in the US is all over the place. A lot of folks on wifi only setups. If you are going to release it, the game needs to function at 200+ms pings

tame slate
ripe phoenix
#

Hi, what's the best way to handle syncing projectiles between host and client? Currently, my client sees the projectile vanish mid-air while traveling to the target. In the meantime, the host has already seen the projectile hit and removed it. I guess that's why the client sees the projectile disappear

sharp axle
viral ether
#

welp, I will put half the rtt

#

cause it's alarming seeing 130 ms in a game, when it feels fine

#

thoughts on that?

sharp axle
viral ether
#

okay, that makes sense

#

this would be super bad, right?

#

reading a NetworkVariable float like that on update

#

cause I don't remember how to do it xd

#

nvm, okayyy I see

#

documentation is a lot better now for multiplayer

#

compared to 2 years ago

ripe phoenix
# sharp axle You'll want to look into Distributed Authority and [Deferred Despawning](https:/...

So basically, deferred despawning makes the client projectile get destroyed a few frames after the server projectile, right? I see that in the documentation, there's a despawnTick. This is manually set, but I think there must be a way to determine the lag in milliseconds or something like that to pass into the deferringDespawn method. Manually setting a value doesn’t seem like the right approach because what if the client lags behind by 200ms, 500ms, or something like that? If I understand correctly

ripe phoenix
#

And using Distributed Authority will require Unity Gaming Services, right? My original idea is to use a client-host model so that players can host their own games without relying on any services. The only exception is Steamworks, which is used to create lobbies for players to join

sharp axle
viral ether
#

I see it's trying to start host twice

#

which... I don't see where that happens in my code 🤔

#

is it because it's inside "try"?

ripe phoenix
viral ether
#
async void Start()
{
    await UnityServices.InitializeAsync();

    if (!Unity.Services.Authentication.AuthenticationService.Instance.IsSignedIn)
    {
        await Unity.Services.Authentication.AuthenticationService.Instance.SignInAnonymouslyAsync();
        Debug.Log("Signed in successfully!");
    }

    _createLobbyButton.onClick.AddListener(OnCreateLobby);
    _joinLobbyButton.onClick.AddListener(OnJoinLobby);
    _openLobbyMenuButton.onClick.AddListener(OpenLobbyMenu);
}```
```csharp
public async void OnCreateLobby()
{
    CloseLobbyMenu(true);
    _connectionTypeText.text = "";
    _connectionTypeText.color = new(1f, 0.5f, 0f);
    var selectedRegion = RelayRegions[_selectedRegionIndex];

    try
    {
        var options = new SessionOptions
        {
            MaxPlayers = 4,
        }.WithRelayNetwork(selectedRegion); // DEVOUR

        var session = await MultiplayerService.Instance.CreateSessionAsync(options);
        _currentSession = session;

        NetworkManager.Singleton.StartHost();
        DisplayLobbyCode(session.Code);

        CloseLobbyMenu(true);
    }
    catch (System.Exception e)
    {
        Debug.LogError($"Error creating room: {e.Message}");
    }
}```
tame slate
sharp axle
sharp axle
viral ether
#

so I should remove listener?

#

on disabled or something? lol

sharp axle
viral ether
#

it's not... xd

#

I only suscribe to it on start with "addlistener"

sharp axle
viral ether
#

with createsession?

#

thanks! that was the problem c:

viral ether
#

do NetworkVariables have a different naming convention?

#

I heard events are EXAMPLE_EVENT

#

which I find crazy and ugly so I don't use it

_privateVariable
localVariable
PublicVariable

^ those are the conventions I know and use so far

fluid walrus
tame slate
sharp axle
cobalt python
#

Hi, guys. Using PUN. Have a problem loading level on other than master client. Other players can connect, spawn in the same room where the master client is. Everyone sees each other. But, during loading the level, others cant see the progress bar. It is just skipped as the logic is in OnJoinedRoom(). But, it simply not triggered on other clients while connecting. What can be the problem? Here is the code, and it is called only on master client:

public override void OnJoinedRoom()
{   
    if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
    {
        Debug.Log("We load the 'Room for 1' ");             
        PhotonNetwork.LoadLevel("Room for 1");              
    }

    connectingLabel.SetActive(false);

    loadingLevelLabel.SetActive(true);
    loadingScreen.SetActive(true);
    progressBar.gameObject.SetActive(true);

    Coroutine loadLevelCor = StartCoroutine(LoadLevelAsync());
}
weak plinth
viral ether
#

@sharp axle you were mentioning, putting everything on the same scene and switching the visibility

#

would be the most logical approach for multiplayer, but wouldn't it be rough having a complete game in the same scene?
wouldn't all objects in it have to be loaded? 🤔

sharp axle
viral ether
#

well...

#

do you have maybe an example script for that? not sure if you have done it before

#

I would love to start testing that out

viral ether
#

I assume putting areas/rooms as prefabs is one thing, but I wouldn't know how to load it and unload it when no players are in that area xD

#

what should I put here, let's say I destroy an object and a player joins

#

for that player to have that object destroyed as well

sharp axle
viral ether
#

or I assume, I should not destroy breakables and enemies, but rather disable them

#

so I can enable for them to respawn (?)

sharp axle
#

I would use Triggers if you when you need to load new rooms

viral ether
#

yes

#

more than likely doors but, I wouldn't know what the scripts would look like

sharp axle
grizzled vector
#

Hi. I have car that i want to be able to enter / exit with host player and client player (peer to peer, netcode for gameobjects). I'm having problem where i can't detect car with raycast with the client player. For host everything works, but client is not detecting car at all with the raycast. Do i need to do this some other way? Code for raycast is after if (!IsOwner) return;

sharp axle
grizzled vector
hazy hollow
#

im having trouble syncing a spawnedPrefab to position itself on top of its parent's position. I thought the Instantiate()'s spawnPosition parameter would be out of sync when actually spawning in the prefab so I tried resetting its localPosition to 0 after setting it as a child of the player but as the image shows, there's still some offset. The parenting works and the prefab does move with the player, however.

[ServerRpc(RequireOwnership = false)]
public void SpawnShieldServerRpc(ulong clientId, Vector3 spawnPosition)
{
    if (!IsServer) return; // Ensure only host executes

    GameObject spawnedShield = Instantiate(shieldPrefab, spawnPosition, Quaternion.identity); // the prefab to spawn
    NetworkObject shieldNetObj = spawnedShield.GetComponent<NetworkObject>(); // the spawned Prefab's networkobjct component for logic (movement)
    NetworkObject owner = GetPlayer(clientId); // the player that requested this

    // reposition (potential network delay from Instantiate(spawnposition)
    Vector3 playerPosition = owner.transform.position;
    spawnedShield.transform.position = playerPosition;

    // Spawn with ownership to the client who requested the shield
    shieldNetObj.SpawnWithOwnership(clientId);

    // Parent to the player, to always stay on top of the parent
    shieldNetObj.TrySetParent(owner, false);

    // Reset localposition if there's an offset due to network delay
    spawnedShield.transform.localPosition = Vector3.zero;

    StartCoroutine(DespawnSpell(shieldNetObj, shieldLifeSpan));
}