#archived-networking

1 messages · Page 40 of 1

reef comet
#

It looks like I can use the InputAction.CallbackContext to get the device through control.device so I am going to try that out instead of the PlayerInputManager

#

By binding some join button press to a function

reef comet
#

I got it working, thank you for the help!

sharp axle
reef comet
#

I detected using a PlayerInputManager when a join button was clicked on a device. I then used the InputAction.CallbackContext.something.device to get the device

celest spire
#

@small saddle so how do i show torch and light to all player?

small saddle
celest spire
small saddle
# celest spire

And if you search your hierarchy, is there 2 "flashlight" objects?

celest spire
small saddle
# celest spire

Ah, so in your hierarchy, it looks like your second players "Camera" (which holds your "flashlight" as a child) is disabled - you probably want to use .isMine to toggle the camera off instead of disable it entirely, or make the flashlight not a child of the second players camera

celest spire
small saddle
#

Np

sacred flame
#

I have this code.

    public void InvokeStart()
    {
        StartGameRpc();
    }
    [Rpc(SendTo.Server)]
    void StartGameRpc()
    {
        Debug.Log("Game is ready to start");
        StartGameClientRpc();
       
    }
    [Rpc(SendTo.ClientsAndHost)]
    void StartGameClientRpc()
    {
        Debug.Log("Game has started");
        gameUI.SetActive(true);
        hostUI.SetActive(false);
        memberUI.SetActive(false);
    }

InvokeStart is being called by another class in the client
However, once InvokeStart is called, it looks as if the StartGameRPC is being executed locally instead of on the host [i.e. console logs appear in the client instead of host], and the StartGameClientRpc definitely does not fire on the host [no changes happen]. What could be causing this?

tame slate
sacred flame
lyric dagger
#

im working on some code for update positions (Yes i know its not the most efficient) and im not sure if i need to update the positions in a ClientRPC since the positions are being stored on networked variables.

#

also i fixed the method name

tame slate
lyric dagger
tame slate
lyric dagger
#

alright thanks

tame slate
#

I'm assuming you're actually moving those transforms on the server in other code?

lyric dagger
#

though they use NetworkVariables

tame slate
#

All your code is doing is syncing the server's position to everyone, including the server itself. You're not moving the transform anywhere.

sharp axle
lyric dagger
lyric dagger
#

Alright i fixed my whole script.

sharp axle
celest spire
#

Hi all, I'm making a multiplayer game. Everything was fine until I changed the character model.. now it doesn't move anymore. Any advice?

celest spire
#

nvm solved it.. thank you

iron dagger
#

👋

sharp axle
tame slate
twin grove
#

how to kick a player from the lobby in Facepunch.Steamworks???

twin grove
rugged spire
#

if I want to put the player name above the player's head. do I need to make a an rpc call at OnNetworkSpawn to get the players names and change the text locally? Or is there a better way?

tame slate
rugged spire
tame slate
rugged spire
tame slate
rugged spire
# tame slate You have to use one of the FixedString types

But how can I access their username without an rpc? the OnConnectionEvent have 2 parameters which are a NetworkManager arg1 and the data named arg2. can I access the name from the passed NetworkManager?
like this:
arg1.Singleton.AuthenticationService.GetPlayerName() ?

#

I'm using AuthenticationService to store players name

tame slate
#

I wouldn’t use OnConnectionEvent. Just OnNetworkSpawn of wherever this NetworkVariable is going to be.

rugged spire
celest spire
#

Hi. I'm using Unity with URP and I have a Spot Light attached to a lamp. The light only seems to illuminate the player model, but not the surrounding environment or the house interior. The light also appears with a weird blue/purple tint, and it's not casting realistic lighting in the scene. I checked my lighting settings, and I'm not sure if Global Illumination or baking is set up correctly. How can I make the lamp actually light up the environment properly?

muted sorrel
#

I'm trying to do a system with pickup and drop, for some reason I keep having an ownership crash when my player 2 tries to pickup the object. When I change it back to IsOwner I keep having issues of my player 2 not being able to move the object. (comments are mine not ChatGPT, I'm trying to do my best to learn)

[SerializeField] private HoldingObjectType _holdingObjectType;
    
    // To allow clients/server to know if you can pickup the object or not, shared variable
private NetworkVariable<bool> _isHeld = new NetworkVariable<bool>(
    false,
    NetworkVariableReadPermission.Everyone,
    NetworkVariableWritePermission.Server
);


private Collider _collider;
private Rigidbody _rb;
private Transform _playerHolder;

// Getters
public NetworkVariable<bool> IsHeld => _isHeld;
public HoldingObjectType HoldingObjectType => _holdingObjectType;

void Update()
    {
        if (IsOwner && _isHeld.Value && _playerHolder != null)
        {
            transform.position = _playerHolder.position;
        }
    }
    
// When player is close to the object and press E to interact they ask to pick it up to the server if it is available
public void RequestPickup(Transform player)
{
    PickupServerRpc(NetworkManager.Singleton.LocalClientId);
}

// The server rpc will give the ownership of the object to the one who requested it
[ServerRpc(RequireOwnership = false)]
void PickupServerRpc(ulong clientId)
{
    // Return if the object is held by other players
    if (_isHeld.Value) return;
    
    NetworkObject.ChangeOwnership(clientId);
    if (IsServer)
    {
        _isHeld.Value = true;
    }
    PickupClientRpc(clientId);
}
#

If I need to share more please feel free to tell me thank you

#

Here's the pickup client rpc :

// We call the client rpc which will update the position for everyone
[ClientRpc]
void PickupClientRpc(ulong clientId)
{
    // Attach to player's hand
    NetworkObject playerNetwork = NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject;
    if (playerNetwork != null)
    {
        PlayerInteractController playerController = playerNetwork.GetComponent<PlayerInteractController>();
        _playerHolder = playerController.HoldTransform;
        transform.position = playerController.HoldTransform.position;
        _collider.enabled = false;
        if (_rb != null)
        {
            _rb.constraints = RigidbodyConstraints.FreezeRotation;
            _rb.useGravity = false;
        }
        
        playerController.OnPickupConfirmed(this);
    }
}
#

My object is already on the scene, am I supposed to spawn it ? (nvm it changed nothing)

sharp axle
tame slate
#

You also seem to be editing transform.position in the PickupClientRpc. If the object has a NetworkTransform, only the authority/owner should be setting the position.

rugged spire
#

Hi. I wanted to make a networkVariable storing players names. So when someone join new he sets other players name above there heads. but I got this error. The game can have a maximum of 8 players

tame slate
#

Also not sure if there's a difference between serialization support between FixedString and FixedStringBytes.. documentation examples use FixedString

rugged spire
heavy swan
#

Howdy folks! Is it possible to have two clients running from the same instance? I currently have my game entirely ignoring netcode when in local play, but if there's a way that I could have an internal server and both clients running at once that would be way better for organization.

sharp axle
heavy swan
#

I don't mean just for testing, I mean for the final build.

#

I have a local gameplay mode and an online gamplay mode. I want to see if I can make it so that the local "couch" multiplayer still uses netcode for gameobjects.

sharp axle
fluid walrus
#

probably not worth it though haha

tame slate
#

Definitely not worth it.. also going with evilotaku's solution means you get to support multiple local players connecting to an online game as well

heavy swan
#

gotcha, that makes sense. thank you all!

reef comet
#

I structured my online play so that you could have multiple local players joining on the same device for an online game

#

and that meant that singleplayer, local multiplayer and online multiplayer were covered by the same code

heavy swan
#

That makes a lot of sense for a game like that, but since my game is only two players I'll probably stick with just not using netcode for local play.

#

I also realized when going through that that it is not actually really because of not using netcode, and that my old code is just egregiously disorganized

reef comet
#

Ah fair

trail ibex
trail ibex
# trail ibex Why am i still getting this error man. WeaponThrowableItem script: https://past...

and just in case method that spawns it in:

[ServerRpc]
public void DropWeaponServerRpc()
{
    if (unlockedWeapons.Count == 1) return;
    int weapon = unlockedWeapons[0];
    unlockedWeapons.RemoveAt(0);

    GameObject obj = Instantiate(NetworkDatabase.Instance.GetWeapon(weapon).Get<PlayerData>().pickupPrefab, gameObject.transform.position, Quaternion.identity);
    obj.GetComponent<NetworkObject>().Spawn();
    WeaponThrowableItem thrownWeaponItem = obj.GetComponent<WeaponThrowableItem>();

    thrownWeaponItem.rb.velocity = new Vector2(5, 12);
    thrownWeaponItem.rb.gravityScale = 4;
    thrownWeaponItem.isPickUppable = false;
    StartCoroutine(thrownWeaponItem.DespawnSelf());

}
#

last line is where the destroyself coroutine is started

#

nvm i fixed

trail ibex
#

has anyone used tiles to spawn network objects

sharp axle
trail ibex
tame slate
trail ibex
#

i already have a network spawner prefab that fully works, what the script did is it spawned an object on network spawn if server, and if not, destroy theg maeobjkect, also server check in update and if server spawns a an item every x amount of seconds

trail ibex
#

keep giving this error though

tame slate
trail ibex
#

but yea i still get this

sharp axle
trail ibex
#

youmeant something like this right

#

wait no

#

like this

#

maybe something to do with my netcode version

#

wait no, i got the latest

#

yea i just dont know

dark umbra
#

Hey, for some reason my RPC doesn't get called on every client that is not the host, At first I thought It was an ownership problem, but I checked that the caller owns the networkbehaviour and yet it still does not call the procedure on the host. My code:

#
public class WeaponSwitch : NetworkBehaviour
{
    public enum WeaponType
    {
        Primary,
        Secondary,
        Tertiary,
    }

    public NetworkVariable<WeaponType> ActiveWeapon = new 
        NetworkVariable<WeaponType>(WeaponType.Primary, 
        NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);

    public Weapon primary;
    public Weapon secondary;
    public Weapon tertiary;

    private InputSystem_Actions input;
    private InputAction secondaryButton;
    private InputAction tertiaryButton;

    public override void OnNetworkSpawn()
    {
        if (IsOwner)
        {
            print(IsOwner);
            input = new InputSystem_Actions();

            secondaryButton = input.Player.SecondaryWeaponSwitch;
            tertiaryButton = input.Player.TertiaryWeaponSwitch;

            secondaryButton.performed += OnSecondaryButtonPerformed;
            tertiaryButton.performed += OnTertiaryButtonPerformed;

            secondaryButton.Enable();
            tertiaryButton.Enable();
        }
    }
    private void OnSecondaryButtonPerformed(InputAction.CallbackContext ctx)
    {
        if (ctx.action.WasPressedThisFrame())
        {
            if (ActiveWeapon.Value == WeaponType.Secondary)
            {
                ActiveWeapon.Value = WeaponType.Primary;
            }
            else
            {
                ActiveWeapon.Value = WeaponType.Secondary;
            }
            print($"[{transform.root.name}] {ActiveWeapon.Value}");
            PrintActiveWeaponTypeServerRpc();
        }
    }

    [ServerRpc]
    private void PrintActiveWeaponTypeServerRpc()
    {
        Debug.Log($"[{OwnerClientId}] {ActiveWeapon.Value}");
    }
}```
#

The network object that is connected to the network prefab:

#

(Should have mentioned that this is netcode for game objects)

sharp axle
dark umbra
sharp axle
#

But RPCs will be sent before the network variable updates

dark umbra
sharp axle
dark umbra
#

it's not, it works locally, but not when networked to the server

sharp axle
#

As long as the network object is spawned and active, an RPC will get sent

dark umbra
#

The object is spawned when a client connects to the server, as it is the player object. Is this enough?

sharp axle
#

Yes

dark umbra
#

so I'm confused. The inputs definitely are working as to be expected, but the RPC does not get called. This is my issue.

dark umbra
sharp axle
dark umbra
sharp axle
dark umbra
#

It's just weird, the host client can use the RPC, but not other connected clients

sharp axle
dark umbra
sharp axle
dark umbra
#

The script isn't getting disabled anywhere unfortunately

#

Wait I'm an idiot

#

It had to do with the fact that I was deleting a network object prematurely

#

and it wouldn't sync

#

sorry, thanks for the help

rugged spire
#

Does anyone knows why it doesn't subscribe to the OnValueChange?

#

this is the variable

#

nothing is printed

sharp axle
rugged spire
rugged spire
#

it shouldn't make a difference

sharp axle
delicate parrot
#

do network variables support lists like that?

sharp axle
#

They do

rugged spire
sharp axle
rugged spire
#

for some reason when I subscribed for the event first time. there was no auto complete

delicate parrot
#
Using collections with NetworkVariables
You can use NetworkVariables with both managed and unmanaged collections, but you need to call NetworkVariable<T>.CheckDirtyState() after making changes to a collection (or items in a collection) for those changes to be detected. Then the OnValueChanged event will trigger, if subscribed locally, and by the end of the frame the rest of the clients and server will be synchronized with the detected change(s).

NetworkVariable<T>.CheckDirtyState() checks every item in a collection, including recursively nested collections, which can have a significant impact on performance if collections are large. If you're making multiple changes to a collection, you only need to call NetworkVariable<T>.CheckDirtyState() once after all changes are complete, rather than calling it after each change.

relevant?

rugged spire
#

I had to make the functions and type the parameters manually

delicate parrot
#

i mean i only just read it so no clue but looks right aha'

#

you might have a reason to not want them but just incase, NetworkLists are an actual thing NGO has aswell

rugged spire
#

what is this for? the forceCheck

rugged spire
#

but I wrote the logic already. there are 3 lists

#

it will take time to change them 🫠

rugged spire
#

It worked

#

Thank you

sharp axle
#

Yea. when you can List in a Network Variable you have to call CheckDirtyState() for it to update

trail ibex
sharp axle
trail ibex
#

The object that spawns (from the tile prefab aka the networkspawner) I believe it wasn't parentes to anything

sharp axle
trail ibex
#

Hmm perhaps it spawns the prefab as a child of the tile first? Then it tried to unparent

polar scaffold
#

im using netcode and i was wondering if there is a way to have 2 builds running at once in the editor instead of having to build it

#

video im watching is manually building each time
i feel this is a good channel to post as people here will probably have the same problem

polar scaffold
#

i found the multi-player play mode

uncut zodiac
#

Hi! I have a multiplayer game made using Unity and NGO with the multiplayer widgets. Been working for 5 months on it. Testing it through the editor as host and client and got it working just fine.
Using client server as topology and Unity Relay.

When I finally made a build (which I guess I should have made way sooner)
Some functions dont work for the client running the build. The host running the build works as supposed.
The strange thing is why it works perfectly when playing together in editor but not in the build version.

Anything obvious I'm missing?

sharp axle
uncut zodiac
#

aye, building a debugging build right. It takes a whole of a lot more time than usual though

trail ibex
#

does instantiating a tile prefab with a network object prefab cause it to be automatically unparented from the tile map becuase the tile map isnt a netowrk obj?

tame slate
sharp axle
#

If its a tile network object then you would have to spawn it at the root level then reparent

trail ibex
#

i see

#

do tile maps have an option to not spawn tile prfabs as a child?

sharp axle
trail ibex
#

Hmm I'll play around with that tomorrow and come back with the results

crimson sleet
#

Hi gang

#

just updated lobby

#

where I was previously accessing _currentLobby.Players[i].Data to get the player names to set on the UI

#

this is now null

#

.Data is null

#

i can grab the player grab their id yada yada but the data object is just null for some reason

#

what has changed in recent 2 months ish of updates that makes this the case

#

idk if there is a nice changelog but the unity3d docs website is down so i can't even check

#
    {
        UpdatePlayerOptions playerOptions = new();

        playerOptions.Data = new Dictionary<string, PlayerDataObject>()
        {
            { "Display Name", new PlayerDataObject(
                visibility: PlayerDataObject.VisibilityOptions.Public,
                value: displayName) }
        };

        await LobbyService.Instance.UpdatePlayerAsync(_currentLobby.Id, AuthenticationService.Instance.PlayerId, playerOptions);

        _lobbyCodeText.text = _currentLobby.LobbyCode;
        _lobbyNameText.text = _currentLobby.Name;
        _lobbyPlayercountText.text = _currentLobby.Players.Count + " / " + _currentLobby.MaxPlayers;

        for (int i = 0; i < _currentLobby.Players.Count; i++)
        {
            UnityEngine.Debug.Log(_lobbyPlayerDisplayNames[i]);
            UnityEngine.Debug.Log(_currentLobby.Players[i]);
            UnityEngine.Debug.Log(_currentLobby.Players[i].Id);
            UnityEngine.Debug.Log(_currentLobby.Players[i].Data);
            _lobbyPlayerDisplayNames[i].text = _currentLobby.Players[i].Data["Display Name"].Value;
        }

        SubscribeToLobbyEvents();
    }```
#

checked version history on the package manager and there isn't even anything remotely relevant to this

#

so idk why tf this would change

tame slate
#

I don't think anything related to that changed, but shouldn't you be using the return value of UpdatePlayerAsync?

#

_currentLobby = await LobbyService.Instance.UpdatePlayerAsync(_currentLobby.Id, AuthenticationService.Instance.PlayerId, playerOptions);

crimson sleet
#

yeah that works

#

if that's how it's meant to be done then I'm very confused cause that seems like a massive thing that I just haven't been doing

#

if we need to regrab the lobby every time something changes

#

and it's worked until now

#

very weird

tame slate
#

That's how it's always been to my knowledge, not sure how your code was functioning before. _currentLobby is your own cache of the lobby, so Lobby has no knowledge of it and is not going to know to update it automatically.

crimson sleet
#

interesting

#
    {
        foreach (KeyValuePair<int, Dictionary<string, ChangedOrRemovedLobbyValue<PlayerDataObject>>> player in changes)
        {
            foreach (KeyValuePair<string, ChangedOrRemovedLobbyValue<PlayerDataObject>> change in player.Value)
            {
                if (change.Key == "Display Name")
                {
                    for (int i = 0; i < _currentLobby.Players.Count; i++)
                    {
                        _lobbyPlayerDisplayNames[i].text = _currentLobby.Players[i].Data["Display Name"].Value;
                    }
                }
            }
        }
    }```
#

how can I grab a new cache of the lobby in a situation like this?

#

this also has broken after updating

tame slate
#

You wouldn't really need to in all honesty. change.Value would give you the updated Display Name

crimson sleet
#

yeah I just did this way for ease because I have no stored value of which tmpro element is for which player

#

so i just refresh the whole list

tame slate
#

If you're subscribed to OnLobbyChanged it should pass through ILobbyChanges which you can then call .ApplyToLobby(_currentLobby) on

tame slate
crimson sleet
#

yeah that works

#

thanks a lot

green timber
#

hey good evening, i am having a problem with the new input system and Netcode for Gameobjects.
the problem is not related to 1 player controlling another as that seems to be the most common one, but the problem comes when i try to change scenes via:

    {
        GUI = GetComponent<UIDocument>().rootVisualElement;
        startHostButton = GUI.Q<Button>("StartHost");
        startClientButton = GUI.Q<Button>("StartClient");
        hostIpAddressInput = GUI.Q<TextField>("AddressInput");

        startHostButton.clicked += HandleStartHost;
        startClientButton.clicked += HandleStartClient;
    }

    void OnDestroy()
    {
        startHostButton.clicked -= HandleStartHost;
        startClientButton.clicked -= HandleStartClient;
    }

    void HandleStartHost()
    {
        NetworkManager.Singleton.GetComponent<UnityTransport>().ConnectionData.Address =
            hostIpAddressInput.value;
        NetworkManager.Singleton.StartHost();
        HandleStarted();
    }

    void HandleStartClient()
    {
        NetworkManager.Singleton.GetComponent<UnityTransport>().ConnectionData.Address =
            hostIpAddressInput.value;
        NetworkManager.Singleton.StartClient();
        HandleStarted();
    }

    void HandleStarted()
    {
    --->  NetworkManager.Singleton.SceneManager.LoadScene(gameScene.ScenePath, LoadSceneMode.Single);
    }
}```
the project is a joint effort between some friends so i don't know exactly how my friend has implemented the netcode, the problem that arises when you change scenes is that no inputs are being recognized (log prints vector2 as 0,0 regardless of input), while they would be before changing. there is no code (that we have made) that moves the player obj between scenes so i thought that could be the problem, but even when doing additive loading the problem persists, any ideas on why this could be happening?
sharp axle
green timber
#
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityHFSM;

public class PlayerController : NetworkBehaviour
{

    #region InputSystem
    [SerializeField]
    internal InputActionReference IS_Movement;
    [SerializeField]
    private PlayerInput m_PlayerInput;
    #endregion

    private double lastGroundPoundTime = 0;
    private double lastSlideTime = 0;

    void Awake()
    {
        Instance = this;
        //m_PlayerInput = GetComponent<PlayerInput>();
        m_PlayerInput.enabled = false;
    }

this disables it (it already starts disabled)

#
   {
       m_PlayerInput.enabled = IsOwner;
       base.OnNetworkSpawn();
   }

   public override void OnNetworkDespawn()
   {
       m_PlayerInput.enabled = false;
       base.OnNetworkDespawn();
   }```
and enables if ownerr
green timber
spring pilot
#

hey guys, sorry for the stupid question but is there any way for me to easily just call a function in the lobbyservice to get the id someone used to join the relay server using their lobby ID?

sharp axle
sharp axle
spring pilot
sharp axle
green timber
spring pilot
# sharp axle I don't think onPlayerJoined will give you a client ID. I usually will make a Ne...

and I suppose this is probably a dumb question but, if there was someone with a modified client, would they be able to send a random int instead of their actual ID making it impossible for someone hosting a game to kick them? my (albeit shallow) understanding is that Network Variables use Server RPC so a hacker would just be able to send a bogus number instead of their actual PlayerId? sorry I'm pretty uneducated about netcode

sharp axle
green timber
#

you think it might be the source of the problem?

sharp axle
green timber
#

cool, any idea of how i could do a bandai fix on this for now?
i didnt read the documentation and the one responsible for this part is working right now

sharp axle
green timber
#

thanks a lot man! will do and try to see if the problem persists

rugged spire
#

How does networkManager assigns IDs ?
I'm making a game where the max capacity is 8 players. and each player spawns in a fixed location according to his network ID (Assuming ids are between 0-7). I activated the Reuse old IDs in network manager and set the time to 5 seconds after no use. But some ids get skipped when a host leaves. create a new game and clients join.

tame slate
rugged spire
#

some items are not allowed to be used unless you have the specific id

tame slate
sharp axle
sharp axle
rugged spire
#

what is the difference ?

sharp axle
#

every single network object in the scene gets a unique network id

rugged spire
#

Oh...

green timber
# sharp axle Comment out that static Instance. Anything needing it should call GetComponent<P...

so i didnt use that gameobject anymore, and created a dummy one
very simple

using System.Runtime.CompilerServices;
using Unity.IO.LowLevel.Unsafe;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Rendering;

public class PlayerMove : NetworkBehaviour
{
    public Rigidbody2D rb;
    public float moveSpeed;
    private Vector2 _moveDirection;
    public InputActionReference move;
    public InputActionReference fire;

    void Update()
    {
        _moveDirection = move.action.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        Debug.Log(_moveDirection);
        rb.linearVelocity = new Vector2(_moveDirection.x * moveSpeed, _moveDirection.y * moveSpeed);
    }
    private void Fire(InputAction.CallbackContext obj)
    {
        Debug.Log("pew");
    }
    private void OnEnable()
    {
        fire.action.started += Fire;
    }
    private void OnDisable()
    {
        fire.action.started -= Fire;
    }
}

it still has the same problem of not working anymore after the event

#

---> NetworkManager.Singleton.SceneManager.LoadScene(gameScene.ScenePath, LoadSceneMode.Single);
is there any flags i need to turn on, on either the network manager or the player character?
i have seem some documentation and throubleshootings online and nothing so far that went over this specific problem
it the Netcode for objects badly implemented or something else entirely ?

#

it seems such a big thing to go wrong so easily

sharp axle
sharp axle
#

Its about write permissions for the variable/component in question. client authority means that the server will accept any changes from the owning client no questions asked. So yea cheating could be possible

#

well, write permissions give the owner a certain amount of control. There are some things that the client will never be able to do like Spawn network objects.

twin grove
#

Has anyone done a lobby kick using Facepunch + Netcode?

sharp axle
hybrid dew
#

if host starts a game
then a manager spawns trees and rocks randomly

then client joins
what's the best approach?
to save all the locations of those spawned prefabs (that don't move nor can be farmed/destroyed)
and instantiate them on client when client connects
or
just make them a network object with network transform?

sharp axle
slow geyser
#

Hey everyone. I've got a question about host migration in netcode. I can see that the older net package had a host migration manager, but I can't find any info on how it works in netcode. Can you share some links to documentation or examples?

tame slate
slow geyser
tame slate
slow geyser
#

Hey. How often does the server send updates to NetworkVariable? Is it every frame or once per value change?

hybrid dew
#

in the case of rpc and using server authoritative

how does the server know which client is which?
i see multiple tutorials where the user will send rpc to server with his input
then the server sends the position back with a client rpc

hybrid dew
#

and hopefully it's optimized that if it hasn't changed, it wont send it

delicate parrot
magic shadow
#

https://pastebin.com/ZHjQR3nb

what the hell is wrong with my code, my gun keeps on firing when i reload and once it reloads the logic works fine, but if I try putting a boolean isReloading, no matter what way, shape or form, it bricks up (how? when I reload, after the reload animation the gun becomes completely unusuable, cant fire, reload, its stuck)

#

my blood pressure has never been this high because of fucking coding, i tried asking chatgpt and guess what, nothing, nada

#

what could POSSIBLY be wrong?

tame slate
tame slate
magic shadow
tame slate
#

currentAmmo and currentMagazineCapacity should most likely be NetworkVariables to make syncing their values simple.

magic shadow
tame slate
magic shadow
#

I really dont understand why NOTHING works in my code after that courontine change

#

i tried setting the variables into network ones, nada

#

same issue

#

do i really need to rewrite literally everything and start over?

tame slate
magic shadow
tame slate
magic shadow
#

weapon script - https://pastebin.com/9n5Nbd1v
player fire - https://pastebin.com/XMQGBtrk

I tried doing it manually, got frustrated and decided to ask chatgpt and theres still the same issue that i had pretty much

magic shadow
tame slate
magic shadow
#

of not being able to reload after shooting that is

tame slate
#

I would probably take a step back and just trying to work on making shoot, reload and ammo mechanics that just work with a button and some Debug.Logs.

#

Everything else is just going to make issues harder to track down.

#

Would also try starting over with NetworkVariables from the jump.

magic shadow
#

but i dont get it, only when i implement the reload boolean it doesnt work, because the current ammo not being a network variable was working fine earlier

tame slate
tame slate
#

Not many, they are very similar. Each has a couple of their own extra features. NGO probably has more active support and more modern features being made for it than Mirror.

sharp axle
#

There is very little technical differences between them.

tame slate
#

Either are suitable. My personal preference would probably be NGO.

#

If you plan on using other Unity services like Lobby/Relay/Sessions, NGO is much easier to pair them with than Mirror as well.

tame slate
#

NGO, Mirror and FishNet are all built off the same foundation essentially. Same thing as I mentioned before, FishNet boasts some extra additional features. Only difference is some of them are behind a paywall I believe.

#

It's honestly just comes down to:

  • Personal preference of code/components
  • What other services you want to pair them with in your game
  • Are any of their extra features essential for you
#

Basically, yeah.

#

Not all necessarily built off of, but at the very least inspired by.

sharp axle
#

They use some flavor of Network Objects, Network Variables, and RPCs

tame slate
#

Fishnet is the only one that boasts a full Client Side Prediction solution built in. I believe it’s behind a paywall and I haven’t seen many people use it. The other two don’t have it built in. NGO has Anticipation which gets you part of the way there.

sharp axle
#

Photon has built in client prediction too

tame slate
#

They all do the most basic level of physics. Allow the authority to do the physics simulation and sync the resulting position to non authorities. None of them support actual client side prediction with physics.

sharp axle
#

NGO has a Network Rigidbody that will sync with the server simulation but it does not do prediction

delicate parrot
#

network physics is inherently a little nightmare-ish and any game needing it probably needs something more tailor made

tame slate
#

Unless your game is fully physics-based like Gang Beasts or similar games, it’s rare that you need a full fledged prediction system that supports physics.

#

Or you have thousands of physics objects.

sharp axle
#

a lot of games use custom physics for the player character

#

without some form prediction, the 2nd player will look like it hit the box but on the server/host it will miss

tame slate
#

It’s more-so just straight up delay/latency, unless you go with a client authority setup.

#

Or a shared authority network topology.

#

and then yeah, simultaneous or fast interactions between players and objects becomes hard to accomplish in a way that looks seamless to the players. But there was ways to design around it.

#

Correct

river gazelle
#

Anyone recently installed Steamworks.NET with Unity 6 and got the app id to work?
When I install it, it doesn't automatically add the steam_appid.txt file, and even if I add it manually, it doesn't use the app id for some reason, no idea what is happening.
I created this issue: https://github.com/rlabrecque/Steamworks.NET/issues

hallow aurora
#

it seems the documentation in NetworkBehaviourReference got cut off anyone know what its supposed to be? the same issue exists on the api reference website

sharp axle
hallow aurora
#

oh i see

#

that makes sense

#

thx

sharp axle
#

It would be crazy rare for something like that to happen. Normally a despawned reference would just return null

plain zenith
#

I wrote my question at the bottom of the message

sharp axle
plain zenith
#

I got it to work by asaaking chatgpt what the hell the docs mean, because they were pretyy hard to follow, not sure if its just a problem with me or not

twin grove
uncut wren
#

doing some testing rn - I've found that calling animator.play on a network animator DOES play the animation across all clients, but if I call it again whilst the animation is still playing, it does not start again on the non-authoritative client

#

host plays animation on character
animation plays on host AND on client
client plays animation
animation plays on host AND on client
either one plays animation, then plays animation again halfway through, animation does not restart on other client, but does restart on itself

#

Is this the intended behaviour?
Using NGO 1.8.1
unity 2023.2.17

sharp axle
#

I didn't think animator.Play() would work. But I guess the States get synced along with the properties

uncut wren
#

it would seem so. State changes look to be synced, but I'd have to manually reset the state time if I wanted to play an animation multiple times

cobalt hornet
#

What is your current techstack for Unity multiplayer now? I'm making a multiplayer piano game. Initially I used FishNet P2P which kinda works but for some reason a minority of players are getting disconnections so I'm thinking of just using my own dedicated server, and I'm thinking of making my own server using NodeJS and WebSockets, any advice?

I do use NodeJS before, but maybe I'll use NodeJS. What C# client library do you use? Any valuable insights or pitfalls I should look out for before jumping in?

It's a simple piano multiplayer (with chat, kick, queue-base taking turns playing piano etc).

small cliff
#

hey guys i have a problem, im making a multiplayer game and the animation only works for the host. The joined players can see their own animation, but cant see other people's animation, only the hosts. The host cant see the animations too. Player is a game object, it has movement script, network object, network transform, and network animator. The player below that is the model, it has the animator. In the animator animation works like this: if speed (float) faster than 0.01 then walking animation plays, etc. Authentication is set to Owner, yeah

tame slate
modern compass
#

Am I allowed to ask non-unity coding questions here?

sharp axle
sharp cliff
# cobalt hornet What is your current techstack for Unity multiplayer now? I'm making a multiplay...

If you've already created your game using FishNet, definitely give using dedicated servers a go to see if that resolves your issues to avoid extra work converting it to something different.

For my original techstack, NodeJS + Socket.IO + MongoDB, for the C# Unity client I used this library: https://github.com/itisnajim/SocketIOUnity

I've since moved over to using an open-source game backend called Nakama, using TypeScript and their Unity client SDK. The main reason is that I realized I was reinventing the wheel with a lot of the core features most games need (e.g. admin dashboard, social logins, in-app purchases, etc.) -- which Nakama already has. Unity client docs: https://heroiclabs.com/docs/nakama/client-libraries/unity/

GitHub

A Wrapper for socket.io-client-csharp to work with Unity. - itisnajim/SocketIOUnity

modern compass
#

I'm making a file transfer system that works over the Internet - using out of band authentication instead of CAs.

Before you ask yes I know it's probably over engineered, yes i know i could just find a working version online for 100x less effort and time but I'm having fun damn it 😂

My question - I'm trying to make a custom TSL inspired handshake. I'm using Diffie-Hellman Key Exchange, plus a transfer code, plus a TOFU system. Is this enough for Internet security for the application? Files would be encrypted using a Key Derivation Function from the DH Key Exchange and the transfer code.

dire sorrel
# modern compass I'm making a file transfer system that works over the Internet - using out of ba...

No one here is going to be able to help you with your question.

This is a game engine network forum. Your question is regarding internet security protocol implementation. Your question is in an entirely different league.

But I will give you some feedback.

If you decide to roll your own security you run a phenomenal risk of unintentionally weakening your security. The general rule to follow is always use standard best practices since those are the ones with the most eyes on and have learned where the flaws are (and resolved them).

elfin field
#

[Netcode] NetworkPrefab hash was not found!
[Netcode] Failed to spawn NetworkObject for Hash 29
OverflowException: Reading past the end of the buffer
NullReferenceException

Iam getting this error

slender zodiac
#

Hey, I’m using Photon PUN 2 (free) for a mobile multiplayer game.

Each player prefab has a camera and a Canvas with joystick, sprint button, and stamina UI — all inside the prefab.

The player prefab is spawned using PhotonNetwork.Instantiate().

❌ Problem:
When Player 2 joins, Player 1 freezes — can’t move or look — and logs:

👻 Not my player, disabling input.

It looks like input scripts are disabling themselves due to this check:
if (!pv.IsMine) { ... }

Also: Players aren’t synced. Player 1 sees Player 2's head move, but the controls are hijacked.

✅ What I want:
Each player to have their own camera + UI + input working properly without affecting each other.

Any idea what might be wrong or how to structure this better?

oak flower
#

@slender zodiac Post your code, ask an actual question, not this annoying LLM drivel.

#

!ask

raw stormBOT
sharp axle
twin grove
#

who used Facepunch + netcode?
When a host leaves the lobby, how do you disconnect other players from the lobby? Or how do you destroy the lobby

#

[FacepunchTransport] - Failed to diconnect client with ID 2914485745, client not connected.
UnityEngine.Debug:LogWarning (object)
Netcode.Transports.Facepunch.FacepunchTransport:Steamworks.ISocketManager.OnDisconnected (Steamworks.Data.Connection,Steamworks.Data.ConnectionInfo) (at ./Library/PackageCache/com.community.netcode.transport.facepunch@6e5559150134/Runtime/FacepunchTransport.cs:272)
Steamworks.SocketManager:OnDisconnected (Steamworks.Data.Connection,Steamworks.Data.ConnectionInfo)
Steamworks.SocketManager:OnConnectionChanged (Steamworks.Data.Connection,Steamworks.Data.ConnectionInfo)
Steamworks.SteamNetworkingSockets:ConnectionStatusChanged (Steamworks.Data.SteamNetConnectionStatusChangedCallback_t)
Steamworks.Dispatch/<>c__DisplayClass29_0`1<Steamworks.Data.SteamNetConnectionStatusChangedCallback_t>:<Install>b__0 (intptr)
Steamworks.Dispatch:ProcessCallback (Steamworks.Dispatch/CallbackMsg_t,bool)
Steamworks.Dispatch:Frame (Steamworks.Data.HSteamPipe)
Steamworks.Dispatch/<LoopClientAsync>d__22:MoveNext ()
UnityEngine.UnitySynchronizationContext:ExecuteTasks ()

weak plinth
#

Hey guys just curious what'd be the best way to make an online game? My idea is to have players matchmake and then play a match (fps game). How would I do this most cost effectively while it being a good method? Original plan was to use relay to connect players and then at random make one of them a host creating a lan server where the rest of the players get connected.

sharp axle
waxen quest
#

Hey guys, i seriously need help here. My free tier is getting fully exceeded in 14 days now. I am having a lot of players. I tried reducing bandwidth usage a lot. Converting integer to byte, packing Boolean arrays to byte, using unreliable delta, increasing send threshold for pos, rot. But still I am unable to reduce, idk what is using so much bandswidth

#

My tick rate is 30

#

I am getting billed 10-20$ every month and I am only earning an average of 3$ monthly from ads, and very rarely player purchase in game items. And no revenue from pc players. Since it's free

#

Having a streamer play my game is a nightmare and feel good at the same time.

#

My Netcode version is 1.12.2

#

Unity 2022

magic shadow
#

why is my client's text different from the actual value? it works when it reaches 0, but shouldn't the script's variables also be changing?

delicate parrot
#

(no one can answer this without code)

sharp axle
waxen quest
magic shadow
sharp axle
waxen quest
#

I have 2 NetworkList of struct

#

1 is sent only once when player joins

#

Other struct can change multiple times

delicate parrot
#

whats in the struct

waxen quest
#

Only few data like 4 bools packed in single byte flag

#

And client id

#

And other struct have few foxedstrings

#

But it's sent only once for a player

#

Not again until he eejoins

#

There's something hidden taking huge bandwidth

#

Is tick rate 30 good or bad?

fluid walrus
#

there's not really a good or bad tick rate, it depends how much data is being sent per tick which depends on your game

sharp axle
# waxen quest There's something hidden taking huge bandwidth

If there are a huge amount of network transforms constantly moving that could account for quite a bit of bandwidth. But nothing should be hidden from the profiler.
Your other option is to hook up Wireshark to find exactly what's being sent by your PC.

waxen quest
#

I just have lobby and player roaming around 😦

waxen quest
#

Another Example

#

is the animator taking that much usage?

rugged spire
#

Is there a limit on how much data can be sent in a single rpc call? for example lists or strings. I heard someone saying that there is a limit of 1300 bytes. but it felt odd for me and I couldn't find anything when I searched
And. Is there a way to send an rpc to a specific client? If yes how can I edit this function to do so? (Assuming I'm using NetworkManager.Singleton.localClientId

fluid walrus
# waxen quest

are you changing parameters every frame? idk if that uses the tick rate, you might need to rate limit that yourself

fluid walrus
#

the max size depends on the transport, i don't use the unity one so i don't know if it has a max but beyond a certain size it'll probably have to break the message into multiple packets and that value is likely around 1300 bytes

#

assuming it does that for you 😛

rugged spire
fluid walrus
#

that link is about the second part of your question

rugged spire
waxen quest
#

Animator transform should only send when it changes right

waxen quest
fluid walrus
#

oh yeah i linked the old docs by mistake (but the current docs also use ClientRpc i guess?)

#

look at the RPC target bit

waxen quest
#

Do I update me Netcode version? I think it have many benefits in less bandwidth useage

#

1.12 rn

#

1.12.2

fluid walrus
rugged spire
waxen quest
#

Based on profiler screen shots do you see any other thing which is causing bandwidth usage alot

rugged spire
#

For the size limit part. does anyone knows if the rpc called in unity transport have a limit on the data?

waxen quest
#

I'll try to optimize anim

fluid walrus
#

iirc all NGO RPCs use fragmented pipelines

sharp axle
sharp axle
waxen quest
rugged spire
sharp axle
cobalt hornet
#

I'm thinking of using the dedicated server model with FishNet (i've already used FishNet but made my game P2P sadly).

In converting this, I was wondering how does one authenticate the Steam username reliably? Are there any open source libraries or pointers on how to do this? Otherwise people can spoof their Steam ID.

sharp axle
snow imp
#

if you have a server build does it add to the amount of ram the server like if you have 2 builds running on a server and they are 80mb each would they take up 160 mb of ram

sharp axle
jaunty stirrup
#

Does someone know how can I destroy an entity but sync it to the late join clients?
I'm trying to make a certain client destroy an entity and it works fine but the problem is that other client can't join after that because their world isn't in sync

sharp axle
jaunty stirrup
#

ohh Tysm

#

I was stuck on it for a long time

grizzled peak
#

Does anyone know a good tutorial for netcode and parrelsync?

I followed one, but when I try to start the client it doesn't join the original unity editor host. I did see an error for using the same port or something so I changed the clone to a different port number but the error went away yet nothing changed, the client still didn't join the host.

tame slate
grizzled peak
#

I'll check this out!

sharp axle
grizzled peak
grizzled peak
tame slate
grizzled peak
# tame slate You should just be able to leave the port empty.

Thanks this helped. I looked back at my script and realized my UI wasn't calling my function appropriately. When I manually tested with the network manager buttons it worked. I probably would've went down a way deeper rabbit hole if y'all wouldn't have filled me in on the port settings

mint anvil
#

there is no way to set the write permission for everyone, right? (security is not a problem in my game) in my rts spaceships can be controlled by the whole team (so i don't use ownership for it) and in my head it feels weird to send so many rpc's the whole time, maybe i am just too focused on performance lol

sharp axle
twin grove
#

Why is it that when a player leaves the lobby, they are visually out, but their data remains in the lobby?

sharp axle
cobalt hornet
weak plinth
#

I don't suppose anyone that uses Facepunch.Steamworks could tell me if the "deprecated" p2p is really not worth going with? This socket stuff is not making sense

tame slate
#

Apparently they have experimental features related to prediction. Prediction and PredictedRigidbody scripts/components specifically.

sly dawn
#

Hey, for my game, i have been working with unity netcode for a bit but now working on integrating Facepunch. I have had alot of issues, specifically one which does not seem to go away

Bellow is all my relevant code files, alongside an error code that constantly spams no matter what i do once i start and actual game in a lobby. The transport layer is unchanged except for one line, which i included in the scripts

https://paste.mod.gg/wrsjdgsyshhr/3

I got the face punch stuff from here

https://github.com/Unity-Technologies/multiplayer-community-contributions?path=%2FTransports%2Fcom.community.netcode.transport.facepunch

https://github.com/MrRobinOfficial/Guide-UnitySteamNetcodeGameObjects

GitHub

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

GitHub

This repository is designed to help developers learn how to get started with Facepunch/Steamworks Networking and Unity Netcode For GameObjects. - MrRobinOfficial/Guide-UnitySteamNetcodeGameObjects

tame slate
sly dawn
#

im not very familiar with networking and i cant seem to find either

#

i will keep looking for now tho

tame slate
#

I wouldn't think it would be an issue with the actual package, but it might help point to the issue.

#

I have not used Facepunch but with the amount of beginners that come in here and have an issue with it, I'm not sure I'd recommend using it if you're starting out. I feel like there are other options with more features that are also simpler to use.

sly dawn
#

i see, fair enough, im just trying ot figure out parts im missing

#

cause i suspect i didnt properly instal facepunch, but rather only have the adapter installed (to allow for use with netcode)

#

if it isnt anything simple, i may switch up plans

#

honestly, im just really unsure

hybrid dew
#

how to send RPC to a specific client?
I am not using anything legacy and dont want to

but the documentation of the latest version still uses RPC params with stuff that don't exist in my code but exists in documentation

tame slate
# hybrid dew how to send RPC to a specific client? I am not using anything legacy and dont wa...

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

hybrid dew
tame slate
#

They have an example of how to pass through RpcTarget.Single() in order to send to a specific client. https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/#:~:text=ping to work%3A-,[Rpc(SendTo.Server)] public void PingRpc,.P))%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20PingRpc()%3B%0A%20%20%20%20%7D%0A%7D,-Other%20RPC%20parameters

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

hybrid dew
#

@tame slate

the problem here is that the property Send inside RpcParams is just a placeholder


private void OnClientConnected(ulong clientId)
{
    var rpcParams = new RpcParams
    {
        Send = new RpcSendParams
        {
            Target = RpcTarget.Single(clientId, RpcTargetUse.Temp)
        }
    };

    const int chunkSize = 100;
    for (int i = 0; i < _spawnedObjects.Count; i += chunkSize)
    {
        var chunk = _spawnedObjects.Skip(i).Take(chunkSize).ToArray();
        SpawnObjectClientRpc(chunk, rpcParams);
    }
}

[Rpc(SendTo.SpecifiedInParams)]
private void SpawnObjectClientRpc(SpawnedObject[] spawnedObjects, RpcParams rpcParams)
{
    if (IsServer) return;

    //do instantiation based on logic here
}

tame slate
#

SpawnObjectClientRpc(chunk, RpcTarget.Single(clientId, RpcTargetUse.Temp));

hybrid dew
#

oooh okay i see, thanks man

sly dawn
sharp axle
fluid walrus
#

there is a non-deprecated steam P2P system

sharp axle
#

Oh so the Netcode Facepunch Transport will need to be updated eventually?

fluid walrus
#

not if it uses SteamNetworkingSockets, the new API

#

which i think it does?

sharp axle
fluid walrus
#

i think OP may be using the API directly not using an NGO transport? 🤔

pulsar solar
#

does anyone know why i see both scenes open on my server, but not on my clients?

Is this intended??? 👀 Im using FishNet btw.

sharp axle
pulsar solar
sharp axle
vital path
#

does anyone know why my player spawner which is pre placed in main scene with a network object has this issue where it isnt spawned somehow when the host or client goes from start screen to main scene

sharp axle
vital path
#

i had that disabled since i didnt know how to prevent it from automatically putting the client into the main game without them using my login system first

vital path
#

any way of doing that?

sharp axle
vital path
#

gotcha, is there a way tho to keep scene manager on and still have a system in place preventing players from getting synced to the same scene?

sharp axle
vital path
#

gotcha, what would you recommend for a rpg game im working on that has a title screen for login and a main scene for gameplay, also combat scene for turn based combat.

tame slate
#

Combat scene should probably be loaded additively. Whether or not you load it additively with the NetworkManager, or just locally for the players involved could go either way IMO. Each has their pros and cons.

weak plinth
# fluid walrus i think OP may be using the API directly not using an NGO transport? 🤔

Honestly I’m so confused on all these new things I think it’s not worth it.
I’m just trying to get simple p2p to work but finding info on how to work with some parts of unity/apis (esp. face punch.steamworks) seems to be impossible atm? Docs for the API suck and tutorials/posts are outdated af or all do completely different things. So not really sure if what I’m doing is going to work or not

sharp axle
weak plinth
#

It’s just so confusing because some people say use unity transport, others say it doesn’t work with Facepunch.Steamworks, some say the Facepunch Unity Transport is deprecated, so I use unity transport, but then someone says I HAVE to use Facepunch’ unity transport (which get an error when trying to add the package for the transport anyways)

tame slate
weak plinth
sharp axle
sharp axle
tame slate
weak plinth
#

I know but I want to utilize steam features to make it easier for people to host/join with friends

sharp axle
#

I would say Unity Lobby, Relay, and Friends services would be just as easy

#

But also using either of the Steamworks libraries shouldn't be that hard either. The community transports will work when give it the steamid

weak plinth
#

Sometimes I wish there wasn’t as much readily available information

#

Because none of it lines up with another

#

I forgot how convoluted everything feels in this engine

celest valve
#

Someone who can help me with something that i proboably simple, but i cant figure out? im trying to make a split input for a single player using netcode. I cant for the life of me find out how or what im doing wrong. Someone have some spare time?

sharp axle
celest valve
#

One player, where lets say the host of a 2 player local co op controls movement, and the client controls the mouse. So they have to work together.

#

When i try to like "split" roles i end up either with no one can control anything, or both can use mouse and keyboard.

sharp axle
celest valve
#

right now im just trying to get the basics so i have just a build on my pc and run it in the editor at the same time.

#

i wanted to that and get something working before i scaled it a bit bigger

sharp axle
celest valve
#

no, i was thinking lets say i host a game, and then my friend can join as a client from his house. I forgot what that type of network system is called, but it will eventually end up running the "server" on the one who hosts and then the client joining will send inputs to that person.
And yes 2 players controlling one object, so lets say you and me are playing together, we see the same stuff, same world and such. You have to rely on me using my mouse to look around and such, and you control the keyboard movement. So its like a work together type of game.

#

i think its called Host (Client/Server) or something like that, so i dont have to have a dedicated server, it will be one of the players who is hosting.

sharp axle
celest valve
#

yeah, i have tried to find some sort of tutorial or documentation on it, but cant seem to find anything. So im struggling very much with how the code would look like to allow something like that to work.

sharp axle
#

You probably aren't gonna find any tutorials covering that. Make them separate objects. Put Network Transform with Owner Authority on each

celest valve
#

so i should make lets say
-Player (Capsule)
-Playercamera
-PlayerMovement

And those two have their own scripts, so one for keyboard one for camera?

sharp axle
twin grove
#

Server RPC and so on only work with ClientID?

sharp axle
sharp axle
#

If the key is the client id then that should be fine

twin grove
#

for some reason, the second player is recorded under the steam, and not the client's key.

vital path
#

okay so i have networkmanager.servermanager disabled for my project. I am changing the scene dynamically creating the player for the client that joins the scene, then later on when another client joins i create their character. The only issue i have is when a client joins the prefab sychronization occurs which destroys all existing in-scene placed NetworkObjects and spawn its corresponding Prefab from the NetworkPrefabs list instead. This causes issues cause the new client deletes the first clients player which makes me get a error [Netcode] [Invalid Destroy][Base Player(Clone)][NetworkObjectId:4] Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host . Anyone have any ideas on how i can fix this without enabling servermanager.

sly dawn
sharp axle
sharp axle
twin grove
sly dawn
sharp axle
# twin grove how do I get the client Id of another player?

You can get it from either the OnClientConnected callback if on the server, or you can use the OnConnectionEvent

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.

sly dawn
#

thanks tho, i will try that when i get home

twin grove
vital path
sharp axle
# twin grove NetworkTransmission.instance.AddMeToDictionaryServerRPC(SteamClient.SteamId, "Fa...

What is the question here? This will send the local client id in the RPC. But so will RPCParams

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

sharp axle
vital path
#

Well I got to just tackle it head on and get it working

#

I’ll probably just work on preventing the destroy case for now and go from there when other issues arise

vital path
#

Do anyone know where the prefab synchronization occurs specifically like which script had the logic for it so I can stop it from destroying the in scene network objects?

delicate parrot
#

You might have to elaborate on what your trying to do more specifically there and/or why the provided system isn't working out for you?

vital path
#

So I have disabled scene manager since I have a login system setup with net code. First the client connects the second they start the application. Then they register an account, login, and I send them to the main scene. The reason I’m not using network scene manager is because it would send every client to main scene at same time instead of at different instances. I have all that working currently with scene manager disabled. The problem occurs in the scene change when I create the first clients player prefab network object. It works fine, but the next client that joins has prefab synchronization occur destroying the first clients player prefab causing a error of a client destroying a unowned network object. So I’m trying to disable that auto destroy on scene change

delicate parrot
#

I think all the advice your gonna get is via the custom scene management doc linked previously

Aside from that I'm not quite sure that you need to disable scene management to solve that previous problem? In theory they would only be joining the network lobby when they go to the main scene, not during main menu?

vital path
#

They join the network to register and login since I’m using net code server and client rpc for those scripts. The custom scene management I just can’t find anything in the doc about how to bypass the auto destroy on scene change for clients

sharp axle
vital path
#

so if i make the player that gets spawn be dont destroy on load when the 2nd client joins it wont auto destroy it like the other network objects in scene?

sharp axle
vital path
#

the players spawned the second they get to main they dont get spawned before that. the issue im having is the prefab sync causing any client that joins to see the player prefab that was spawned in main scene for the previously joined client and attempting to destroy it

sharp axle
vital path
#

Vector3 spawnPos = GetSpawnPosition(clientId);
GameObject player = Instantiate(playerPrefab, spawnPos, Quaternion.identity);

var netObj = player.GetComponent<NetworkObject>();
netObj.SpawnAsPlayerObject(clientId);

sharp axle
# vital path i am

You'll need to reorder your scenes if you don't want network objects syncing too early. Or you can use Network Visibility to hide objects from new clients
https://docs-multiplayer.unity3d.com/netcode/current/basics/object-visibility/

Object (NetworkObject) visibility is a Netcode for GameObjects term used to describe whether a NetworkObject is visible to one or more clients as it pertains to a netcode/network perspective. When a NetworkObject is visible to a client, the server will assure the client has a spawned version (a clone) of the NetworkObject. This also means that...

vital path
#

okay i did some checks and found the 2nd client does detect the first clients player prefab as not owned by 2nd client which is good, so the visiblity and ownership is working properly. its just that the second client 2 joins the same scene as client 1 it destroys it player prefab locally which leads to the whole issue.

sharp axle
vital path
#

yes

sharp axle
#

That is something happening in your code then.

vital path
#

its the prefab syncronization causing the main issue for me

sharp axle
#

That doesn't destroy prefabs though

vital path
#

so after a lot of searching i realized that the client when he joins it creates a clone of all the network objects in scene after removing the orginal right, but it also takes any spawned network object that was spawned before it connected and clones it in the scene it is in. so in thiscase when client joins start screen it creates a copy of baseplayer prefab that the host has spawned in the main scene. I believe this is why when the client goes to main scene and the scene loads the clone it already made and the one in main scene destory each other

#

i could be wrong and something else is causing it to destroy but i can say for certain its not any my code causing this to occur

sharp axle
vital path
#

the client connects to the network when the program opens, the client is in the title screen, then he logs in and gets sent to the main scene. when sent to main scene it instantiates a player prefab network object for that client specifically. Now when a 2nd client opens program he connects and that client 1 player network object gets cloned into the title screen for that client 2 automatically by netcode package script. I just need to prevent that so the client does make a clone of it in title screen

tame slate
vital path
#

yea but i like the login system i have that works fully currently. so is there a more complex solution perhaps? sorry for all the questions just been struggling with this for days now

tame slate
# vital path yea but i like the login system i have that works fully currently. so is there a...

Object (NetworkObject) visibility is a Netcode for GameObjects term used to describe whether a NetworkObject is visible to one or more clients as it pertains to a netcode/network perspective. When a NetworkObject is visible to a client, the server will assure the client has a spawned version (a clone) of the NetworkObject. This also means that...

vital path
#

so i spawn the network prefabs without observers then i manually attach visiblity to the 1st client player prefab to the 2nd client once login is sucessful that was he doesnt duplicate it in start screen

vital path
#

welp at least 3 days of being stuck on this issue has forced me to learn so much about netcode lol. Thanks for all the help to everyone who answered my questions

hybrid dew
#

im facing an issue where sometimes when using Multiplayer Play Mode, IsServer is true even though it shouldn't be
and the only way to fix it is if I close the project and start again

is this typical or happens?

sharp axle
weak plinth
#

Would anyone know why im getting a
NetworkVariable is written to, but doesn't know its NetworkBehaviour yet warning with this code?

var pizzaShop = Instantiate(pizzaShopPrefab);
                var pizzaShopNetObject = pizzaShop.GetComponent<NetworkObject>();
                pizzaShopNetObject.Spawn();

                SpawnPlayer(NetworkManager.Singleton.LocalClientId);
                
                currentLevelObject.Value = pizzaShopNetObject;

I have tried setting the NetworkVariable inside the OnNetworkSpawn of the prefab I am instancing, but still the same thing.

delicate parrot
#

OnNetworkSpawn should work afaik?

#

that snippet above absolutely won't though, as the NetworkObject (and Behaviour) need to be initialized before any of their networkvariables or rpcs work

weak plinth
delicate parrot
#

wait I misread that snippet, still waking up apologies. Nothing in there is messing with a networkvariable?

weak plinth
#

and yeah, in the OnNetworkSpawn of the instanced object, I get the same warning

delicate parrot
#

Are you sure your looking at the relevant problematic code?

weak plinth
#

Sorry, currentLevelObject is a network variable

#

again, this is all from researching online so im a bit confused

#

I know it needs to happen after the object is spawned...and I confirmed the code ran after the it actually spawned

#

so very confused lol

delicate parrot
#

I'd need more context to see where this is being run and what owns currentLevelObject, but my initial suspecion is that at least from that code you can't assign an unspawned networkobject to a networkvariable

#

but as you said you tried in onnetworkspawn so is currentLevelObject currently the problematic variable?

weak plinth
#

Yeah currently the only problem. The warning in the console points me to the ...Value =... line

#

Ill try to sum it up:
So, this is in my script that exists in the scene at all time

public class GameManager : NetworkBehaviour
    {
        public NetworkVariable<NetworkObjectReference> currentLevelObject = 
            new NetworkVariable<NetworkObjectReference>();

Then in the menu UI, player presses "host", it starts a lobby, and i want to spawn the inital "level".
So, after the lobby successfully creates, I call the function that instances the level geometry.

if (NetworkManager.Singleton.IsServer)
            {
                var pizzaShop = Instantiate(pizzaShopPrefab);
                var pizzaShopNetObject = pizzaShop.GetComponent<NetworkObject>();
                pizzaShopNetObject.Spawn();

                SpawnPlayer(NetworkManager.Singleton.LocalClientId);
                
                currentLevelObject.Value = pizzaShop;
            }

The level geometry is a simple mesh with a NetworkObject component on the root.
I am a tad bit new to MP so i might just be missing something obvious but im not finding anything

delicate parrot
#

So as previously mentioned that code will def not work afaik because you can't assign an unspawned networkobject(the pizzashop) to a networkobjectreference networkvariable. doing that in pizza shop's onnetworkspawn is the right move.

In addition to that, You might wanna use inspector or logs to sanity check confirm if the GameManager has network spawned? Based on what your saying it should be but good to confirm

weak plinth
delicate parrot
#

😄

#

Networking can be tricky at the start, you get into the groove fairly fast

weak plinth
#

yeah its making more sense as I go. Just getting over the initial hurdles for sure lol

spring void
#

I get the following error:

KeyNotFoundException: The given key 'TacticsWizard.Lobby' was not present in the dictionary.
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <71119615d44348f087b10ce3c1671c84>:0)
Unity.Netcode.NetworkBehaviour.__endSendClientRpc (Unity.Netcode.FastBufferWriter& bufferWriter, System.UInt32 rpcMethodId, Unity.Netcode.ClientRpcParams clientRpcParams, Unity.Netcode.RpcDelivery rpcDelivery) (at ./Library/PackageCache/com.unity.netcode.gameobjects@4b084d75a42e/Runtime/Core/NetworkBehaviour.cs:269)
TacticsWizard.Lobby.NotifyPlayersCountChangeClientRpc (System.Int32 playerCount, Unity.Netcode.ClientRpcParams clientRpcParams) (at Assets/Scripts/Lobby.cs:106)

The script that causes this error derives from the Unity.Netcode.NetworkBehaviour. The method has the attribute [ClientRpc] includes ClientRpcParams clientRpcParams as the last parameter, and its name ends with ClientRpc. The prefab that has this script also has NetworkObject component and is added to the NetworkPrefabsList assigned to the NetworkManager. Any ideas what I could be missing? 🤔

tame slate
spring void
sleek nest
#

Network Manager HUD not showing in build, who can help with this ?

sharp axle
sleek nest
sharp axle
#

If there is a camera in the scene and it's not rendering, theyn the camera's renter target display might be wrong.

sleek nest
#

I already tried to add a camera to the scene, but unfortunately nothing changed, mirror hud did not appear

delicate parrot
#

Lets say I have two versions of a game

One is a newer version of the game that implements new INetworkSerializable classes and has some functions that utilise them.

Is the new client allowed to connect with the old client or is there something similar to the networkprefab list check that will discover this difference and mark it as incompatible?

I know if the new client tries to run stuff using these new things it will error just curious if it prevents connection in anyway

sharp axle
delicate parrot
#

Oh no i want them compatible, hence asking if there's any automated checks that might stop that

sharp axle
celest quarry
#

if i want to make mmo, which way is the best solution for dedicated server

sharp axle
celest quarry
#

oh i mean mirror/photon/C# netcode, which is best for mmo😂

sharp axle
violet frost
#

Weird Network Variable Bug:

I have a network variable that stores a FixedString32Bytes string:

private readonly NetworkVariable<FixedString32Bytes> playerName =
new(writePerm: NetworkVariableWritePermission.Owner);

And this function that is only called by the owner:
public void UpdateGameToSettings(PlayerSettings playerSettings)
{
this.playerSettings = playerSettings;
movementController.UpdateSensitivity(playerSettings.mouseSensitivity);
playerName.Value = new FixedString32Bytes(playerSettings.playerName);
GameObject.Find("CineCam").GetComponent<CinemachineCamera>().Lens.FieldOfView = playerSettings.FOV;
}

The function works totally fine when I call it on network spawn but doesn't work when I call it later in the game.
The problem is about this line:
playerName.Value = new FixedString32Bytes(playerSettings.playerName);

The error:
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.FixedStringSerializer1[T].WriteDelta (Unity.Netcode.FastBufferWriter writer, T& value, T& previousValue) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSerialization.cs:701)
Unity.Netcode.NetworkVariableSerialization1[T].WriteDelta (Unity.Netcode.FastBufferWriter writer, T& value, T& previousValue) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSerialization.cs:1642)
Unity.Netcode.NetworkVariable`1[T].WriteDelta (Unity.Netcode.FastBufferWriter writer) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs:198)
Unity.Netcode.NetworkVariableDeltaMessage.Serialize (Unity.Netcode.FastBufferWriter writer, System.Int32 targetVersion) (at ./Library/PackageCache/com.unity.netcode.gameobjects/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs:111)
Unity.Netcode.NetworkMessageManager.SendMessage[TMessageType,TClientIdListType] (TMessageT.....

sharp axle
violet frost
violet frost
#

Problem solved after updating

waxen quest
#

@sharp axle I have tested it with 5 instances, all idle players, but still they sending huge amount of data

#

I have set Position Threshol to 0.01

#

how they send so much data when idle

sharp axle
waxen quest
#

it would be good to know what network object is sending so much data

#

is it possible in profiler?

sharp axle
sharp axle
waxen quest
#

still few messages but lower

waxen quest
waxen quest
# sharp axle That could be. you can try disabling the sync pos/rot on those transforms instea...

Will this approach works fine?

        foreach (var rb in limbsRigidbodies)
        {
            rb.isKinematic = false;
            var networkTransform = rb.GetComponent<ClientNetworkTransform>();
            if (networkTransform != null)
            {
                networkTransform.enabled = true;

                networkTransform.SyncPositionX = true;
                networkTransform.SyncPositionY = true;
                networkTransform.SyncPositionZ = true;

                networkTransform.SyncRotAngleX = true;
                networkTransform.SyncRotAngleY = true;
                networkTransform.SyncRotAngleZ = true;
            }
        }
        foreach (var coll in ragdollColliders)
            coll.enabled = true;
sharp axle
waxen quest
#

I was paying a lot for this simple mistake

#

Thanks for your help mate!

cobalt hornet
#

One player is unable to connect to multiplayer in the game (but the rest is). My multiplayer uses sockets (so they resolve my domain name to an IP). I'm behind Cloudflare, so they can either get an ipv6 or ipv4 back.

I debugged this and it seems they don't support ipv6, running ping -6 example.com doesn't work for them which verified that.

Additionally, Unity could not send crash logs because it tried to send it to the ipv6 address.

Has anyone been able to resolve this issue? I am using Nakama. But it seems the Unity build doesn't auto-detect if ipv6/4 is supported and force using the ipv4 address instead of ipv6.

dapper zinc
#

Why is the class DistributedAuthorityTransport not public?

#

I was making a config that makes use of this class, however turns out it's not public in the package, so i cannot add as component...

livid grotto
#

Hey, when playing with multiple people in my game or sometimes just 2, the game lags on the clients, im using my local ip to connect to the host why is so laggy

tame slate
#

All clients are skipping identically - likely an issue with your movement code rather than network lag.

livid grotto
#

sometimes the models in the game move in slowmotion, i thought that was because of the network, I have no clue. Can it be because of my laptop? Because sometimes it goes back to normal...

tame slate
livid grotto
#

and the build is running in one instance

sharp axle
#

That just seems like low frame rate

livid grotto
#

ok, figured it out, I had to turn off vsync on the project settings and now runs fine, srry to bother!

plain zenith
#
System.Guid.ToString (System.String format, System.IFormatProvider provider) (at <8db6ec373e6d40bd9d38c8037d358c4e>:0)
System.Guid.ToString () (at <8db6ec373e6d40bd9d38c8037d358c4e>:0)
InventoryElement.NetworkSerialize[T] ``` anyone know why this would cause a stack overflow? Too long?
sharp axle
plain zenith
#

Wait I think understand now

plain zenith
#

I extended a server rpc function through inheritance, called an override server rpc function of the same function, and this for some reason caused the stack overflow

delicate parrot
plain zenith
#

apologies for the lack of clarity

tame slate
#

If you need to, make wrapper functions to do so

plain zenith
#

also the a key on my nice keyboard i bought from japan is very faaulty, and puts in double a's, or doesnt recognize when ive pressed a entirely for a while

#

very frustraataing

#

lmao

#

fml

#

im currently trying to figure out a good system for transferring items between players and different containers

#

I programamed my entire inventory system from scratch, aand ive been optimizing it f or days noww lol

#

never done this before so im not sure what the network layer should look like

#

trying to figure out how to make it modular/ condensed and readable

sharp axle
delicate parrot
#

Since it just basically wraps up getting something via index

delicate parrot
#

Weird question but is there anyway to handle a NetworkVariable on behalf of another object? Was curious if i could have NetworkVariables in eg. A ScriptableObject but have another spawned ngo look after it like an orphaned duckling

sharp axle
delicate parrot
#

Does it though? Like is there some shenanigans where I can do that behind the scenes setup myself?

#

Like I assume they must use reflection or something to find them all on the behaviour right? Maybe i can give those to a ngo/nb manually?

sharp axle
old mural
#

@sharp axle what are your thoughts on capacity planning specifically for a multiplayer workload? Asking just to ask.

#

Any tips?

plain zenith
#

Man I tried to make my own custom ui system and then add all of the networking, modified all of the mouse event scripts to be custom, and it became extremely complex so fast and Kindof exploded

#

Not sure how to make an inventory system that is simple

sharp axle
sharp axle
plain zenith
#

It’s just the lack of understanding of how NGO works for the most part, it’s pretty confusing while learning it

delicate parrot
#

are you networkvariable pilled yet

sharp axle
delicate parrot
#

Not a NetworkList?

sharp axle
#

either will work

#

You can work with Linq using the first method

plain zenith
#

I did that

#

And then I just send an id number as well as a guid over the network, the if variables searches a SO “database” for the time

#

Item

#

The issue is trying to get everything to sync, I think I’ve just done it pretty terribly, I’m wondering if there’s some sort of design concept I should be following, like MVC or something, but game engines are so much different have have so many different requirements than the usual applications that use MVC

#

I think I’m also working on something very complicated for my first multiplayer object, and should probably start a lot simpler lol

sharp axle
plain zenith
#

The issue is the syncing of all the different inventories across the network

#

They all use the same class for their inventories, and for some reason each player object tries to access every other players inventory on network spawn, even though they shouldn’t. I think I just need to take break from the code and look at it again later lol

sharp axle
plain zenith
#

No I'm not, each player has an inventory, and this is how it is saved to the server ```using Unity.Netcode;
using UnityEngine;

public class InventoryManager : NetworkBehaviour
{
public NetworkList<InventoryElement> networkInventoryElements = new NetworkList<InventoryElement>();
public bool isContainer = false;

/// <summary>
/// Sends a request to the server to add an inventory element to this player's inventory.
/// </summary>
/// <param name="inventoryElement"></param>
[ServerRpc]
public virtual void RequestToAddInventoryElementServerRpc(InventoryElement inventoryElement)
{

    networkInventoryElements.Add(inventoryElement);
}

/// <summary>
/// Sends a request to the server to remove an inventory element from this player's inventory.
/// </summary>
/// <param name="inventoryElement"></param>
[ServerRpc]
public virtual void RequestRemoveInventoryElementServerRpc(InventoryElement inventoryElement)
{

    networkInventoryElements.Remove(inventoryElement);
}

}

#

then I have another class that sortof accesses it and saves each item in there to a dictionary, which is then sent to a uimanager that displays them in the correct position

#

I think I just need to simplify it a lot

sharp axle
plain zenith
#

for some reason each player that spawns tries to execute eachothers servewr rpcs

#

yeah I literally just changed that haha

sharp axle
plain zenith
#

I am, but it for some reason gets past it

#

oh wait i missed one

plain zenith
plain zenith
#

I was like about ready to aabandon this project, then I just deleted ton of bloat code and fixed some things, and now it sortof works. The way the network interactions work is just pretty confusing, going to have to figure it out further

#

Man I just feel so bad at this network stuff, it’s pretty demotivating lol

#

Not sure if there’s some core stuff I’m missing here

#

Should probably read the docs more actually

green vortex
#

this is a unity session question

do we have intermediate function to validate or extract password on isessioninfo?

#

i mean ofc i can just call JoinSessionByIdAsync and let unity verify it for me, but that cost network traffic right? so im trying to validate it without calling network related function as possible

green vortex
sharp axle
green vortex
sharp axle
green vortex
#

dw i have a null check for that

green vortex
#

i think i cannot leave session asap, it needs to be the last thing instead

wild mortar
#

hi guys, i am making a session system and im trying to implement kicking. so far, the host of the session can kick players, but for the player they still in the gui i made for the session. i want it to close when they're kicked. heres the script that handles the sessions including kicking players: https://www.ghostbin.cloud/csgo0. and heres the script that handles joining sessions and where im trying to close the gui for the player when they're kicked: https://www.ghostbin.cloud/yat90. any help appreciated

frigid minnow
#

I use low lvl API so I would send the kick request from host and then from server send kick response to player who was kicked

plain zenith
frigid minnow
#

Unity transport

plain zenith
#

aah

#

If someone does not own an objeect, is it not synchronized to their client?

tame slate
plain zenith
#

its pretty confusing whaat ownership actually does, even after reading NGO docs like 5 times

#

ah okay

tame slate
plain zenith
#

this seems so much more complicated than it needs to be

tame slate
plain zenith
#

alright

tame slate
plain zenith
#

is there a simpler networking framework for client-server

#

like theres just so mukch stuff in ngo that I realaly could do without that just adds bloat it seems

tame slate
#

Most of the popular ones are all very similar to NGO. They are among some of the simpler ones there are.

plain zenith
#

damn alright

#

thaanks

#

Im just unsure of wwhen I should use IsOwner HaasAuthority, IsClient

#

How to disable specific scripts for clients but not the server

#

or atleast maake the client unable to use the scripts f;unctions

tame slate
#

The most common approach is to just gate functions

#

if (!IsOwner) return at the very start of the function to prevent non-owners from running the code

plain zenith
#

I would have to put that at the start of a lot of functions haha

tame slate
plain zenith
#

alright

#

is session owner the host/server?

tame slate
plain zenith
#

kk

plain zenith
#

Man it’s too annoying

#

I’m just going to install unreal, apparently their networking is simplified

#

You can see how it works because it allows you to view the source

#

Or I’ll have to build a project from scratch really slowly to avoid building too much stuff without understanding how the full system fits everything together

#

Over the network

sharp axle
blissful jay
# plain zenith Man it’s too annoying

look, i get it. you’re frustrated, and you should be. ngo is a total mess. way too complicated, way too over-engineered. not good! but don’t give up on unity just yet. go check out photon fusion or quantum, tremendous frameworks, very professional, very smart people behind them. you’ll be impressed, believe me.

tame slate
plain zenith
#

Unless your game is pong

tame slate
plain zenith
#

should I be using netcode for entities?

sharp axle
sharp axle
plain zenith
#

Ive been designing it from the beginning as multiplayer, but my understanding of ngo has changed as ive tried to implement more features

#

right now im trying to figure out if OnNetworkSpawn is called for every single client when they locally create the game world and the shared game object, or if its invoked once for that object when it first joins the server

plain zenith
#

kk

plain zenith
#

Deleted my entire inventory system and now I’m going to build it from scratch

#

Is NGO sufficient to support a lot of players

delicate parrot
#

"a lot" is a very useless piece of info, respectfully

tame slate
#

and there also is no direct answer. It largely depends on the type of game and how optimized your network code is.

plain zenith
#

Like multiple players, not a small coop online game

delicate parrot
#

is there a very rough number?

#

eg. some people might consider wow to be "a lot"

#

some might consider 8 to be a lot

tame slate
delicate parrot
plain zenith
delicate parrot
plain zenith
#

I’m trying to make an mmo first person rpg dungeon crawler type game, NGO doesn’t seem that it would be able to support a ton of players, so I’ll probably have a server for each dungeon or something

delicate parrot
#

There have been successful indie games that honestly don't even have the most optimised network stuff have worked fine with even moree than that

plain zenith
#

Oh sweet

tame slate
#

I had 16+ players running on NGO + Relay when it was in prerelease without any network or performance issues. It can handle more than people give it credit it before, so long as you write optimized code.

wide temple
#

pretty simple question, using NGO, all I want to do is have a client spawn an object to everyone else

tame slate
wide temple
#

thats what ive been trying but it doesnt seem to be working

#

ill try again

tame slate
#

Make sure the prefab is in the spawnable prefabs list

wide temple
#

done that

wide temple
delicate parrot
#

you'd probably have to post code

#

also make sure the thing calling the rpc is spawned

wide temple
#

wait what does that mean

#

oh

#

it def isnt spawned

delicate parrot
#

if its not spawned it can't send rpcs

wide temple
#

oh shit

fossil acorn
#

What is it then, if not spawned?

wide temple
#

just instantiated locally ig?

fossil acorn
#

Show code

wide temple
#

code instantiating a shit ton of nodes, the nodes are what I want to communicate with server

        for (int j = -rank; j < rank + 2; j++)
        {
            for (int i = -max; i < max; i++)
            {
                if ((i - 1) % 3 != 0)
                    Instantiate(node, new Vector3(rt3 * j - rt3 / 2, 0.25f, 0.5f + i), Quaternion.identity);
            }
        }
#

then code on node 💀 (i dont know how to use this)

    public void OnMouseDown()
    {
        SpawnHouseRpc();
    }

    [ServerRpc]
    private void SpawnHouseRpc(ServerRpcParams rpcParams = default)
    {
        GameObject obj = Instantiate(housePrefab, transform.position, Quaternion.identity);
        obj.GetComponent<NetworkObject>().Spawn(); 
    }
#

both the node and house prefabs are apart of the network prefab list

fossil acorn
#

Right... so the RPC needs to be a part of a NetworkBehaviour or whatever it was called. I think an RPC with [ServerRpc] actually needs to have a name ending in ServerRpc.
With that said, are you sure you need an RPC for spawning an object?

wide temple
#

how else would I do it?

wide temple
fossil acorn
#

Just do the code in that rpc

wide temple
#

but isnt the client not allowed to used .spawn()?

fossil acorn
#

(I'm not a network expert though, just played a bit with networking for a prototype some 2 months ago)

fossil acorn
wide temple
#

yeah i get this error

NotServerException: Only server can spawn NetworkObjects
Unity.Netcode.NetworkObject.SpawnInternal (System.Boolean destroyWithScene, System.UInt64 ownerClientId, System.Boolean playerObject)
fossil acorn
#

Okay, so change the name to end in ServerRpc and try again

tame slate
wide temple
#

i hate this shit man

#
        for (int j = -rank; j < rank + 2; j++)
            for (int i = -max; i < max; i++)
            {
                if ((i - 1) % 3 != 0)
                    obj = Instantiate(node, pos, Quaternion.identity);
                    obj.GetComponent<NetworkObject>().Spawn();
            }
        }

ts spits out 100 errors and wants to die

#
Sphere(Clone) is already spawned!
UnityEngine.Debug:LogError (object)
Unity.Netcode.NetworkSpawnManager:SpawnNetworkObjectLocally (Unity.Netcode.NetworkObject,ulong,bool,bool,ulong,bool)
#

how

#

what

#

and now i can spawn house on host but not even instantiate it on client

fossil acorn
#

go step by step... do you have something that's on the scene from the start and is a network object and somehow synced?

#

if so, make an rpc on that and some editor button that calls it and make sure it executes as expected when called from clients... then make it instantiate an object and do spawn - see what happens... and so on

#

I feel like you currently don't know where the problem even is (or maybe that's just me 😄 )

wide temple
#

yeah i dont

wide temple
fossil acorn
#

so... add one that starts on the scene, make it sync transform (it's part of network object or something)

#

make sure it's synced by moving it in editor on the host

#

then do the other steps 🙂

#

step by step - until the current step works - that's the best way to understand what's going on 🤷‍♂️ I don't have an NGO setup around to test it myself, but it's probably better if you play more with it anyway - to get a better idea

wide temple
#

im going to take a break now

#

my brain is fried

plain zenith
#

Im going to just try using the low level unity transport library

sharp axle
untold holly
#

When trying to connect as a client to an ip with no hosts on it, I get an "All socket receive requests were marked as failed, likely because socket itself has failed" I understand why this error happens, but I basically would like to check first if there already is a host, and if it is, connect as client by using NetworkManager.Singleton.StartClient();. How can I do something similar?

#

I don't need to exactly do that of checking if there's a host. If there's a way to solve this issue, it works for me. Because my app has a single connect button, and if I just add two buttons, one to connect as host and another one as client, I will just get the same error.

tame slate
plain zenith
#

man its a lot easier to do networking in c++ than unity c# lol

sharp axle
weak plinth
#

Hey folks, can someone point me in the direction of the proper way to despawn a player character when the owning client disconnects/closes the game?
I've been finding the OnClientDisconnectCallback but that only seems to run on the client once they disconnect. Not sure how to communicate this to the server 😛

tame slate
#

In terms of better options for disconnection callbacks, check out Connection Events.

https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/connection-events/

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.

weak plinth
#

Sorry, im still so confused

#

i cant get the host to "hear" when a disconnect happens? is it something to do with multiplayer play mode maybe?
The host only hears about the disconnect after the host exits play mode

#

ok yeah seems to be a multiplayer play mode thing

tame slate
#

I wouldn't think MPPM would effect this, but I haven't used it so I can't say for sure

weak plinth
#

weird, but good to know 😛

sharp axle
weak plinth
sharp axle
#

depends on when you are subscribing to the Connection Event

weak plinth
twin grove
#

me need NetworkBehaviour? for netcode

#

player management

sharp axle
twin grove
#

I still can't figure out if Rpc works with SteamID?

tame slate
sharp axle
tame slate
#

If for whatever reason you wanted to accomplish that, just make a Dictionary with Steam ID and Client ID. Not sure what the use case for that would be that you couldn't just use Client ID for by itself

waxen quest
vital hill
#

Does somebody know why the client is not running The SendSeedToClientsClientRpc? (Unity 6 Fishnet)

The Script With the SendSeedToClientsClientRpc

    [Server]
    private void LateUpdate() {
        if(!onTime) {
            onTime = true;
            ...
            SendSeedToClientsClientRpc(shuffleSeed); // An Clients senden
            ...
        }
    }

    [ObserversRpc]
    private void SendSeedToClientsClientRpc(int seed) {
        Debug.Log(seed);
        Debug.Log(UpgradeCard);
        ApplyShuffleAndAssign(seed); // Clients führen lokalen Shuffle aus
    }

The script, where I spawn the Obj with the script above

    [Server]
    private void Update() {
        if(i != Oldi) {
            Oldi = i;
            Player[i].GetComponent<UbgradePlayerCards>().canChooseCard = true;

            GameObject UpgradeScreenObj = Instantiate(UpgradeScreen);
            Spawn(UpgradeScreenObj);
        }//, Player[i].GetComponent<NetworkObject>().LocalConnection
        ...
    }
sharp axle
vital hill
twin grove
sharp axle
# twin grove something is wrong with me, how do I get them?

The client id? You can get it from many places. Each network object has a Owner Client Id. RPCs can send it RPCParams. Connection events if you want to save it when a client connects

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.

untold holly
#

Is there a way using NGO to check before connecting if there is a host already using a specific IP and port?

sharp axle
untold holly
#

I have a connect button. the purpose of that connect button is to try connecting as a host, but if there already is one, connect as client. Yet I get an error no matter what, let me show you

sharp axle
untold holly
#

Yeah, but even if I do it like that, I get an error that can't be try-catched

#

Give me a second and I'll show you

#

This error keeps repeating. I'll show you my code

#

public void Connect()
    {
        

        try
        {
            Debug.Log("Trying to start as client...");
            ConnectAsClient();
        }
        catch
        {
            Debug.Log("Failed to start as client. Trying host");
            try
            {
                ConnectAsHost();
            }
            catch
            {
                Debug.LogError("Failed to start as host too.");
            }
        }
    }

public void ConnectAsHost()
    {
        Debug.Log("Starting Host");
        bool success = NetworkManager.Singleton.StartHost();
        if (!success)
        {
            Debug.LogError("StartHost failed");
            clientDisconnectedFeedback.SetActive(true);
        }
    }

    public void ConnectAsClient()
    {
        Debug.Log("ConnectAsClient invoked");
        clientConnectingFeedback.SetActive(true);
        SetConnectionData();

        bool success = NetworkManager.Singleton.StartClient();
        if (!success)
        {
            Debug.LogError("StartClient failed");
            clientDisconnectedFeedback.SetActive(true);
            return;
        }
    }```
#

I'm lost, super lost, the button is supposed to do that, but even with all these try-catch it doesn't work

#

I tried so many things

sharp axle
untold holly
#

And also, I'm testing on the same PC for now, would the remote connections thing still be an issue if I'm trying to connect to multiple instances of the game in the same computer?

sharp axle
untold holly
#

Well, it still happens in localhost. So I have no idea what's wrong with that I'm doing

#

The same error occurs even when allowing for remote connections so now I don't know what to do

#

I can choose to connect from the buttons in the inspector, it's just this script that fails

sharp axle
untold holly
#
private void SetConnectionData()
    {
        UnityTransport myNetworkTransport =
        NetworkManager.Singleton.GetComponent<UnityTransport>();
        myNetworkTransport.ConnectionData.Address = ipInput.text;
        if (ushort.TryParse(portInput.text, out var port))
        {
            myNetworkTransport.ConnectionData.Port = port;
        }
        else
        {
            Debug.Log("Error en el numero de puerto");
        }
    }```
#

I think so. Is this not supposed to work?

#

Okay, I tried something. I made some lines where if I press the P key it starts as host, and if I press the O key it starts as client. They both work, but I have no idea how to implement them both into a single button

#

Another issue i'm finding, the errors are constantly appearing. Like, every 1 second, the error pops up, instead of popping up only once

sharp axle
untold holly
#

I'll just paste the whole code and see if there's something wrong with it

untold holly
#

After testing with Debug Logs, I can see that the error is specifically happening on NetworkManager.Singleton.StartClient();

#

Like, it's that line that's returning the constant errors every 1 second. Which is weird, because I'm pretty sure it's an error per second

#

This also happens when I click on the start Client button in the inspector, so it isn't an error on my behalf? I don't understand

#

I figured out something too

sharp axle
#

My mistake there is a max connection attempts in the Tranport

untold holly
#

It was this

#

So, when the max connection attempts in the transport is reached, is there a way I can know to invoke the connect as host method?

sharp axle
#

You'll get a Disconnect event from the transport. I'm pretty sure OnClientDisconnect will fire

untold holly
#

Right, but the same thing would happen if you were previously connected successfully and log off, so I'd like to be able to differentiate a connection attempt failed to a disconnection.

My goal is to try connecting as client, and if not, connect as host, but in that event, wouldn't willingly disconnecting try to connect you again?

untold holly
#

I think I'll just make it a coroutine with a waitforseconds equal to the connect timeout * connection attempts

plain zenith
#

Has anyone here actually made a complicated networked game in Unity

sharp axle
# plain zenith Has anyone here actually made a complicated networked game in Unity

If you want an example you can look through the Boss Room project. Most games don't talk about their network stack so the biggest game using NGO that I know of is Lethal Company

GitHub

A small-scale cooperative game sample built on the new, Unity networking framework to teach developers about creating a similar multiplayer game. - Unity-Technologies/com.unity.multiplayer.samples....

twin grove
#

It's a pity there are no knowledgeable people here

sharp axle
vital hill
#

Hey, I got issues with setting an Owner when I spawn an obj (Unity 6 Fishnet)

So in the 3rd line the correct Player sets his bool
But in the last, The Owner becomes the Host everytime. Why?
The host is not even in the Player List

       if(i != Oldi) {
           Oldi = i;
           Player[i].GetComponent<UbgradePlayerCards>().canChooseCard = true;
           Debug.Log("asfasfasfasfhasofhoasfhaoshfioashfoashfouh");

           UpgradeScreenObj = Instantiate(UpgradeScreen);
           Spawn(UpgradeScreenObj, Player[i].GetComponent<NetworkObject>().LocalConnection);
       }
vital hill
#

got fixed

twin grove
#

and what about the host?

sharp axle
# twin grove and what about the host?

The host should subscribe to OnClientConnectedCallback as well. the call back will run for every client that connects there.
You can also use the ConnectionEvents i posted earlier so the other clients can get notified when clients join as well

mild brook
#

Hey just a fast question, which way can i use to make multiplayer a 2-3 player little game without a lot of things happening in it ? Without dedicating server, hosted by a player. thx !

sharp axle
mild brook
sharp axle
sharp axle
twin grove
#

clientID 0

sharp axle
#

yea, the host client id will always be 0. it will go up by 1 for each connection.

twin grove
sharp axle
#

Or you could use OnNetworkSpawn of the player objects

twin grove
sharp axle
twin grove
# sharp axle You can see it used [here](https://github.com/Unity-Technologies/com.unity.multi...

void OnConnectionEvent(NetworkManager networkManager, ConnectionEventData connectionEventData)
{
if (connectionEventData.EventType == ConnectionEvent.ClientConnected)
{
if (NetworkManager.Singleton && NetworkManager.Singleton.IsServer)
{
return; //you don't want to do actions twice when playing as a host
}
RefreshLabels(true);
}

        else if (connectionEventData.EventType == ConnectionEvent.ClientDisconnected)
        {
                RefreshLabels(false);
        }
    }

Which method should I use instead? OnClientConnectedCallback(ulong clientId) or private void ClientConnected(ulong clientId) => Debug.Log($"I'm connected, clientId={clientId}"); ???

sharp axle
twin grove
tame slate
tame slate
#

You can get client ID through connectionEventData.ClientID

green vortex
#

this is an ordinary error message generated by unity session

i want to make my own error display UI to display a summarized error in my game, thats why i need to contain the exact variable of the error , i dont want to just extract some of the words inside and hard coded them as magic words

public const string InvalidPassword = "password does not match";```
#

and not only unity session, i want it to cover all kinds of error , from session to NGO

#

so is there a function/variable that i can listen to

#

like this one, can i have

e == unitySession.LobbyErrors.OwnershipIsInvalid```
sort of that thing
tame slate
# green vortex

You shouldn’t have to make your own. You would just catch for a SessionException instead of just the regular Exception.

elfin field
#

Anyone know how to make ready and start system in netcode

green vortex
#

ty i will check it out👍

green vortex
twin grove
sharp axle
tidal hemlock
#

How does a game like Fall Guys handle server auth and client prediction with a non deterministic physics engine, across multiple platforms?

To my (very basic) understanding, non deterministic movement in a server authoritative with client prediction netcode would result in jittery-ness etc, is that not the case? Or not the case anymore?

hearty dock
tidal hemlock
#

I was reading in the forums about how it’s very easy for them to diverge pretty quickly and got scared before even trying 😂

I’m making a movement system, it’s not too physics depends so for like 80-90% a simple character controller works perfect, but for that other percent, I’d need to simulate those physics-like movements with the normal character controller, which has been a pain for parts

Would it be worth just sticking to the character controller since it’s not too dependent on physics? Or would it be worth adding some physics aspect and stop being paranoid about the non-determinism ?
@hearty dock

hearty dock
#

I can't comment on what the best choice for your particular game is without intimately knowing the details of it.

tidal hemlock
#

Makes sense, thanks for the insight, I’ll keep digging

twin grove
#

that's what I see in NetworkManager, but how do I make a discount?

tame slate
twin grove
#

OnConnectionEvent yes?

tame slate
tame slate
sharp axle
tidal hemlock
sharp axle
tidal hemlock
#

wasn’t aware thanks, gotta look into it

sharp axle
tidal hemlock
#

My biggest debate right now is wether I want to use physics for 10-20% I need it for, or just keep with a basic controller and simulated “physics” which works for 80-90% … cause it’s been a pain to simulate some things

twin grove
#

Only I do not understand what to do further how do I clientId get the players who connect?

tame slate
twin grove
#

and have them get it from the host

tame slate
tame slate
#

without the need for the Host to send any RPCs

sharp axle
#

Also if you just want to broadcast to all clients, you don't need to specify any client IDs.

twin grove
#

I need Rpc to transfer the readiness of players, so that the player has a button to start the game, also to kick players out of the lobby, because in Steam there is no kickout

twin grove
#

why doesn't it work?

sharp axle
twin grove
#

I logically get an error here, but the other half has no logs on the client.