#archived-networking
1 messages · Page 40 of 1
I got it working, thank you for the help!
For posterity, how did you manage to get it working?
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
@small saddle so how do i show torch and light to all player?
When you ran Unity as the second client, and searched the hierarchy, did you find 2 "flashlight" objects? If you select the second flashlight object, and hit "F" does it show up in your scene?
And if you search your hierarchy, is there 2 "flashlight" objects?
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
YES!
thank you so much 😃
Np
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?
Any errors? Is this code in a NetworkBehaviour?
yeah, I found out I just forgot to make it a NetworkBehaviour 😅
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
That will work in some fashion, just probably not the best order of operations. I would use OnValueChanged to update your body and hand positions on the client
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#using-a-networkvariable
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
so i can keep my current code and it will work fine at best?
Not the most efficient, but sure.
alright thanks
I'm assuming you're actually moving those transforms on the server in other code?
No, thats kinda the whole script excluding the variable initialization.
though they use NetworkVariables
All your code is doing is syncing the server's position to everyone, including the server itself. You're not moving the transform anywhere.
Is there a reason for not using Network Transforms here?
so do i need to put it in a client RPC?
not really, just decided to use a vector3
Alright i fixed my whole script.
You have your network variables as server authoritative, so you would need to send your position values to the server in the RPC
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?
nvm solved it.. thank you
👋
For multiplayer, is something like this useful? https://assetstore.unity.com/packages/tools/network/smooth-sync-96925
I've not used it.
But Client anticipation is something that is built in NGO now
Client anticipation is only relevant for games using a client-server topology.
was definitely more useful years back. Almost all of the libraries that asset supports have received updates that make their default NetworkTransforms just as good.
how to kick a player from the lobby in Facepunch.Steamworks???
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?
Use a NetworkVariable to store the name. Use .OnValueChanged to set the text
the host is the only one who can write on it right?
By default, yes. You can change write permissions if you wish
but they can't store strings. can they?
You have to use one of the FixedString types
Netcode's serialization system natively supports Unity's Fixed String types (FixedString32, FixedString64, FixedString128, FixedString512, and FixedString4096). The serialization system intelligently understands these fixed string types and ensures that only the amount of the string in use is serialized, even for the larger types. This native su...
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
You either make the NetworkVariable have Owner Write Pernissions so clients can sync their own name or you have clients send an RPC to the server for it to set the variable.
I wouldn’t use OnConnectionEvent. Just OnNetworkSpawn of wherever this NetworkVariable is going to be.
I guess I have an idea of what to do now. Thanks for the help
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?
This sounds like a question for #archived-lighting
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)
What do you mean by ownership crash? I would set the parent of the object with TrySetParent() in the serverRPC
I don't see your exact issue, but you should be trying to use _isHeld.OnValueChanged instead of constantly checking the value in update. Also should try using OnOwnershipChanged instead of changing the ownership and calling an RPC directly after as the order of delivery is probably not guaranteed.
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.
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
Appears that FixedStrings don't have built in serialization for arrays. Try NetworkList<FixedString> or NetworkVariable<List<FixedString>>
Also not sure if there's a difference between serialization support between FixedString and FixedStringBytes.. documentation examples use FixedString
I used list instead of arrays. the error is gone now. Thank you
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.
This is what Multiplayer Play Mode is for
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.
local co op would still only use 1 client for both players. You would just use the Input System Player Input Manager amd have the client connect as local host
it miiiiight be possible with some hacking, i expect you'd have to do a lot of extra work to manage scenes and such because each client would need to have its own NetworkManager and a separate copy of the entire scene
probably not worth it though haha
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
gotcha, that makes sense. thank you all!
I (have started to) manage it!
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
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
Ah fair
Why am i still getting this error man.
WeaponThrowableItem script: https://paste.ofcode.org/tgKatRpYUbcz9kjkGH2Ja9
The method that despawns the gameobject (on player script): https://paste.ofcode.org/g2ukDfdKxy2qCBf8mdi4Vw
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
has anyone used tiles to spawn network objects
It feels like that would result in way too many Network Objects
true, but everything can go wrong if you dont do it right, in think the application i have in mind, although not more effecient, is more satisfying to me for level designing, but it requires spawning network objects from tiles
Do you mean spawning tiles as NetworkObjects?
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
no i give the tile a prefab, and it spawns that prefab has a script that spawns stuff on the nwtwork
keep giving this error though
https://paste.ofcode.org/uDzq4zcR4aj3ge3sGRQjBz code if yall curious
Odd. Could try OnNetworkPostSpawn instead.
right so this is unusual? also i tried to set a coroutien that wiats for 1 second, since im both client and sewrver (host) that should be more than enough time for everything netcode to be ready
but yea i still get this
Should probably check NetowrkManager.IsListening in Update()
i tried that too before
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
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)
Server RPCs only run on the server/host. You probably was to use the ActoveWeapon.OnValueChange event instead of a Rpc
I know the server RPC only runs on the server, but does that also mean it can't be called by a client? The goal of my code is to change the value of ActiveWeapon, then print that its value has changed on the server.
All clients can call a RPC.
But RPCs will be sent before the network variable updates
right, but what I'm getting at is that the function isn't run unless it is run by the host
That is something wrong with you inputs then
it's not, it works locally, but not when networked to the server
As long as the network object is spawned and active, an RPC will get sent
The object is spawned when a client connects to the server, as it is the player object. Is this enough?
Yes
so I'm confused. The inputs definitely are working as to be expected, but the RPC does not get called. This is my issue.
do you know what else could be wrong?
Dunno. If the print() is getting called then so is the Server RPC. You can open the network profiter to double check that it's getting sent to the server.
Just used the network profiler, it doesn't seem to be sending the RPC to the server. However, the client is definitely sending other data to the server, as I have player movement that syncs between all clients.
Weird. And there are no errors in the console on the client?
nope, no errors.
It's just weird, the host client can use the RPC, but not other connected clients
The host will just call server rpcs locally
ok, so it's just an issue of the client not sending data then, got it.
make sure the script isn't getting disabled anywhere
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
Does anyone knows why it doesn't subscribe to the OnValueChange?
this is the variable
nothing is printed
I try to avoid singletons whenever possible especially in networking. But try subscribing to it in OnNetworkSpawn
then how do you access them?
Why's that?
According to the documentation. if the object is spawned dynamically (which is the case. since it is in the player prefab). The order of functions is: Awake -> OnNetworkSpawn -> Start
it shouldn't make a difference
I'll normally use static events if I need to send data to other objects
do network variables support lists like that?
They do
I didn't get an error so it should be fine
Just personal preference mostly. But when network objects respawn on scene load singletons sometime act weird
for some reason when I subscribed for the event first time. there was no auto complete
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?
I had to make the functions and type the parameters manually
like this?
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
what is this for? the forceCheck
I didn't know that
but I wrote the logic already. there are 3 lists
it will take time to change them 🫠
Yea. when you can List in a Network Variable you have to call CheckDirtyState() for it to update
Anyone knows how to deal with this?
looks like the issue is with reparenting
In what way
The object that spawns (from the tile prefab aka the networkspawner) I believe it wasn't parentes to anything
Dunno. But it sure thinks you're trying to reparent a network object before the server is connected
Hmm perhaps it spawns the prefab as a child of the tile first? Then it tried to unparent
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
i found the multi-player play mode
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?
Drop in a debug console in the build to see what errors you are getting
aye, building a debugging build right. It takes a whole of a lot more time than usual though
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?
Pretty sure you just have to spawn NetworkObjects at the root level no matter what.
If its a tile network object then you would have to spawn it at the root level then reparent
doesn't look like it. I would use an RPC to call TileMap.SetTile()
Hmm I'll play around with that tomorrow and come back with the results
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
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);
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
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.
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
You wouldn't really need to in all honesty. change.Value would give you the updated Display Name
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
If you're subscribed to OnLobbyChanged it should pass through ILobbyChanges which you can then call .ApplyToLobby(_currentLobby) on
If you're doing that before this, it should work fine
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?
That is the correct way to change scenes. If the player object is getting spawned automatically by the network manager, then you just need to make sure that the player input components are not getting disabled or removed
they dont seem to be, i checked each time
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
the problem seems to only happen when load scene is called
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?
Make sure you are not using a Singleton for the player controller
There is no map for client Id to player Id. You would have to create that dictionary yourself
ah I see
so I would have to use onplayerjoined to pair the two IDs together?
I don't think onPlayerJoined will give you a client ID. I usually will make a Network Variable for the PlayerId on the player class
oh, i will check it
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
not much you can actually do about a hacked client without a dedicated server. But you could have the host try to lookup a playerId via Cloud Code and if its invalid, kick that client
so, acording to the guy that made it he said it isn`t a singleton, it has a static instance, but it doesnt have a dont destroy on load
you think it might be the source of the problem?
yes. because all players will using the same static instance
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
Comment out that static Instance. Anything needing it should call GetComponent<PlayerController>()
thanks a lot man! will do and try to see if the problem persists
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.
Don't use ID, just use player count.
many things are related to ids. So it will be hard to change them all
some items are not allowed to be used unless you have the specific id
I personally would not rely on those IDs for any logic. Either find simpler alternatives like using something like player count for logic that allows it, or store IDs yourself.
client Ids are increments each connection and they do not get reused as far as I know
They are reused
that is network id not client ids
what is the difference ?
every single network object in the scene gets a unique network id
Oh...
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
You need to make sure that both the move and fire actions are enabled. Also check in update for IsLocalPlayer so only the client's local player will move
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.
Has anyone done a lobby kick using Facepunch + Netcode?
As far as I've been able to find, it doesn't look like steam lets you kick a player from the lobby
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?
If they are instantiated with a random seed, then the clients could use that same seed.
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?
It is not built in to NGO by default at the moment.
It could be accomplished by storing a limited version of the game/world state on each client, using Lobby/Sessions to connect remaining players to a new NGO hosted game session and recreating the game/world with the cached information.
Thank you. Are there any manuals on how to do that?
Not really. I'm sure you could find people sharing parts of their solution on the forums.
Distributed Authority has host migration built in technically if it is something that fits your game.
Hey. How often does the server send updates to NetworkVariable? Is it every frame or once per value change?
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
not 100% sure, but i think it depends on the tick rate of the server u choose
and hopefully it's optimized that if it hasn't changed, it wont send it
almost certainly on change
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)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
my blood pressure has never been this high because of fucking coding, i tried asking chatgpt and guess what, nothing, nada
https://pastebin.com/QBQ2L915
this is my player fire script that is attatched on the player prefab, and that script above is the weapon script on the prefab of the weapon that is a viewmodel/child object of my player prefab
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
what could POSSIBLY be wrong?
When you reload, you're only resetting currentAmmo = maxAmmo on the server. The client still thinks they have 0 ammo.
what lines?
WeaponScript 159
so i need to update the ui of the client aswell?
Has nothing to do with UI. You use currentAmmo to check if the client is able to shoot their gun in your Player script. If it never gets reset on the client, they will never be able to shoot again after running out of ammo.
currentAmmo and currentMagazineCapacity should most likely be NetworkVariables to make syncing their values simple.
what about max ammo and max magazine capacity, shouldnt they also be network variables?
I would assume those don't change, so no they don't have to be
i barely understand my code now because of how braindead i have become from doing this for 8 hours straight counting with yesterday
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?
I mean, just simply changing them to NetworkVariables is not just going to fix everything - there are certain ways and rules of using them
well yeah but i tried making the player fire only change the server value and display it on the client, nope, nada
You can send that code if you want
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yes ai bad, but im not trying out for other 8 more hours of pure brain damage inducing code sesh
You're initializing both ammo NetworkVariables to 0, that's going to prevent you from shooting and reloading
0 or not, the issue persists
of not being able to reload after shooting that is
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.
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
shooting itself works without me trying to implement the reload logic
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
Have you put logs in the chain of calls that start from the Reload Animation Event completing?
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.
There is very little technical differences between them.
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.
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.
They use some flavor of Network Objects, Network Variables, and RPCs
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.
Photon has built in client prediction too
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.
NGO has a Network Rigidbody that will sync with the server simulation but it does not do prediction
network physics is inherently a little nightmare-ish and any game needing it probably needs something more tailor made
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.
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
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
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
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
It's referring to trying to cache references to destroyed objects. It's possible for the network id to get recycled.
The full docs here don't really mention it
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/
Brief explanation on using NetworkObject and NetworkBehaviour in Network for GameObjects
It would be crazy rare for something like that to happen. Normally a despawned reference would just return null
You're already using a network list. There is no need for a client rpc as well
Im confirming the client sending the rpc is the real client, and then returning an array to update their local inventory list
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
Help guys Facepunch and netcode need kick looby
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
I didn't think animator.Play() would work. But I guess the States get synced along with the properties
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
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).
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
How are you playing the walking animation?
Am I allowed to ask non-unity coding questions here?
I guess as long it's network related but dunno how much help we can be with any custom solutions dealing with raw sockets
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/
Thank you!
Its more of general advice regarding networking security rather than "I'm having problems help me fix it" lol
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.
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).
[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
My problem is solved
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?
@slender zodiac Post your code, ask an actual question, not this annoying LLM drivel.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Each player should not have their own camera. Unity only supports one active camera in the scene. You'll want to disable any camera not on the local player. Screen space UI should only be local as well
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 ()
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.
When you use Relay, whoever creates the match is the Host.
oh okay
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
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?
(no one can answer this without code)
You can view the network profiler to see exactly what is using bandwidth. But ultimately you will need to change your business model. Make in game items worth buying. Create a battlepass subscription. Make a 2.0 version and start charging for the game itself.
It's very confusing. There are Messages and Objects. It's just showing a graph and bytes sent and received
Under Objects, you will see the RPC and Network Variable data sent
https://docs-multiplayer.unity3d.com/tools/current/profiler/#objects-module
This guide uses Unity 2021.3 LTS.
im going to rewrite my guns, should I code around networking or just make the guns work first and only then try to implement networking?
Definitely needs to be networked from the start. Unless you just want to do it twice
The rpcs are not that much
I have 2 NetworkList of struct
1 is sent only once when player joins
Other struct can change multiple times
whats in the struct
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?
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
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.
There are close to none. Just players position and y rotation, with animation rigging target transform
I just have lobby and player roaming around 😦
this is what the profiler shows
Another Example
is the animator taking that much usage?
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
are you changing parameters every frame? idk if that uses the tick rate, you might need to rate limit that yourself
check out the bit about rpc send params: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/clientrpc/
ClientRpc and ServerRpc are legacy features of Netcode for GameObjects and have been replaced with the universal RPC attribute. This documentation is for legacy use. For current projects, use RPCs instead.
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 😛
there is nothing about the size limit
that link is about the second part of your question
What is the difference between [ClientRpc] and [Rpc(SendTo.ClientsAndHosts)] ?
Yes in Update there are few. But how doing this affects that. Since I am doing it in local animator and it may not change everytime
Animator transform should only send when it changes right
ClientRPC is legacy now use Rpc
oh yeah i linked the old docs by mistake (but the current docs also use ClientRpc i guess?)
You can configure the Rpc, ServerRpc and ClientRpc methods in the following ways:
look at the RPC target bit
Do I update me Netcode version? I think it have many benefits in less bandwidth useage
1.12 rn
1.12.2
every time it changes it'll send an RPC, if you have animators that are frequently setting parameters maybe you don't want to be syncing that with NetworkAnimator
Great. Thank you
Based on profiler screen shots do you see any other thing which is causing bandwidth usage alot
For the size limit part. does anyone knows if the rpc called in unity transport have a limit on the data?
I'll try to optimize anim
Pipelines are a core functionality of Unity Transport that allows selectively adding layers of functionality on top of the standard unreliable datagrams that UTP provides by default.
iirc all NGO RPCs use fragmented pipelines
No, anything over the MTU will get fragmented across multiple packets. But you also really shouldn't be sending files in an RPC
I would say to always update the package when there are no breaking changes.
Is it fine if update is not showing in editor but we update using manifest file
I'm sending a FixedString4096Bytes
That's fine. You can also specify the version number when adding the package by name
Thanks
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.
Steamworks authenticates through the steam client. If someone has hacked a steam account there is not much you can do about that
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
Build size and ram usage are 2 different things. But yes running 2 servers will double the ram used
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
You shouldn't be destroying scene objects. If the object can be dynamically destroyed then it needs to be dynamically spawned
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.
Should just be able to type in localhost, 127.0.0.1, or 0.0.0.0 for both editor instances
Also there's MPPM which is the newer tool and tends to be a little easier to use than ParrelSync
Overview of Multiplayer Play Mode
I'll check this out!
Also the port does need to be the same on all instances
Thanks I changed the port back
My address is 127.0.0.1 already :/.
Maybe it's just a parrelsync thing? I'll look into mppm!
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
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
No, you can't. There need to be only one source of truth. If 2 clients were to write to the same variable at the same time there would be race conditions.
Now what you can do is use Anticipated Network Variables. Each client can change it locally, send the RPC to the server, then get authoritative updates back from the server
Why is it that when a player leaves the lobby, they are visually out, but their data remains in the lobby?
might have to update the lobby data. There should be some kind of GetLobbyData for steam.
Just wanted to thank you again as I tried Nakama for a few days and it's lovely for my use-case! Highly recommend.
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
Apparently they have experimental features related to prediction. Prediction and PredictedRigidbody scripts/components specifically.
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/MrRobinOfficial/Guide-UnitySteamNetcodeGameObjects
A tool for sharing your source code with the world!
Community contributions to Unity Multiplayer Networking products and services. - Unity-Technologies/multiplayer-community-contributions
Can you post SocketManager and ConnectionManager?
im assuming thats from the package? i can go find it one moment
im not very familiar with networking and i cant seem to find either
i will keep looking for now tho
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.
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
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
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...
I understand but isn't this a part of the legacy system?
because I don't have this method im trying to use
// Send to a specific single client ID.
public BaseRpcTarget Single(ulong clientId, RpcTargetUse use) { /* ... */ }
RpcTarget and BaseRpcTarget are classes, not functions.
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...
@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
}
That's not what the example does. I would assume you just pass in RpcTarget.Single(clientId, RpcTargetUse.Temp) like they do in the example.
SpawnObjectClientRpc(chunk, RpcTarget.Single(clientId, RpcTargetUse.Temp));
oooh okay i see, thanks man
If anyone is able to help, i also attached the netcode integration repo i used for it, i can try to provide anything i can cause im really stuck here lol
I didn't think Steam P2P was deprecated
i think in Facepunch it's built on the deprecated ISteamNetworking interface
there is a non-deprecated steam P2P system
Oh so the Netcode Facepunch Transport will need to be updated eventually?
In that case you shouldn't have to worry about working with sockets then. NGO will work like normal with it
i think OP may be using the API directly not using an NGO transport? 🤔
does anyone know why i see both scenes open on my server, but not on my clients?
Is this intended??? 👀 Im using FishNet btw.
The server has to have all scenes loaded. By default the clients should be syncing with all loaded scenes on the server. I don't know how fishnet handles scene management
Doesnt this mess up how the server sees movement/physics? (If a player is walking through a wall that is there on the server but not on the clients)?
Yes. That's why the clients also need the scenes to be synced with the server. The scenes need to be the same on both client and server
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
Most likely you are not switching scenes with the Network Manager Scene Manager
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
any way of doing that?
remove the player prefab from the network manager and then spawn the player object manually
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?
By default, you can't have the client and server in different scenes. You can use Scene Validation if you need server only scenes. But if you trying to have players in different scenes, that will not sync. You could have the scenes loaded additively and place them in different locations. Or you could use NetworkHide/Show() to hid objects a client should not see
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.
Title screen offline (in terms of NGO). You can use other packages to group people up in to lobbies and matches that are lighter weight.
Main scene loaded with the NetworkManager so it's synced on joining a match.
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.
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
I would just use Unity Relay during testing and wait till you get a steam dev account so you can join the steamworks developer group.
Isn’t that kinda pointless? Unless I’m mistaken, wouldn’t I just be writing the net code twice?
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)
Unless you specifically need some features related to Steam and/or Steamworks, I would not bother with it at all. There are better alternatives.
Well I wanna add the game to steam
If you are using Steam P2P then you will have to either use the Facepunch Transport or the steamworks.net transport
You don't need Steamworks to release on Steam
That doesn't require you to use Steamworks.
I know but I want to utilize steam features to make it easier for people to host/join with friends
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
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
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?
What do you mean by split input?
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.
Is it local co op or remote? They host should have authority and the client would send inputs to the host
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
so its, 2 clients running on the same PC? Will this be 2 players controlling one object?
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.
Yea. you can give the host(player1) authority over the object and the client(player2) authority over the main camera
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.
You probably aren't gonna find any tutorials covering that. Make them separate objects. Put Network Transform with Owner Authority on each
so i should make lets say
-Player (Capsule)
-Playercamera
-PlayerMovement
And those two have their own scripts, so one for keyboard one for camera?
I would have the player camera as its own separate object
Server RPC and so on only work with ClientID?
ServerRPC or RPC(SendTo.Server) will only get sent to the host/server. You can change them. RPC(SendTo.SpecifiedInParams) you can send to specific clientIds
good?
I don't know what this is supposed to be
If the key is the client id then that should be fine
yes
for some reason, the second player is recorded under the steam, and not the client's key.
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.
Hey, im sorry for asking again but i havent been able to find a solution to this issue yet, if anyone can point me in the right direction that would be awesome!
With Scene Management disabled you are forced to use Custom Scene Management
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
I would simplify things down to just a scene with NetworkManager with FacePunch Transport and a simple script to set the transport's Steam ID and see if you can get that connected.
how do I get the client Id of another player?
i see, fair enoguh, i do get space war running and it does (i think) connect to steam, but in the lobby it just spams that error lol
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.
thanks tho, i will try that when i get home
ty
NetworkTransmission.instance.AddMeToDictionaryServerRPC(SteamClient.SteamId, "FakeSteamName", NetworkManager.Singleton.LocalClientId); ?
Any advice before I start making one
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...
My advice would be to avoid it altogether. It's a huge pain to rewrite all the sync functionality
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
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?
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?
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
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?
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
You probably shouldn't be joining the network before logging in. Normally, authentication happens with a rest API before starting a session. I would also caution against trying to roll your own authentication.
But to answer the question, you would need to set anything to want to persist to Don't Destroy On Load. Or you add scenes Additively
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?
Players automatically move to the new scene
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
Are you not spawning the players manually?
i am
Vector3 spawnPos = GetSpawnPosition(clientId);
GameObject player = Instantiate(playerPrefab, spawnPos, Quaternion.identity);
var netObj = player.GetComponent<NetworkObject>();
netObj.SpawnAsPlayerObject(clientId);
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...
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.
Wait, what do you mean locally? Client 1 player prefab is getting destroyed on client 2?
yes
That is something happening in your code then.
its the prefab syncronization causing the main issue for me
That doesn't destroy prefabs though
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
Network objects can't spawn before it's connected. If you are instantiating a player object locally before you connect to the network that will cause issues.
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
The simple solution would be to not immediately connect on application open. Title screens don't really have any business being connected to real-time networking.
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
This is probably your best bet.
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...
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
Correct
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
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?
Depends on when you are checking IsServer. If domain reload is disabled then mppm clones will not update code. If you don't save the scene in the main editor then the clones will also not update
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.
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
im confused though because searching online gives me snippets exactly like that
wait I misread that snippet, still waking up apologies. Nothing in there is messing with a networkvariable?
and yeah, in the OnNetworkSpawn of the instanced object, I get the same warning
Are you sure your looking at the relevant problematic code?
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
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?
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
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
well I just realized my GameManager was missing a NetworkObject component and now it's working with the setting of the variable on the pizza shop (OnNetworkSpawn). Only just now did it give me a popup that it was missing. My bad!
Thank you for the help regardless 😅
yeah its making more sense as I go. Just getting over the initial hurdles for sure lol
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? 🤔
Ensure the object is spawned as well as enabled on all connections at the time of calling this RPC. Make sure not to destroy any components on the object as well.
Turns out I had a typo in my spawning script. Thanks. 👍
Network Manager HUD not showing in build, who can help with this ?
Most likely, you are mssing a camera in the scene
Nah, i try create a camera, but network hud not visible in build
If there is a camera in the scene and it's not rendering, theyn the camera's renter target display might be wrong.
I already tried to add a camera to the scene, but unfortunately nothing changed, mirror hud did not appear
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
You would set the NetworkManager Protocol Version if you need to make them incompatible
Oh no i want them compatible, hence asking if there's any automated checks that might stop that
As long as the protocol version is the same, then it will connect.
if i want to make mmo, which way is the best solution for dedicated server
The only real solution is to self host. Plus you'll need to team to build the server backend. But if you have enough money the you can use AWS, Azure, or Google Cloud.
oh i mean mirror/photon/C# netcode, which is best for mmo😂
Honestly, it's whichever your team is most familiar with. Whatever you go with will need to be highly customized in any case. Mirror does have the uMMORPG asset on the asset store.
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.....
What version of NGO are you running?
I used a really old one, I'm updating now and testing if the problem is solved
Problem solved after updating
@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
weird. it only sends update when the transform moves
I have few Client Transform on player bones, but they are disabled until player dies (for ragdol sync purpose). Does that cause any bytes to send when disabled?
it would be good to know what network object is sending so much data
is it possible in profiler?
That could be. you can try disabling the sync pos/rot on those transforms instead
I'm not sure. I don't think so since network transform is using custom messages
omg i tried it, that completely put the graph down
still few messages but lower
That messages were from my other client which had it enabled
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;
probably. Though I honestly would not worry about syncing a ragdoll. as long as the root is synced up the limb placement shouldn't matter
Ill experiment with this for now, if this is causing reduction in huge bandwidth usage then i will leave it enabled or will off it sometime in future
I was paying a lot for this simple mistake
Thanks for your help mate!
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.
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...
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
All clients are skipping identically - likely an issue with your movement code rather than network lag.
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...
Likely. 4 instances going on a laptop probably won't run well unless it's higher end.
Now that I checked in my game outside when the part of the gameplay that also happens, this showcase model in the build, runs in slowmotion or skips a frame, in the editor that doesn't happen
and the build is running in one instance
That just seems like low frame rate
ok, figured it out, I had to turn off vsync on the project settings and now runs fine, srry to bother!
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?
Are you saving it to a fixed string?
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
I mean based on what your saying thats an infinite loop
its just a nextension of amethod, that calls the base function of the method
apologies for the lack of clarity
I can't give a perfect explanation on why, but usually you should just avoid doing anything extra like that with Rpc function definitions.
If you need to, make wrapper functions to do so
I was creating two inventory manager classes, one for player, one for containers, and I was under the impression that you had to caall the basae function within your overridden function, like in Java, but c# is different, and you cana call functions on a class that doesnt contain the function, as long as the original class marks it as virtual
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
I think generally you would reference items by an ID number so inventory and chests would just be a list of Ids
You can also open up how Unity implements NetworkObjectReference and make a very similar implementation for your various scriptableobjects to make it a little cleaner when using in network related stuff
Since it just basically wraps up getting something via index
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
The Network Variable has to be on a spawned Network Object. but it can be accessed just like any other public variable
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?
maybe. but seems like way more trouble than its worth. You'll have to rip apart Network Manager Spawn Manager to figure something out.
@sharp axle what are your thoughts on capacity planning specifically for a multiplayer workload? Asking just to ask.
Any tips?
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
Regarding player capacity, I believe that depends mostly on your server hosting provider. What hardware is the server running on? How much bandwidth is available? can new servers be easily load balanced or dynamically allocated?
You have to design it networked from the very beginning. Adding networking after the fact is going to be a bad time
I essentially added very basic functionality of setting one variable in an inventory slot object equal to an item variable. But it just became so complicated trying to create additional containers etc
It’s just the lack of understanding of how NGO works for the most part, it’s pretty confusing while learning it
are you networkvariable pilled yet
I would use NetworkVariable<List<Item>> for the inventory. then the UI could loop through the list and populate the containers
Not a NetworkList?
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
You might be overthinking this. The network List is already being synced. You can use the index of the list as the UI container slot. Populate the slot with whatever is in the SO for that item id
I’m doing exactly that right now
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
oh are you using a singleton for the inventory?
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
Seems like you could skip the dictionary and have the UI manager read from each ash player's inventory list directly
for some reason each player that spawns tries to execute eachothers servewr rpcs
yeah I literally just changed that haha
this is the main manager script
You'll need to check for IsLocalPlayer before sending any server RPC
thanks so much dude, thata actually helped
man its so buggy, but im finally getting closer, idk why this is so difficult haha
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
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
in fact i already implemented that, im just finding a better way to cut down possible costs
That would be bad for security if you could. The network cost of a connection attempt is not worth worrying about
ok , heres my new workflow
leave current session -> join session -> (unity verify password if exists) -> joined room
if failed -> join back to previous one (lets say room A -> B -> C, if C is failed, join back B)
You would need to check that the previous session still exists but that should work.
dw i have a null check for that
i think i cannot leave session asap, it needs to be the last thing instead
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
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
what do you mean by loww level aapi
Unity transport
It syncs, you just do not have authority to perform network related functionalities to it.
its pretty confusing whaat ownership actually does, even after reading NGO docs like 5 times
ah okay
i.e. change a NetworkVariables value, have a NetworkTransform sync position
but if you send a server rpc that changes the network variable, even if you dont have ownership, thats fine?
this seems so much more complicated than it needs to be
Right. The server is the one running the function that writes to the NetworkVariables value. The client is just sending a message requesting the server to do so.
alright
Just takes getting used to. It’s a large change-up from offline development.
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
Most of the popular ones are all very similar to NGO. They are among some of the simpler ones there are.
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
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
I would have to put that at the start of a lot of functions haha
Would be a good handful, shouldn’t be too many in all honesty
Should be to start by default, yeah
kk
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
Just FYI, NGO is open source. All the code is in the package folder.
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.
I did not realize
I’ll check them out
Photon's libraries are great, but if you think NGO was complicated to use you are not going to have a better time with Photon.
Its not complicated, I can read everything and understand what it means, and can use it, but there’s an expectation that you must understand how the entire system works together, very well, otherwise nothing works. So you have to learn all of NGO before you can make a functioning game
Unless your game is pong
You shouldn’t have to get down much more than how to use NetworkVariables and RPCs before you get started.
Adding networkobjects and ownership with those just complicated everything very quickly. I’ll probably try again
should I be using netcode for entities?
Only if your game is already being built with DOTS
You should not be adding networking to a single player game. That is just going cause a ton of rewrites. The game needs to be designed from the beginning to be multiplayer
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
Every client
kk
Deleted my entire inventory system and now I’m going to build it from scratch
Is NGO sufficient to support a lot of players
"a lot" is a very useless piece of info, respectfully
and there also is no direct answer. It largely depends on the type of game and how optimized your network code is.
Thanks that was about as useful
Like multiple players, not a small coop online game
is there a very rough number?
eg. some people might consider wow to be "a lot"
some might consider 8 to be a lot
Some friendly advice, you should either start with a really really really simple version of your inventory system or start with something else in your game if you're just beginning with networking. Inventories can get complicated even without networking, and that will only serve as a detriment to your learning experience with networking.
also yeah, OnNetworkSpawn is your ngo equivalent to Start. means the object is spawned on all clients in the lobby, all it's networkvariables are setup etc.
Considering the amount of info NGO sends over the network, probably 8 would be a lot
Yeah I think you’re right
Then yeah it can absolutely be fine
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
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
Oh sweet
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.
pretty simple question, using NGO, all I want to do is have a client spawn an object to everyone else
Send an RPC to the server to have it spawn the object.
Any errors or anything noticeable happening? Or just nothing?
Make sure the prefab is in the spawnable prefabs list
either i can get the host to do it but then the client errors OR neither of them do anything
you'd probably have to post code
also make sure the thing calling the rpc is spawned
if its not spawned it can't send rpcs
oh shit
What is it then, if not spawned?
just instantiated locally ig?
Show code
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
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?
how else would I do it?
it is apart of a network behaviour
Just do the code in that rpc
but isnt the client not allowed to used .spawn()?
(I'm not a network expert though, just played a bit with networking for a prototype some 2 months ago)
I don't know... is it? It should be able to, imo, but I don't know
yeah i get this error
NotServerException: Only server can spawn NetworkObjects
Unity.Netcode.NetworkObject.SpawnInternal (System.Boolean destroyWithScene, System.UInt64 ownerClientId, System.Boolean playerObject)
Okay, so change the name to end in ServerRpc and try again
Your nodes don't look like they're spawned on the network, so they cannot send RPCs.
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
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 😄 )
yeah i dont
no i shouldn't, the only network object I have are the nodes that are spawned and the hosues
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
Im going to just try using the low level unity transport library
Just so you know, that is actually going to be way harder. If just want to handle your own messages then look into using Custom Messages in NGO.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages/
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
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.
Usually you just put calls like this in a try-catch block to catch the error and display to the user why they couldn’t connect. There’s no way to check if connecting is valid except for actually attempting to do it.
man its a lot easier to do networking in c++ than unity c# lol
@untold holly If you are using the Sessions SDK, then you can use QuickJoin matchmaking with a single button
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/matchmake-session#find-a-session-with-quick-join-using-unity-lobby-service
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 😛
Player characters should destroy when their owner disconnects. You can also mark any Network Object to be destroyed when it's owner disconnects.
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.
Ok I figured as much. I will look into Connection events, thank you 🙂
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
So long as you're subscribing to this you should be getting notified of disconnections
I wouldn't think MPPM would effect this, but I haven't used it so I can't say for sure
works if i build and run outside of the editor
weird, but good to know 😛
It does work with MPPM, could be a timing issue though
Timing as in?
depends on when you are subscribing to the Connection Event
Ah, right.
Well I subscribe long before any player is actually even spawned into the world. But I get what you're saying, ill have to play around with it a bit more
Only if it's using Network Variables or RPCs. You would probably want to disable it if its not the LocalPlayer.
I still can't figure out if Rpc works with SteamID?
Like using Steam ID to send an RPC to a specific client?
Once you are connected through the network manager, RPC will use client ids just like normal
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
In my case I have created a PlayerData struct which have client id, auth id, player name, other player related stuffs.
And I use Dictionary client id key and player struct variable. And I use Network List of player structs to update the dictionary using callbacks of NetworkList.
Once these implemented correctly it's super easy to get player data just by using its client id
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
...
}
I don't use fishnet but you'll need to make sure the object is actually spawning on the clients
Yeah, sadly that's not the problem
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.
Is there a way using NGO to check before connecting if there is a host already using a specific IP and port?
There is no way to check without actually trying to connect and failing
But when I try to connect, I get errors. Even if I use try catch, those errors still appear and don't let me do anything, let me explain
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
You need to do it the other way around. try to connect as client first then if that fails, start the host
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
When the socket fails, that is usually a firewall issue. Make sure Allow Remote Connections is checked if you are testing on different PCs. I would also use the Sessions SDK so you don't have to worry about typing in the IP and port
I'll take the sessions sdk into account for latter projects, but this is homework for my college class, which basically makes me do it this simple way.
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?
if you are connecting to localhost then it shouldn't matter
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
Are you calling UnityTransport.SetConnectionData?
The NetworkManager is a required Netcode for GameObjects component that has all of your project's netcode-related settings. Think of it as the central netcode hub for your netcode-enabled project.
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
That's weird, it should not be looping. As far as I know it will not automatically retry the connection if it fail
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
My mistake there is a max connection attempts in the Tranport
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?
You'll get a Disconnect event from the transport. I'm pretty sure OnClientDisconnect will fire
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?
I think I'll just make it a coroutine with a waitforseconds equal to the connect timeout * connection attempts
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
That's how I use Facepunch.
It's a pity there are no knowledgeable people here
So after you connect with the Facepunch Transport, you will get a client id from the Network Manager. That is the id that RPCs will use.
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);
}
got fixed
Right here?
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
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 !
You can use the Relay Service for that. Sessions SDK and widgets makes it super simple
thanks ! i'll check that, people told me to use photon is it overkill / too much or is it equivalent ?
Its roughly the same. Photon is a little more expensive but has more built in features
Thanks then i'll check both
Just like that bro?
Yes. But that doesn't give you the steam id. It gives you the client id.
I don't need a steam ID because I only display my nickname and avatar through it.
clientID 0
yea, the host client id will always be 0. it will go up by 1 for each connection.
for some reason, when the player connects to the lobby, it does not show in the logs.
On Client Connected will only get called on the host and the connecting client. other clients already connected won't get that event. For that you need to use NetworkManager.OnConnectionEvent
Or you could use OnNetworkSpawn of the player objects
could you please show me an example on my code?
You can see it used here
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}"); ???
I'm not sure what you mean here. You wouldn't use either of those with OnConnectionEvent
I don't really understand what you're talking about.
OnClientConnectedCallback and OnClientDisconnectedCallback are being deprecated and replaced by OnConnectionEvent which does the same and more as the previous functions.
You can basically use this code as exactly as it’s shown here. Just put your own function to replace RefreshLabels. You can name it whatever you want and give it any return type or parameters that you want.
You can get client ID through connectionEventData.ClientID
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
You shouldn’t have to make your own. You would just catch for a SessionException instead of just the regular Exception.
They’ve got a pretty wide range of errors covered already
Anyone know how to make ready and start system in netcode
ohhhhh
ty i will check it out👍
actually im making a display UI , to display the sessionexception that i will catch , or was trying to find out before ,not the whole system
You can use Session/Lobby Player property for this
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/session-op-client#add-a-player-property
Could you show me an example?
This is the example
#archived-networking message
I didn't figure it out.
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?
difficult
I think maybe you're overestimating the "non-deterministic"ness of Unity's physics engine. instances of the client prediction and server simulation diverging by a significant amount are going to be rare and mostly can be cleanly masked with interpolation tricks
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
I don't really know to be honest. The part of Unity's physics engine that is oft-quoted as "nondeterministic" is just that it uses floating point math, which can be done at different levels of precision on different hardware. I suspect whatever code you are writing is subject to the same limitations anyway
I can't comment on what the best choice for your particular game is without intimately knowing the details of it.
Makes sense, thanks for the insight, I’ll keep digging
disconnected no?
that's what I see in NetworkManager, but how do I make a discount?
You do not use OnClientConnectedCallback or OnClientDisconnectCallback. Forget about them completely.
after all, I use them, should I delete them and just use one method?*
OnConnectionEvent yes?
OnConnectionEvent is a replacement for both of them. So you either use those, or OnConnectionEvent. Not both.
okay, ty bro
Not really a direct answer to your question but their competitor Stumble Guys uses Photon Quantum which provides a deterministic physics system for you I believe.
I don't know the details but its way more likely that they using custom character physics. Also a lot of those type games the movement is a bit janky by design to hide the prediction sloppiness
Interesting, thought photon was just a netcode framework not physics or anything
That makes sense, smart
They have their own physics, voice, and cloud relay services too
wasn’t aware thanks, gotta look into it
It's a bit more expensive than Unity services but its does more for you.
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
good?
Only I do not understand what to do further how do I clientId get the players who connect?
I'm not sure I understand your question. Do you want the Client IDs of the people already connected?
Yes, so that the host can send Rpc messages to them.
and have them get it from the host
eventData.PeerClientIds
I think you can also just add ConnectionEvent.PeerConnected as a case to your switch statement to do what you're wanting to do.
without the need for the Host to send any RPCs
Also if you just want to broadcast to all clients, you don't need to specify any client IDs.
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
why doesn't it work?
What part is not working?