#archived-networking
1 messages · Page 29 of 1
But isn't this even more exposed than hardcoding, or does unity have an option for encryption?
Are you trying to send logs from clients to your email?
That is correct. I have it working already with system.net.mail, but my current method requires the client to have the sensitive SMTP server info
Is there a specific reason the client needs to send this to email? I would consider sending the data to an HTTP server and deciding there what to do with it.
How can i Sync in unity objekts that are already in the scene? with mirror;
I have a gameobjekt in my scene, with a key press i can add child objekts. now how can i take the childobjekts and sync them to the client with mirror.
i tried NetworkServer.Spaw() and NetworkServer.SpawnObjects(). also i tryed to clone the gameobjekt withe the children but that also didnt work.
does in-scene networkobject automatically spawn on other client?
If you are using NGO, yes. As long as Scene Management is enabled on the Network Manager.
so what if both client having the same networkobject betfore starting host-client
You shouldn't see anything happen but the client scene objects get respawned
can i set networkvariable beforespawning?
i know it gonna say that i couldnt edit it before it spawn
work around?
The functionality is not built in, as far as I know.
Why do you need to access a NetworkVariable before the object is spawned?
just thinking it would be more convenience to spawn object with value set by the server
like spawning an enemy with half health
It will technically work but the real way is to use OnSynchronize()
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior-synchronize/#pre-spawn-spawn-post-spawn-and-synchronization
NetworkBehaviour is an abstract class that derives from MonoBehaviour and is primarily used to create unique netcode or game logic. To replicate any netcode-aware properties or send and receive RPCs, a GameObject must have a NetworkObject component and at least one NetworkBehaviour component.
ooooo nice
I am making an online ultimate tic tac toe game
but when i am calling Rpc from the host side it is not updating on the client side
Is it necessary to make my play board a network prefab?
Send the function?
sending
oh i forget
my bad
[Rpc(SendTo.Everyone)]
public void SetActiveGridRpc(string grid)
{
if (activeGrid == -1 && gridState[GetGrid(grid)] == 0)
{
activeGrid = GetGrid(grid);
LoadGrid(GetGrid(grid));
}
}
No reason that shouldn't be called on the client. What changes are you expecting to see?
I want it so that when a grid is selected
it is highlighted on both sides
and is loaded in the play area
the total board is of 9 * 9 and the playboard is of 3 * 3
3*3
is in-scene object is automatically own by server regard of whether its on client or server?
if so how to make the in-scene object own by the client ?
[server rpc] in onnetworkspawn?
by in scene object do you mean local objects?
network object in the hierachy
if it is in hierarchy
then both server and client will have there own instance of that object
yeah but they both own by the server
send a serverrpc from the client side to demand changes from the server
yeah but its alittle convolutedd
you cant make direct changes from client side to server side objects
and if you want to have seperate objects for the server and client use the Spawn() function to spawn it on the client side
the client will be able to make changes to that object
but if you want them both to be synced
then you would have to use ServerRpc to make the similar changes on the server side too
nvm im dumb
use NetworkManager.Singleton.LocalClientId instead lol
turn out i just needd the client id
if it works then there's no problem in that
oh
what game are you working on?
oh, nice
Yup I was thinking that might be the best way too. Cheers
Hello guys, hope you are having a good day!
Are there any know issues/complications when using NGO + Relay and trying to have a mobile player as a host?
We have tried:
- PC Host / PC client -> Sucess
- PC Host / Android client -> Success
- Android host / pc client -> Fail
- Android host / Android client -> Fail
Hence why I believe the issue lies with Mobile trying to host the game.
Mobile platforms can host with no problem. Hosting takes more resources than just being a client which might be where the problem lies.
Turns out quantum console had a missing reference that caused expensive async code to be called every frame, which was dwindling performance to the point of a crash, the hosting failing was a consequence not a cause xD. But thanks
Hey, i am trying to get the local player but this is always null, also the network manager spawns the player and player prefab is set
NetworkManager.Singleton.LocalClient
When are you trying to get this?
OnNetworkSpawn
of what object?
on an object which is spawned by the host
and also tried to debug log that on network spawn on the player itself
An workaround that i did is on network spawn for the player owner is this
Yeah, that looks like a cleaner solution anyway. Is this the player object you're running this code on?
yes
Hey, i am trying to get the local player
using NGO, and I'm trying to get the player to throw a grenade.
The grenade needs to be spawned and "given" back to the weapon manager component, so it can track it
i guess the flow would be
player presses grenade throw button
server spawns grenade for the player
player releases grenade throw button
server launches grenade with force, etc etc etc
is there a less delay-inducing way to do it than sending an rpc to spawn it, and then an rpc to give the reference back to the player?
Giving ownership of the grenade to the player who threw it when you spawn it will probably make getting reference easier
i feel like i'd then need to find all the grenades in the scene, see which ones are owned by that player, then filter out the ones that haven't been thrown
I would store it somewhere locally.
There's no way for the client to "know" when its been spawned on its own, though
That's why I suggested giving ownership to the player who threw it.
In OnNetworkSpawn() of the grenade, you then can use OwnerClientId to find the owner and tell them to store reference.
i think I have figured out a roundabout way to do it
Is there a way to pass a network prefab via rpc?
Network Prefab?
yeah, or an unspawned network object/game object
the server has no way of knowing which grenade the player is trying to spawn
You'd most likely want to use something like an enum to tell the server which grenade type is being requested to be spawned
that's
gonna be a big enum
I'm also going to have to map each grenade prefab to each enum entry
Just do it by index
public enum GrenadeType
{
GrenadeOne = 0,
GrenadeTwo = 1,
GrenadeThree = 2
}
I don't know how many grenades im going to have yet
Why does that matter?
You can add more without issue
The server would just store a list of the grenade prefabs, and do something like:
var grenadeToSpawn = grenadeList[(int)grenadeType];
to avoid hardcoding the numbers of grenades, the player and server both have a reference to the grenade prefab, and then the player finds the index of that grenade prefab
because i know for a fact im going to forget which number is which
@uncut wren This isn't hardcoding. This line of code will never have to change. All you have to do any time you make a new grenade is add to the end of the enum, and drag and drop the new prefab to the end of grenadeList.
I can't get my unity app to receive data over udp
using UnityEngine;
using System.Net;
using System.Net.Sockets;
public class UDPListener : MonoBehaviour
{
private UdpClient clientData;
private int portData = 50505;
private IPEndPoint ipEndPointData;
private System.AsyncCallback AC;
private byte[] receivedBytes;
void Start()
{
InitializeUDPListener();
}
public void InitializeUDPListener()
{
ipEndPointData = new IPEndPoint(IPAddress.Any, portData);
clientData = new UdpClient(portData);
Debug.Log($"UDP client listening on port {portData}");
AC = new System.AsyncCallback(ReceivedUDPPacket);
clientData.BeginReceive(AC, null);
}
void ReceivedUDPPacket(System.IAsyncResult result)
{
receivedBytes = clientData.EndReceive(result, ref ipEndPointData);
ParsePacket();
clientData.BeginReceive(AC, null);
}
void ParsePacket()
{
Debug.Log($"Received packet from {ipEndPointData}. Length: {receivedBytes.Length} bytes");
// Here you can add code to process the receivedBytes as needed
// For example, converting to a string:
string message = System.Text.Encoding.UTF8.GetString(receivedBytes);
Debug.Log($"Message: {message}");
}
void OnDestroy()
{
if (clientData != null)
{
clientData.Close();
}
}
}```
i can receive the data with a similar script if i don't run it in unity, but as soon as i try to use it in unity it won't receive the data
so unity must be blocking it somehow i just can't figure it out
Is it better to upgrade from Unity Transport 1.4.1 to 2.3.0. Since the package manager does not show update and Unity Transport is installed as dependency because of NGO.
Should I update it?
2.3.0 does not show Release tag on it
If you don't need any of the features or bug fixes in Transport2.0 then no, you don't need to. Though it is recommended to use the latest versions
I was wondering about the R tag which is not on v2.3.0
I believe that depends on the version of the editor. In Unity 6 it has the release tag
Ohh I see
Hey guys im learning NetworkVariable but i got an issue where it just doesnt update the variable for clients, im using multiplayer play mode to test.
Pressing T update the variable ONLY for the one who pressed it
Network Variables are tied to the Network Object. So only that player will get the Speed change
so i have to create the variable somewhere else ?
Using an RPC would be easier for that case. If you put it on an inscene object then only the server would be able to change it
like i create the variable on the server ?
Or you can use a RPC to set the speed on each player
Hey I was having some problems with lag after I switched my game to relay and I was just wondering if the fact that I'm running both host and client on the same pc would be significantly contributing to that
Relay will introduce more latency than testing on LAN or using a dedicated server
Host and client being on the same PC will be more networking intensive, but shouldn't really cause significant lag I would say
ok so if I'm planning to launch with relay, the lag I'm getting would be basically the average experience?
Most likely, yes. Doesn't hurt to do some testing to confirm your latency isn't out of an acceptable range. Relay is a capable solution for many types of games. If your latency is crazy high, most likely something else is wrong.
If you're allowing it to autoselect a region, make sure it's doing so correctly and is selecting a region that's close to you
ok, great. I know I have some optimization issues since its my first time networking so it's probably mostly from that
thanks
does NGO work with the new input system?
It works great. Though you're not really sending input events over the network
Do i still need to make the input actions in awake?
It works like normal. But you should disable the component if it's not the local player
so I fiddled with it and
I don't know when I need to set it's refrence to itself, normally I would just have the input actions equals new input actions, but I'm getting some timing(?) issues where on enable and on disable run before the input actions has gotten a refrence to itself
er go creating null refrence exceptions
does it need to intialize in on network spawn instead?
I'm using the Player Input component and just disabling that component in OnNetworkSpawn() if its not the owner
@sharp axle what's the difference in player input and
InputActions inputActions;
void Awake(){
inputActions = new InputActions();
}
It handles the input actions for you
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.10/manual/PlayerInput.html
how do people recommend handing unit actions like a Move() action, an Attack() option or a CastSpell(Spell spell)? I've tried the command pattern but recently learnt that that doesn't work because you cant derive from INetworkSerializable.
Usually, I make each action an RPC. Or if you really need a generic PerformActionRPC(), send an enum as a parameter and parse it on the other side. The spell example could also be a enum for spell type and then an INetworkSerializable for any spell data you might need to send
ah right im silly 🤦 was over engineering it in my head for no reason haha
tyvm
You're talking about using the generated c# input, which is what I do. Let me share some snippets of how I did it and basically have to never worry about it
I create a static instance of the generated input (this is to avoid issues, when more than 1 script want to access some actions, an easy hack to never worry about it)
public static class InputManager{
public readonly static PlayerInputGenerated PlayerInput = new();
}
then in the playercontroller
public override void OnNetworkSpawn()
{
[...codecodecode...]
if(!IsOwner)
{
return;
}
InputManager.PlayerInput.Player.SetCallbacks(this);
InputManager.PlayerInput.Player.Enable();
InputManager.PlayerInput.UI.Disable();
base.OnNetworkSpawn();
}
so you set the callbacks to be received only by the "local player" after it is spawned and knows its the one
so you can be sure that any function called by the callbacks, like
public void OnDash(InputAction.CallbackContext context)
{
if(context.performed){
dashComponent.Dash();
}
}
are called only by the local player, so no need to perform IsOwner checks.
is mirror still the way to go or has it changed over the years
there are, and always have been, multiple options that you can choose from depending on your goals & needs.
Hello! Quick question: I am using NGo + Relay + Lobby, and I want to handle when a client crashed (meaning they do not send any disconnection messages). My issue is that right now, NGO timeout the player correctly, but the lobby does not. What is the correct way to check if a client is not responding anymore and remove them from the lobby?
There is no way to know what happened to the client. Typically you’d use a timeout to drop them when you don’t receive a heartbeat for N seconds.
Ok thanks! Since NGO and relay have their own timeout implemented, I was wondering if something similar exist for lobby, but I guess not !
Lobby does have a timeout functionality. You just have to lower the time in your dashboard. I believe the minimum is 10 seconds.
By default I believe it’s quite long.
Indeed I found out after posting my initial message, unfortunately, even when putting 10sec, if I alt-F4 the client, the lobby player count stays at 2. I must be missing something quite important haha
You'll need to use lobby events to see when that player times out. Its fairly long by default to allow the player to reconnect.
@dry maple Save statements for a blog, please.
Hello Fogsight, I thought what I said was fine 😄 It's important to show the weakness of certain popular solutions since released games (such as Havoc which released very recently) prove them to be problematic and potentially project-ruining for some types of games like that.
If you want to make comparative review statements, make them somewhere where they can be debated by all parties.
Sorry, not sure what you mean. I just made a reply to someone, it's not intended to be a review.
But if such discussion is not allowed, it's fine. Though I'd like to know which rule/guideline prohibits it so I don't repeat it?
If you are unable to judge when you are dispensing a subjective opinion I suggest you won't post it then. Next time will result in a moderation action.
Could you answer my question: But if such discussion is not allowed, it's fine. Though I'd like to know which rule/guideline prohibits it so I don't repeat it?
I has been made clear to you previously that no comparison based discussions are welcome here. Yet you continue with it.
Sorry I don't recall that. But if that's what you want, it's fine, I will not compare.
So, I am using PhotonTransformView to sync the positions of all the Coins on my Carrom Board between both the players. So, when the turn switches and the ownership of the coins' PhotonView gets transferred to the player whose turn it is, there is a slight glitchy effect where the coins randomly move a bit then get back to the right place as if it's synchronizing between the scenes. How can I fix this?
You can look at 1:20 and 2:40 to see what I mean
I tried adding Interpolation but doesn't chnge anything.
Can you not just make the coins owned by the server?
How do I do that, i wanted to do that but was unsure on how to do it
I don’t use Photon, so I’m not sure how to specifically.
But I’d say that’s definitely what you’d want to do. Then you just have each client send their input for the server to shoot their coin and all the transforms in their physics can be done by the server for consistency.
Yeahh, I also wanted to do that but I was unable to figure it out
I dont use Photon either, but you would use RPCs to send the vector 3 of the client input to the server
I have an issue with clients connecting at I'm not sure how it happened, it used to work fine, but now the host works fine, then if a client connects then the host freezes but is still being updated on the clients screen
and the client is fine
Is there any other way to run code on the server beside rpcs ?
What solution are you using? And why do you need an alternative to RPCs?
RPCs are like functions that are called right? The movement should be live as their positions change every frame. Basically like in the video I sent and there is also physics. So, RPCs will help me regarding this?
I have a development on this, that jittering only happens in the previous PhotonView's owner's side. So, if Player 1 is the owner and player 2 requests the ownership, the jittering happens to play 1 when the ownership is transferred. Jittering as in, the objects go back to their initial position then come back to the correct position.
Edit: I removed Photon Transform View and added a script to handle the synchronization but it still happens 😔
Yall should check out PlayFab for online gameplay and management. Its quite awesome.
Im using it to implement a TCG I designed and its really been great.
Hey guys, I have an issue:
...
else
{
Debug.Log("Sending Move to Server");
SendMoveToServerRpc(new int[] { _currentMove.MoveCoords[0], _currentMove.MoveCoords[1], coords.x, coords.y });
}
[ServerRpc(RequireOwnership = false)]
private void SendMoveToServerRpc(int[] move)
{
Debug.Log($"Inside SendMoveToServerRpc, turn manager: {ServerTurnManager.Instance != null}");
ServerTurnManager.Instance.ValidateMove(move, NetworkManager.Singleton.LocalClientId);
}
This was previously working as intended, my changes were that NetworkManager, ServerTurnManager and SessionManager are now being spawned in another scene and added to DontDestroyOnLoad. But now, I don't get to the Debug inside the RPC, only the previous one, and in the console I get:
"KeyNotFoundException: The given key 'ThisClassName' was not present in the dictionary."
Anyone got any ideas of what the issue might be?
The problem might be putting those in Don'tDestroyOnLoad
Might've been, ended up using NGO's scene manager rather than the "normal" one and it worked
when ever i click the button leave room i get the responce "Operation leave room not allowed on current server(Master server) can someone please help. i also get the warning "Photonnetwork.currentroom is null and that you dont have to call leaveroom() when your not in one . i know that i am in a room tho.
What is networking?
I replied in the unofficial Unity discord.
I am pretty new to NGO and I am trying to make an object that acts sort of like a game manager class over the network. I need a way to access it through a singleton sort of how NetworkManager can be accessed so I am currently using this logic to get it, however I feel like the way I am doing it is probably wrong.
In my NetworkController class I have:
public static readonly NetworkVariable<ulong> singletonID = new();
And then to retrieve it:
public static NetworkController Singleton()
{
return NetworkManager.Singleton.SpawnManager.SpawnedObjects[singletonID.Value].GetComponent<NetworkController>();
}
And then in an OnNetworkSpawn method in a NetworkBehaviour attatched to my player I have:
if (IsHost || IsServer)
{
Debug.Log("Spawning Network Controller");
var prefab = Instantiate(networkController);
prefab.Spawn(true);
NetworkController.singletonID.Value = prefab.NetworkObjectId;
}
I try to avoid singletons in general, but you can just make it a normal Singleton as an in scene network object. There is no need for a network variables.
Hey all. In NGO, Is there a way to send packets between client without a NetworkObject or a NetworkBehaviour? My project is mostly not dependant on GameObjects (Data and GameObject visuals are very decoupled), but from what i see, RPC would need to be under a NetworkObject and Custom Messaging requires a NetworkBehaviour.
I can also hack it by having a surrogate game object for each client, but i'd rather not go that route if possible
Custom messages don't need a network behavior or network objects at all. The samples here in the docs only use them for the OnNetworkSpawn convenience
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.
I see it now, just need to use CustomMessagingManager
thanks for the pointer!
My code for turns:
public struct Turn : INetworkSerializable {
public bool hasMoved;
public bool hasAttacked;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref hasMoved);
serializer.SerializeValue(ref hasAttacked);
}
}
public class TurnManager : NetworkBehaviour
{
public NetworkVariable<Turn> turn;
...
What I'm trying to do:
turnManager.turn.Value.hasMoved = true
How can I set hasMoved to true in my server RPC for moving a unit? Do I have to basically reinstantiate the turn object each time I want to change a single variable like turn = new Turn(...)? I've tried looking at the docs but I don't really understand
is it a custom NetworkVariable I need?
Yes. the way you currently have it, you need to make a new Turn object. You could also just have 2 NetworkVariable<bool> on you player object
alright ill make a new turn object 🙂 I'm planning on adding more bools to turn so ill keep it in the turn object. Thanks a ton for the help again
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Unity.Netcode;
public class NetworkUI : MonoBehaviour
{
[SerializeField] private Button hostBtn;
[SerializeField] private Button clientBtn;
[SerializeField] private Button serverBtn;
[SerializeField] private InputField nickFld;
private static HashSet<string> usedNicknames = new HashSet<string>();
private void Awake()
{
hostBtn.onClick.AddListener(() => {
if (IsNicknameValid(nickFld.text))
{
usedNicknames.Add(nickFld.text);
NetworkManager.Singleton.StartHost();
}
});
clientBtn.onClick.AddListener(() => {
if (IsNicknameValid(nickFld.text))
{
usedNicknames.Add(nickFld.text);
NetworkManager.Singleton.StartClient();
}
});
serverBtn.onClick.AddListener(() => {
NetworkManager.Singleton.StartServer();
});
nickFld.onValueChanged.AddListener(delegate { ValidateInput(); });
}
private void ValidateInput()
{
if (nickFld.text.Length > 12)
{
nickFld.text = nickFld.text.Substring(0, 12);
}
}
private bool IsNicknameValid(string nickname)
{
return !string.IsNullOrEmpty(nickname) && nickname.Length <= 12 && !usedNicknames.Contains(nickname);
}
}
Why can't I drop my InputField into inspector?
could be that you are using TextMeshPro's input field, in which case, you should be using TMP_InputField instead of InputField
forgot to reply^
I am a bit confused with reading this documentation
https://docs-multiplayer.unity3d.com/netcode/1.10.0/advanced-topics/fastbufferwriter-fastbufferreader/
Does this mean that FastBufferWriter does not dynamically resize, and we have to manually resize them ourselves?
Does anyone have an example of a dynamically growing buffer?
The serialization and deserialization is done via FastBufferWriter and FastBufferReader. These have methods for serializing individual types and methods for serializing packed numbers, but in particular provide a high-performance method called WriteValue()/ReadValue() (for Writers and Readers, respectively) that can extremely quickly write an en...
thanks, ima try it
worked, thanks!
Hi! I might need a bit of help because I am going crazy: I am using the classic combination of NGO/Lobby/Relay/Auth, and I am able to connect player together and play in the same session perfectly. HOWEVER if the Lobby host crashes, the clients never receive the Player Left lobby event, and the lobby itself is also never updated with the player leaving. Anyone managed to handle a host crashing with this combo of packages ?
LobbyDeleted doesn't get fired when a host crashes?
No because the lobby isn't deleted, what is supposed to happen is the host is automatically transfered to another user, but it is not happening since the lobby does not register the host has left
Right. Forgot about automatic host migration in Lobby
Hi! Question.. In Distributed Authority mode, is it possible to restrict the spawning of certain NetworkObjects to be allowed by the session owner only?
I've yet to find a situation where an application quitting/closing/crashing doesn't eventually remove the player from the lobby (although I primarily have used Lobby on mobile)
how are you "crashing" your application?
Its on Meta Quest, but I am quitting it through the OS, similar to Task Manager kill is I think
Doesn't NGO have some kind of timeout? Regardless i usually just make my own pinging implementation so i can detect disconnection at my own pace (eg: have a more relaxed ping interval in lobby vs in-game)
There is not. Each client is their own authority so they can always spawn their own objects. You can have them call RPCs which can check for session owner to run.
quick question is there a way to get the server's client id from the Network Manager?
or is it only for the UnityTransport? (if so, how would it work on other transport?)
Thanks for your tip! How will using an RPC help?
Because if they can spawn their own objects then its possible for a cheater to inject code that would spawn them right?
It's NetworkManager.LocalClientId I think
that would be the current client's id no?
I have another client that needs their connected server's client id
Right, if they hack the client then nothing you can do in that case
The server id is always 0
If the Host isn't timing out, a pinging or heartbeat system won't solve his problem. The host crashed and can't disconnect themselves and no other client can force the host to disconnect.
ah good to know, thanks
Wait, so when the host crashes NGO doesn't auto disconnect and the server is still responsive?
He's talking about Lobby specifically I think, not NGO
The host is not timing out, leaving the rest of the clients in an unresponsive lobby with no new host being selected
The lobby host will eventually time out.
[Netcode] [Invalid Destroy][RTS Networking(Clone)][NetworkObjectId:2] Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.
i am spawning an object with a network object, and then loading a new scene (with networking ofc), but then this happens and the object is only destroyed on the client not the server
Make sure that only the server is calling Spawn() and NetworkManager.SceneManager.LoadScene()
quick question
In my project, when you enter by default it does StartHost()
And then when you want to connect to another host, it does Shutdown(), waits for OnServerStopped, and then does StartClient()
Is this correct? or am i supposed to use a whole new NetworkManager?
That should work fine
For some reason when i do this, OnClientConnected i print the networkManager.LocalClientId and both client and server is saying 0 (despite being on different clients/editor)
is it even possible to start a client and then having its id 0?
wait... is the client id only unique for its own client? not that it is unique for the whole connection? Did i miss something in the documentation?
The server/host client id will always be 0. If a client disconnects and reconnects then the client it will always increase by 1. Those ids do not get reused.
so technically the ids should be unique across connections, right?
In my screenshot though, Right is a host that has id 0 and Left is a client that connected to RIght (and i've confirmed that they do connect to each other) but the client's LocalId is 0, it's really weird and i'm not sure what causes this.
I guess i'll try experimenting on a separate blank project
Yea, every client that connects gets their own client id. The Onclientconnected callback should be giving you the proper client id.
Hello, I have faced an issue that when joining as next client, host's camera is stuck on it's player camera which is the right thing, and there is new player spawned when client joins, but client only sees that their game is frozen while in reality the host now controls new player even tho I check if (!IsOwner) return;
why does this happen?
Here are scripts
(sending files cuz characters for each are too long)
bruh discord doesn't allow me to send any file for some reason
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Use one of the links
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Movement.cs
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
NetworkUI.cs
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
PlayerNickname.cs
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
SerializableString.cs
to not cause confuse I am replying to help message
help will be appreciated
@restive plinth how are your players being spawned?
network player prefab
player has Movement, camera, and PlayerNicknames.cs
Hello, I have faced an issue that when
playerID in body must match authenticated player```
After creating a lobby, when I exit play mode, start the game again and try to create a lobby, I get this error.
Here is my code https://pastebin.com/LbwDqQzs
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.
Has anyone messed with Matchmaker and Relay instead of MultiPlay? Documentation seems to be lacking around Relay use with Matchmaker.
well yeah, the network object spawns on both just fine, but only when i load the scene i get the error and it gets destroyed (the scene is loading fine too except, yk, this error)
In case any1 is struggling here the same way that i did;
OnClientStarted is the wrong context to be checking if your client can already send messages, because at that point your LocalClientId is still 0
sounds obvious but did catch me offguard xP
can someone help me out beacuse i am working on this game and when i tried to test the multiplayer it is not showing me any rooms for me to join even though on the game i have created an room. and when trying to join from the room ist i cant find it there
Haven't done a local server build for a while, but when I do a local dedicated server build on my windows machine targeting window platform with il2cpp backend chosen it builds, but when i run it i get "failed to load il2cpp" error and the process ends.
closest thing i could find on google was this https://discussions.unity.com/t/dedicated-server-build-for-linux-from-silicon-mac-unity-editor-fails-to-run/868567 but it mentions the issue about building from a mac or linux machine.
Any ideas?
uSing netcode for entities 1.2.3
@pearl girder Don't cross-post. Remove the post when moving.
i need help with photon
Then !ask an actual question what you need help with.
!ask
⛔ Before Posting
🔍Search the internet for your question! 🔍
⠀+ Use the API Scripting Reference and User Manual.
⠀+ This troubleshooting site for commonly posted issues.
- Please attempt to debug your issue.
- Find a channel by reading the name and description.
- Take a look at #🔎┃find-a-channel
- Read the pinned messages 📌
-# For more posting guidelines, go to #854851968446365696
if it's anything like what you talked about in #💻┃unity-talk, you do not need help with photon, but ask away I guess
playerID in body must match authenticated player```
After creating a lobby, when I exit play mode, start the game again and try to create a lobby, I get this error.
Here is my code https://pastebin.com/LbwDqQzs
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.
I cant find anything about this error on the net
Did you match the request’s player ID with the authenticated player’s
Yeah
Do you have proof?
new Dictionary<string, PlayerDataObject> { { "Name", playerDataObjectName }, { "Character", playerDataCharacter } });```
that doesn’t prove that the player ID is actually the authenticated one, or that any ID is authenticated at the moment.
You may have to re-auth that ID
What do you mean by Player ID? If you are talking about the ID of the creator of the lobby or a player in the lobby, yes they match.
private Player playerData;
...
CreateLobbyOptions options = new CreateLobbyOptions();
options.IsPrivate = false;
options.Player = playerData;
public async void CreateLobby()
{
Debug.Log(playerData.Id);
Debug.Log(AuthenticationService.Instance.PlayerId);
Logs show they match @austere yacht
Im Talking about what the error message says
If I knew what the playerID in the error message was it would solve the problem
Hello guys, I'm having a synchronization problem, I'm using unity netcode and the Client Network Transform on the Player, Network Transform on the platform.
What is happening:
-
I have a player that is synchronized between host and client, using the Client Network Transform
-
I have a movable platform that uses NetworkTransform
-
When the player stands on the platform he follows the movement of the platform and can move freely on top of it, this works on the host and the client
THE PROBLEM: -
on the client screen, both the host and the client are synchronized on the platform, without sliding or getting in the middle of the platform
-
on the host screen, the client slides and enters the middle of the platform when it moves on the Y axis
I will attach the codes and a video that shows this happening.
In the video, the left side (unity editor) is the client, and the right side (native application) is the host.
Player script: https://hatebin.com/emfgmdtqtm
Moving Platform: https://hatebin.com/wutluodqls
video: https://drive.google.com/file/d/1WdQs_H9rGNTFq_vEiSana5AXm7iWI8lG/view?usp=sharing
moving platforms are hard. The best solution might be to reparent the player to the platform. But that has its own issues
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
should be the one you get from IAuthenticationService.GetPlayerInfoAsync().ID AFTER you have signed in.
it is likely that this ID is cached and persists accross sessions, but the signed-in state doesn't.
The API's signed in user could very well be undefined for your API/user token and to not leak secrets the API just pretends the name was wrong
hey all, not sure if this is the right channel for this, point me elsewhere if so.
I'm working on a multiplayer project using mirror, but my main conern is that I want to be building my project with the idea of a headless dedicated host server in mind.
What design patterns/considerations should I have when designing my scenes/netcode for a dedicated headless server?
another thing I read was that it is possible to build a server backend as just a C# appliaction, or even C++, to communicate with unity over the network. has anyone here attempted anything like this?
if you're 100% on a dedicated server you can skip handling the "Host+Client" case (which makes stuff complicated). Also don't rely on anything graphical or GPU related on the server. I'd also aim to get that server running on an actual cloud server right away, it'll save you a bunch of woes if you need to retrofit your UX to the specific hosts flow/features.
Its not mirror but check out the docs here. there are some good tips here regardless of framework
https://docs-multiplayer.unity3d.com/tools/current/porting-to-dgs/
This is part one of the Porting from client-hosted to dedicated server-hosted series.
I am, my usecase 100% require authoratative server
I will read this, thank you for sharing
also if you do require authority, you likely want to compile any server code out of your client builds, so for that wrap all your server code in #if SERVER pragmas
this is much easier if you have partial classes with .server, .shared and .client parts
or just server/shared/client component NetworkBehaviours on the same game object
in general my workflow should look like this:
- player issues commands to units, these commands are batched and RPC to server every 1 second
- server takes commands and updates values on units, then updateds postions for moves/targets for damage
- only need to update units on local grid so interest management based on parent game objects
if this is turn based you should just send the player inputs to the server
well, if you can get away with some lag, just send the inputs to the server and have it do everything
that is certainly the simplest approach
but not always the nicest for the player
idk how to model inputs to ther server, I'm not doing like wasdd movement, I'm clicking on a unit and right clicking on a grid to assing a destinaion positon
sry my typing is terrible today for some reason
you can represent all that with integers
each unit has an ID, each kind of input action has an ID
you dont need to send raw inputs, but if you worry about cheating, you should, and validate those agains what is actually possible for the player in its current state
see I was working with photon right and I wanted to push this over input
namespace SpaceGame.DTO.Commands
{
public struct MoveCommandDTO
{
public int UnitId;
public int LocalGridID;
public Vector3 Position;
}
}
they told me 'my use case didnt fit with fusion'
so I thought this wasnt possible
I figured I could represent this as ints but i figured I would jsut batch these commands and RPC them to the server as an array
why would you manually batch them?
from what I was reading frequent RPC are bad and should be limited in send rate. was going to batch to stop them from choking my server
then you may have misunderstood something
Try to avoid premature optimization
mirror does automatic batching, you just should not do more RPCs than you have actual messages
also don't send data in the RPC args that you don't need
haha I'm very comforable with the vector math and game logic but still learning netcode
all your messages (RPCs) are aggregated into a tick and sent more or less together
i see, so then I can jsut reduce the tick rate to achieve the same effect
yes
well that much simpler haha
but only if you don't do it because its turn based
or you actually want to control that delay
its a very low-level thing, not something you would expose to your game design
okay so if I want to send a move command over the network like the struct I pasted before, I just need to convert the vector3 into ints?
no, you can send the vector3
you just should not use reference types or strings
all your entities need/have an integer ID you can use to send references
yeah I have everything working by ID already in my management calsses
thats the important bit
that goes a long way
yeah syncing ints cheap, I know that
not just that, it makes everything much simpler
I have been gathering info for about 2-3 days, you have been very helpful
I think I am prepared to start my net implementation
What’s good networking package that have updates don’t break your game?
None of them should have updates that break the game. At least any breaking changes would be clearly labeled
I'd reccomend Photon Fusion
Unity ngo v1.10 have some new methods but after updating it still don't have that methods. Those are OnNetworkPreSpawn, etc
How are you trying to access them?
Like we do for OnNetworkSpawn, Despawn
thank
I have no issues using them.
You probably just have to restart the editor
It still doesn't work after restarting
You sure you have 1.10.0 installed correctly?
if its still not working, then delete the Library folder and restart
It still does not work
Can you show how you’re trying to define the functions and any errors you’re getting?
If there are any console errors, that can stop it from fully compiling
There are no errors. It's just like it never updated. It just not showing new methods
There are no errors, the project is perfect and payable
the only other thing it can be is Assembly Defines somewhere
Not showing as in not showing in IntelliSense autocomplete?
The intelliSense works fine. The new updates in scripts also not showing in IntelliSense
I'll see what's wrong. Thanks for your time evilotaku and Dylan
The new methods don't show up in IntelliSense either for me, doesn't stop me from using them
That's why I'm curious as to how you're trying to define them
Ohhh, I didn't tried to complete it since it was not showing on IntelliSense. I thought it doesn't exists
Just try typing in the override definition, and if it doesn't error that means it's a valid override
Ah, I wasn't on system any more so I was just writing here
Yeah I will do this
protected virtual void OnNetworkPreSpawn() { }
public override void OnNetworkSpawn() { }
protected override void OnNetworkPostSpawn() { }
These were all valid for me
Yeah, OnNetworkSpawn and Despawn works for me in intelliSense too just the new methods doesn't show
Thanks for your time Dylan
the new ones have to be protected not private or public
Ohh that's the issue!
I was just keep trying to get it on IntelliSense using public
best free networkign solution that doesn't require port forwarding?
thanks
all can be doable without port forwarding, by using relay sdk such as: Steamworks, EOS, and unity relay. OR client-app relay such as: ngrok, hamachi
but fusion is built-in
Hey guys, I haven't done multiplayer before, I am making a fps shooter I know very original, and I want to implement multiplayer early on, so i dont face many issues
I have the controller built guns are not implemented yet, but I want a system that is scalable but not limited to an eco system like photon, etc. I want to implement dedicated servers like minecraft and cod4, where players can download server files and host the server themselves as well as official servers using quickplay which I will host myself.
What should I do and can you link any good resources to learn multiplayer?
noob question, I'm trying to figure out how I can get two separate players detected in the same lobby (this is in the VR Multiplayer template) using parallel sync. I get this after I already have first player joined
Unity anonymous Auth grants unique ID's by editor/build and machine
Their sample shows how to get around this issue.
Thanks, do you think 'multiplayer mode' in Unity 6 is a better approach?
I will test it out
If you're referring to this:
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual
I would say yes. I haven't used it, but I've only heard good things about it so far. AFAIK, it is being designed to make simple Lobby/NGO/Relay implementations as easy as possible and is very much in active development to make it even better.
Yes, it looks interesting, this is the other link I found on it: https://docs-multiplayer.unity3d.com/mppm/current/about/
Overview of Multiplayer Play Mode
Oh, that's something different. But also useful.
It's ParrelSync built in to the editor, but faster, easier to use and more efficient
I like the sound of that
You can us MPPM but you will still have to switch Authentication Profiles when connecting from the same PC
I haven't been able to get this working with Relay and WebSockets yet. When configuring to use WebSockets for the Transport, Relay doesn't get setup to use websockets, so you just get an error. Since you don't have any control over the relay allocation, it's seemingly a big gap. That said, it's super easy to implement and will remove some of the confusion new developers may have when trying to setup multiplayer in their game.
Yeah, 100%. It's lacking customization in several areas. Why I made sure to say it's good for simple implementations.
So far, websockets is the only area that I think it's lacking. Everything else works great 🙂
Be sure to ask about this in the Dev Blitz next week. Seems like it should be a fairly easy add
I'll put it on my calendar, thanks for the reminder 👍
Hello 👋 Here's something that got me stuck for a bit now, maybe someone has an idea!
I'm using Unity NGO 1.9.1 on Unity 2021.3.37f1. I first start a host using NetworkManager.Singleton.StartHost() then I'm loading a scene using NetworkManager.Singleton.SceneManager.LoadScene(sceneName, LoadSceneMode.Additive); and everything works great until I call NetworkManager.Singleton.Shutdown() upon exiting my first game session and attempting to load another. From that point on, after starting the host again, attempts to load the same scene again leads to the returned status of the loading method to be SceneEventProgressStatus: SceneEventInProgress.
What am I doing wrong?
For context, everything works fine without the Shutdown call, but from then on my NetworkManager IsHost is true, which messes up with a lot of the logic I have, as I ultimately would like players to be able to initialize a Host session or join another game without closing the game.
also the LoadScene() method crashes (after Shutdown and StartHost anew) with this Exception: Failed to find any loaded scene named PlayScene! in Unity.Netcode.NetworkSceneManager.GetAndAddNewlyLoadedSceneByName (System.String sceneName) (at Library/PackageCache/com.unity.netcode.gameobjects@1.9.1/Runtime/SceneManagement/NetworkSceneManager.cs:909)
Make sure that you are waiting the 10 seconds needed for Shutdown to fully complete before trying to StartHost() again
the game goes through the menu and I start the new game via the interface. It's not 10s .. but several at least. Is there a way to check the state? I'm already awaiting await UniTask.WaitWhile(() => NetworkManager.Singleton.ShutdownInProgress); which only lasts one frame
This may be exiting early? Not sure when ShutdownInProgress gets set after calling Shutdown()
May have to check that it's true before waiting for it to not be true
Because it should definitely be true for longer than a single frame
maybe I can investigate that, but I just tried waiting for a full minute now, and I just got the same issue
NetworkManager also get put into DontDestroyOnLoad, you might end up with duplicate network managers
afaik there's only one, it's initially in my loading scene and gets put into DontDestroyOnLoad. I'm only additively loading the scene containing the level
I also stumbled upong NetworkManager.Singleton.SceneManager.Dispose() and I'm not even sure what it does ^^ I don't know why I would have a SceneEventInProgress on the second load attempt. I'm tracking every SceneEvent in the game and the last one I receive is always UnloadEventCompleted for unloading the previous instance of the Scene
thanks, I think I either need to modify one of the scripts shown in screenshot, or just create a script to switch authentication profiles and attach it to the XRI Network Game Manager object. Am I close?
What I do is right before SignInAnonymouslyAsync() I'll call AuthenticationService.Instance.SwitchProfile(CurrentPlayer.ReadOnlyTags()[0]);
just make sure the tags are unique to each clone
thank you, I somehow got it all to work lol. Multiplayer play mode is looking nice
So I had a thought, my game is already a online game. It downloads some definitions for costs and stuff, but could I also define and download icons this way? Then save and load them to display on an Image component
Yeah. I usually keep a lot if images/icons in an Amazon S3 Bucket and download them at runtime.
how do you handle the texture / sprite problem, right now most of my icons are loaded in as sprites but now I am working with Texture2D, should I just make a Sprite from each texture or change all Image to Raw Image?
You pretty much want to use Raw Image whenever possible.
so it would be better to go through and replace all the Image components with Raw ones
at least for the dynamically loaded icons
Yeah. Otherwise you’re creating sprites at runtime which takes longer and uses more memory.
I am working with Mirror and I don't know how to setup drop and pickup correctly. I have those two methods set up already and NetworkIdentity and NetworkTransform on item. Where can I find examples of this being done, or tutorials, because there is little to none on Youtube.
Read through it already and it wasn't really helpful.
What are you trying to accomplish?
Just a simple pickup and drop.
And Interaction
Now when I pick it up it disapears.
The guide link I sent covers that. If there are specific things you don't get, you can ask about it here.
Hello I'm trying to make a game with my own websocket multiplayer, and I show a bit of my code, and everyone seemed appalled that I worked with string, So I made some research and I wanted to know if instead of sending the data as string like that
ws.Send("GID"+GameID+positionString+"!"+rotationString+"IsAiming"+fpsController.IsAiming()+"IsWalking"+fpsController.IsWalking()+"IsRunning"+fpsController.IsRunning()+"IsHigh"+fpsController.IsHigh()+"IsReloading"+fpsController.IsReloading()+"$");
will it be better if I send the data like that ?
public void SendPlayerData(Vector3 position, float rotationY, bool isAiming, bool isWalking)
{
using (var memoryStream = new MemoryStream())
{
using (var writer = new BinaryWriter(memoryStream))
{
writer.Write(position.x);
writer.Write(position.y);
writer.Write(position.z);
writer.Write(rotationY);
writer.Write(isAiming);
writer.Write(isWalking);
ws.Send(memoryStream.ToArray());
}
}
}
Hello,
I am making a board game with a turn based multiplayer, how do i go about it for changing the turn from one player to another like if there are 4 to 6 players
it depend, what are you using to make your multiplayer ?
Hey, im making a multiplayer shooter where the bullets are very slow and i wanted to add server rewind or "lag compenstation". I have not found a single tutorial on this and have no idea how to make it, does anyone know?
There's a good explanation of it here:
https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking#Lag_compensation
Using NGO, a very simple starting point would probably mainly involve storing a list of colliders that represent players previous positions and making use of NetworkTime
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networktime-ticks/
LocalTime and ServerTime
Yeah, but how does the server know how many ms it has to compensate?
That's a bit backwards. The server should not be compensating. Clients can forward predict where objects should be by the time any input packets reach the server. The clients are the ones who should be rolling back if mispredictions happen.
That’s correct for client-side prediction and reconciliation.
I believe he’s wanting server-side lag compensation for his projectiles though which is something different.
anyone have any advice for making lobbies in unity service?
Use Lobby Events lots!
wdym?
does it work with relay?
Yep! It's designed to.
This also wraps NGO, Relay and Lobby all in to one easy to use package if you're interested in that
thanks! ill check this out!
I was talking about bullet hit detection
send the tick
and how do i get the tick number?
only photon?
Fusion and Netick is the only lagCompensation raycast I've tried
When I reload the domain, this id starts from 1 and continues to increase one by one every time I stop and restart the game. I need to find a way to reset this before the game stops working.
LocalTime and ServerTime
also, what about interpolation? how does the server calculate that?
is it local time or server time?
idk in NGO
NetworkManager will track both local time and server time. There is also a new partial tick if you're feeling fancy
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/api/Unity.Netcode.NetworkTime.html#Unity_Netcode_NetworkTime_TickWithPartial
partial is like the alpha?
between ticks?
thanks for sharing the information @sharp axle
If you need the accuracy, it will give you the exact time between ticks when you call this
Hello,
I am making a board game with a turn based multiplayer, how do i go about it for changing the turn from one player to another like if there are 4 to 6 players
You probably use a network variable for the turn number and then have the server increment it after the player ends turn
turn number can be list of player so index 0, 1, 2, etc
how do I use lobby quickjoin
public async void QuickJoin()
{
try
{
LobbyJoined = await LobbyService.Instance.QuickJoinLobbyAsync();
}
catch
{
}
}
this is what I have so far, I want to start a client in the lobby now
idk if this is even right, my brain hurts\
If you're using Relay, usually you put the join code in the Lobby's data so that clients can read it from the Lobby data and use it to join the Relay
You need to make Quick Join Lobby Options
https://docs.unity.com/ugs/en-us/manual/lobby/manual/quick-join
Hello, not sure if I should be asking this here or in the Mobile section, but I'm trying to handle disconnect responses and right now players are sent back to the main menu whenever anyone disconnects. This is working on PC fine, if either the client or the host close the game unexpectedly the other is sent back to the main menu and the session terminated. This logic is hooked to OnClientDisconnectCallback if server and to the OnDestroy on the client side (since this object is owned by the server/host).
On mobile however, when I minimize the game and then clear it from the "opened apps tray", it seems like the player isn't actually disconnecting or even running the Destroy/OnApplicationQuit methods, or even disconnecting from the network session. Do I need a different approach to application quitting on mobile?
you should never really count on OnApplicationQuit or scene destroy methods being called except when the player closes the window on a desktop app, most platforms don't have much way for applications to do anything special on quit, they just quit
Hm, but even the NetworkManager isn't detecting a disconnection... I kinda need to be able to know when this happens so the other player isn't just held hostage
is your example when the host quits and it doesn't lcean up properly on the client? there might just be a different event you need to listen to
usually if the other end disconnecting doesn't immediately remove the client, there should be some kind of timeout depending on the transport you're using
I'm using relay, and I hadle both client disconnection and host disconnection. If host disconnects -> NetworkObject is destroyed -> Clients React. If Client disconnects -> Host recieves event -> Disconnects other cliesnts (not relevant cause there's only 2 but wtv) -> Handles self disconnection
The issue is that closing the game on the phone, as either entity, does not result in a disconnect
Yhea, so I just tested, if I leave it there it disconnects after a while
I assume there's something somewhere that pings everyone occasionally and that ping fails
but still, it's a significant (tens of seconds) delay
Hm, it's the "disconnect timeout" property in the transport... But still would be nice to be able to know if someone closed the game xD
I've had a similar issue as I wanted to know if a player is 'asleep' before reaching the disconnect timeout. On the Host I listen to unityTransport.OnTransportEvent and I update a table of activity per client. One issue is that transport uses ulong transportClientId and not clientId , and the mapping is not exposed. It's in the NetworkConnectionManager : "TransportIdToClientIdMap". I had to get it using Reflection, which is a bit of a pain. but it works fine Android.
how do i work around this?
it weird that clientconnectioncallback doesnt provide a way to get the connected client id
do that via subscription
NetworkManager.Singleton.OnClientConnectedCallback += CreateRandomGenerator;
you can either put the IsServer check before the event subscription itself or inside the Method it calls
i got error Cannot assign to 'OnClientConnectedCallback' because it is a 'method group'
can you show?
hm, thats because now you have an object as parameter and the event passes a ulong
if you need it to be an object instead of a ulong then do
NetworkManager.Singleton.OnClientConnectedCallback += (x)=> Try(x);
that's strange
either way I see you have 3 refs to where you are subscribing, events should only be subscribed once and then unsubscribed once
probably need to check that
wait
that seems to want to call a method inside the NetworkManager
not the event
stupid question but, is that the NetcodeGO NetworkManager.Singleton?
because this should be what it reads when you place your cursor on top of OnClientConnectedCallback, an event Action
yes
nvm worked
okay there you go xD
recompiling issue?
or did you have another class called NetworkManager with a singleton?
nah i may accidentally create an empty method via the action tab
to the network manager
that funny because if you ran the game it would've probably worked, because changes made to the NetworkManager script are lost
so it might've compiled correctly
yea thank worked
do you have an issue associated with it or you just don't like the warning?
the client doesnt connect
check this thread and see if it helps you
https://discussions.unity.com/t/network-config-mismatch-error-while-config-is-the-same/843536
nvm fixed, it seem that i put a networkobject into a prefab and then place it on scene give the error somehow
remove the prefab to turn it into a normal inscene place object fixed it
Im by no means experienced in NGO, working on my first project with it now, but what I have noticed is that quite often issues arrise with network objects that are fixed by adding and removing the NetworkObject component from the prefabs/scene objects
I don't understand it
I don't like it
but sometimes it's needed and it works
hyah same
so if you want it as a prefab, remove it from the scene
create the prefab with a new NO
and add it to the scene
don't do it in the scene then save the prefab
ahhh okay okay
hello guys !!
I need some help to wait correctly the scene load to complete
NetworkManager.Singleton.SceneManager.OnLoadComplete += SceneManagerOnOnLoadComplete;
NetworkManager.Singleton.SceneManager.LoadScene("Gameplay", LoadSceneMode.Single);
private void SceneManagerOnOnLoadComplete(ulong clientId, string sceneName, LoadSceneMode loadSceneMode)
{
if (sceneName != "Gameplay") return;
InitializeClientOnConnection(clientId);
}
I am working on my game flow (so a lot of scene transition) in my GameManager StateMachine. I have not monobehavior attached.
I know this is a bad way to wait for the scene to be ready.
How are you waiting the scene to be ready ?
how to set inscene placed object to be own by the client instead of server?
There is nothing wrong with using OnLoadComplete
You don't. If it needs to change ownership it should probably be dynamically spawned instead of be in scene
call this in OnNetworkSpawn?
that will change ownership each time a new client connects
That function does serve that purpose but you need to know when you should and how you should do it
is the server the one who knows when X authority should be changed to Y authority?
is the client who is requesting this change from the server?
if you think the right place to do it is OnNetworkSpawn, than you probably should already Spawn it with the correct ownership as evilotaku was suggesting
oohhhh okay
yea thank
hey guys, this is more of a general question than an actual technical issue I'm having, but after following codemonkeys lobby tutorial I noticed that the same function used to leave a lobby "LobbyService.Instance.RemovePlayerAsync(playerID)" may also be called to remove any player from the lobby, in my specific use case for the host to kick a player from the game. My concern is that someone with a hacked client would potentially be able to call this function themselves in order to kick any player from the game. I've had no luck finding an answer online to this question. Is this a potential issue? Or is it only possible for the host client to call this function for other players? Many thanks for anyones time or insight.
Only the lobby host can kick another player. Regular players can only remove themselves
thanks!
can someone help me with multiplayer
so im trying to do like a test of doing multiplayer
and when i join from another laptop nothing updates when i move
also as the host, the camera switches to the client that joins
for example: ill have two pcs number 1 is the host client and pc number 2 is the client that joins
pc 1 starts hosting; pc 2 joins; pc 1 camera switches to pc 2's camera pov; pc 1 moves but nothing of the actions are updated on pc 2 and viece versa;
What is generally the tick rate I should aim for in a 2 player online game?
Genre?
Depends totally on your game. I believe the default is 50 fps
no clue exactly what to call it but it's similar to the "bullet hell" style of games
2d in a limited area though, and a decent bit of precision is needed
This is the tooltip for Mirror's NetworkManager
ah perfect that works for me
The NGO docs recommend that that should be the same Fixed Timestep when using physics
LocalTime and ServerTime
ah perfect, I'm using 50fps for fixedupdate for now but I've been using time.fixeddeltatime so I might change it in the future if it seems necessary
Hey everyone can anyone help me with this error.
[Netcode] Deferred messages were received for a trigger of type OnAddPrefab with key 439981654, but that trigger was not received within within 10 second(s).
UnityEngine.Debug:LogWarning (object)
Unity.Netcode.NetworkLog:LogWarning (string) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.10.0/Runtime/Logging/NetworkLog.cs:28)
Unity.Netcode.DeferredMessageManager:PurgeTrigger (Unity.Netcode.IDeferredNetworkMessageManager/TriggerType,ulong,Unity.Netcode.DeferredMessageManager/TriggerInfo) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.10.0/Runtime/Messaging/DeferredMessageManager.cs:97)
Unity.Netcode.DeferredMessageManager:CleanupStaleTriggers () (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.10.0/Runtime/Messaging/DeferredMessageManager.cs:82)
Unity.Netcode.NetworkManager:NetworkUpdate (Unity.Netcode.NetworkUpdateStage) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.10.0/Runtime/Core/NetworkManager.cs:82)
Unity.Netcode.NetworkUpdateLoop:RunNetworkUpdateStage (Unity.Netcode.NetworkUpdateStage) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.10.0/Runtime/
Okay I figured it out. The prefab which I am spawning is not in network prefab list. I don't know the reason but network prefab list scriptable object is behaving strangely. The prefabs in it are getting removed automatically. I added prefab to it but now when I checked it is not in there. Now i added it again which fixed the above issue.
Thanks
is it possible to give a command in discord and run this command in unity? for example, when i type /jump in discord i want my character to jump
and if its possible what can i use for this
you'd need to look into making a discord bot, once you've got that it could publish the commands on a server somewhere that the unity clients can connect to
does unity already have a system to do this?
no
thanks 🙂
public override void OnJoinedLobby()
{
base.OnJoinedLobby();
Debug.Log("Connected: Room found");
GameObject _player = PhotonNetwork.Instantiate(player.name, spawnPoint.position, Quaternion.identity);
}
Im using Photon to create a multiplayer game. I get Can not Instantiate before the client joined/created a room. State: JoinedLobby error, even though i joined a room?
you should probably instantiate from the server, not sure if that does it but looks like client code (?)
I am not sure how to do that and what is the difference.
@warm bone ah hm.. have you already completed the tutorial? https://doc.photonengine.com/pun/current/demos-and-tutorials/pun-basics-tutorial/intro
from what I know OnJoinedRoom is the proper callback for when the client enters a room, not OnJoinedLobby
Oh ok i see the error now thanks
do the tutorial, it'll save you time in the long run
Can someone help me understand Netcde for gameobject... i have watched so many tutorial but can't really get my head around it : (
Please don't crosspost. If you can't understand it, it's likely out of your current scope and any help anyone can offer would require literally 1:1 mentoring you, which nobody here will do. You need to start smaller and actually build the experience to understand it.
Ik I'm doing same but like there is this "IsServer" var i don't understand, I'm not asking to 1:1 mentor me just I got few quetions...
sorry for misunderstanding : (
Then you can post your questions here and if anyone wants to take the time to answer, they can. A general "help me" isn't enough information.
Ok Ok lemme specify my question in detail 🫡
If i'm calling "IsServer" from a client then it's not going to run on that machine which client is using right ?
private void Update()
{
if(IsServer)
if (networkPosition.Value != Vector3.zero)
updateServer();
}
private void updateServer()
{
transform.position += networkPosition.Value;
}```
In the code above when I press the Arrow keys (which basically changes the networkPosition.Value) the "updaeServer()" will run on the server machine (Host in this case) and will not run on the client machine from my understanding so when it's running in the Host/Server machine I'm modifying the transform.position, which moves the client... How so ? the code runs on the host which says transform.position++ shouldn't the host move ? why client moves
If this object has a network transform then it will sync the position to all clients. Your input should be checking if its the local player
the engine I used to use you could essentially open two instances of the game window in the editor press play and run two seperate instances of the project in the editor. This made it extremely easy to test multiplayer code. It seems like in unity you either keep the server/client in the same project and build a client or server when you want to test, or seperate the client/server into two projects with all shared code going in a dll. Is there a better way i am not aware of?
You should really be using Scripting define symbols to check weather its a server or a client
you can make an editor script to update these values
then your code would look like this
private void Update()
{
#if SERVER
if (networkPosition.Value != Vector3.zero)
updateServer();
#endif
}
#if SERVER
private void updateServer()
{
transform.position += networkPosition.Value;
}
#endif
the code wrapped in #if SERVER will only be included in the project if you define SERVER in the player settings, this prevents the client from ever having the built server code on their machine.
Them being able to decompile your code and find the server code will make it very easy for them to find vulnerabilities in any cheat prevent methods you emplace on the server
ParrelSync, DualPlay, and nowadays Unity is building in a feature called Multiplayer Play Mode for Unity 6
they both take forever to set up a "clone" in large projects with lots of assets. its faster to build if go into the settings and chose the optimize for build time option
Creating the clone for the first time takes a little bit, using it after that is quite quick in my experience
you dont have to recreate it after each change to the original project?
No
Mhm
oh shit mppm + dedicated server build target and multiplayer roles is a huge win for unity
afaik it uses symbolic links, so no actual files are copied. It's far from perfect though, and asset values (like the damn network object list) can often de-sync. Had a few occasions where the clone somehow got pushed into my repo despite being in the parent folder where git didnt reach, and messed things up a bit
safe to say watchout what you push after git add . lol
I'm trying to make my game work for 50hz online connections, but it seems that "OnValueChanged" isn't working very well since I only end up recieving position information every two-ish frames now (though occasionally it'll still recieve info 2 frames in a row)
Is there something besides OnValueChanged I should use to update the position
This is using a Vector2 NetworkVariable btw
50hz meaning updating network loop 20 times a second?
What do you mean?
im asking you to explain what your definition of a 50hz connection is
Doesn't 50hz mean 50 times per second (in this case, once every FixedUpdate frame)?
ok you're right, so why are you only receiving updates every two frames?
is there a place i can ask people to join my server and be a dev
i dont think you need something other than onvaluechanged and probably should debug to find out whats going on. Is the value indeed being sent etc
In #📖┃code-of-conduct they've got a bit of info in the "Collaborating and job posting" section which suggests using the Unity forums
my code essentially boils down to
{
if (IsServer) serverSidePosition.Value = transform.position;
else if (IsClient)
{
transform.position = serverSidePosition.Value;
}
}```
I've also been trying it using the OnValueChanged but neither one seems to work
okay for some reason if I put it in the regular update loop, it updates every 6-7ish frames
which is smoother since the game runs at a very high fps, but my point is that the problem is still around
perhaps there is a threshhold, so that 0.0001 value changes are not evaluated, there is a setting for that in the NetworkTransform component afaik
it has to decide on some value above which to send an update, otherwise traffic would be 90% garbage for bigger scenes where most things are static most of the time
it's there for a reason tho, so you seeing those updates less frequently than literally every update is a good thing
I know you can change some of those thersholds in some of the provided network components, but if you really need it you can look around project settings, or wherever you can (if you can) configure such settings globally
does the problem persist if you build the game?
what did you do?
I'm just using ClientRPCs instead of the NetworkVariable
i mean yeah thats deff an option
but finding out why its happening may be beneficial in the long run
wait
Haven't done much testing though, maybe I'm just going mad
idk tbh
this is why I always roll my own networking library
makes it a lot more apparent when its user error or bug
What do you mean by "roll my own networking library"
i write my own code to handle the networking isntead of using a built in solution
using raw sockets
ah so not using netcode for gameobjects or anything?
does sound pretty nice after hours on end of dealing with unity's stubborness
what kind of game you making?
1v1 pvp "bullet hell" style game
I had it running at 10hz before while first implementing multiplayer which is why I never had this problem
show me where you're setting this hz setting lol
it's not an actual setting
I just had it set up so that the host would send info to the client every 5 frames
meaning that at 50fps (the fps of FixedUpdate), the client would recieve data 10 times per second
Now I have it so that the client is sent data 50 times per second, at once per frame
anyways, using a ClientRpc definitely seems to have been the solution
hello ! I made a websocketsharp server for my fps, and i don't know why but after a while, even if the server keeps receiving messages, the server goes to sleep, nothing is displayed in the console and the server doesn't send any more messages, what's really strange is that the serveur don't shut down because I don't have any error inside unity telling me that "The current state of the connection is not Open." and also the serveur shut down only after I press any key on my keybord:
internal class Program
{
static void Main(string[] args)
{
WebSocketServer wsnds = new WebSocketServer("ws://127.0.0.1:8000");
wsnds.AddWebSocketService<Lobby>("/Lobby");
wsnds.Start();
Console.WriteLine("WS serveur started on ws://127.0.0.1:8000/Lobby");
Console.ReadKey();
wsnds.Stop();
}
}
do you know what's appening and also how can I solve this issue ?
Hey are you aware if I can set different scripting define symbols for different editor instances? I have a build scenario setup where it launches another tab but no matter w hat i do its keeping t he scripting define symbols that were set in playersettings
I know ParrelSync has some way of checking your clone number through script, that's about all I know
im not using parrel sync but i found a way around it!
(I'm assuming that Photon also applies to Networking). I'm a new dev (Meaning I don't know how to code lmao), but I'm following a tutorial on creating Multiplayer using Pun. And anything related to Photon.Pun or PhotonNetwork isn't working. Is Pun not supported anymore? Or is it just a me problem.
Its been deprecated but as far as know it should still work. Photon Fusion 2 is probably what you should be using
Ah alright, thanks!
Hello, I get an error like this when printing netcode variable data in netcode, and it gives the error constantly, not just once. The object is a network object, I spawn it later, the permissions are only open to the server and I change it only on the server. What is the reason?
Thats my variables
Btw thats not giving error
But when i try change it like that it always give error
I guess I can't change the strings a second time, except for this part.
Because it gives an error when setting it, the second time the error applications start.
Gotcha thank you so much 🫡
I dont even know what to share to help people help me with this issue?
Playing the game from the editor as either host or client just doesn't work with built versions? It removes a bunch of objects (all the ones with network objects) and disconnects the client instantly.
Playing the game with two built versions works fine though
I don't even know what I've changed to cause this
Playing the game from the editor as either host or client just doesn't work with built versions
Hi, I am having a very interesting problem while sending ws between two computers in the same network using the input of a pen x,y and pressure the two programs lag a lot (using new InputSystem). But if its with a mouse that doesnt happen. And more over if its in the same computer sending the websockets to the apps it goes ok. Anyone has any idea what can be happening?
what features do you all think the current big networking solutions for unity are lacking?
show your websocket code
Hello guys !
I have worked on a state machine, but it's not a networkbehavior or a monobehavior,
So i wanted to serialize the current state, and handle the transition each time the state change,
But my state type is an inferface, IState, how do i serialize that ?
maybe serialize the name of the state, then in a switch method find the state based on the name
but it's smells right ?
What are my options, convert my state machine to inherit from a network behavior ?
Or change my interface to a abstract class ?
you would make a key/signal based state machine where each state and each signal has a unique integer ID
for example:
// declare the machine
enum State { Foo, Bar }
enum Trigger { Continue }
IState fooStateImpl = new FooState();
IState barStateImpl = new BarState();
FSM.Configure(State.Foo)
.Permit(Trigger.Continue, State.Bar)
.OnEnter(fooStateImpl.OnEnter)
.OnExit(fooStateImpl.OnExit)
;
FSM.Configure(State.Bar)
.Permit(Trigger.Continue, State.Foo)
.OnEnter(barStateImpl.OnEnter)
.OnExit(barStateImpl.OnExit)
;
// to trigger a transition:
FSM.Signal(Tigger.Continue);
Ohh yeah i see ! 😮
Thank you
I need to stop players shooting themselves in a server authoritative game - so the server handles the shooting stuff. Players are able to look downwards and shoot at their own hitboxes
has anyone dealt w this kind of thing before?
You would either use a collision layer mask, or you could do a IsOwner check
i think ive figured it out, im checking for hitboxes (which are network behaviours) and then ignoring any colliders hit with a hitbox owned by the owner of the weapon
ye olde RaycastAll
When I print debug.log(transform.position) from my player object and then put an empty at that position, it does not match the position of the player object. This is only happening to my client player objects. I'm having trouble figuring out why this is... Any ideas?
Hello!
Goal: I'm working on a multiplayer project using Photon Fusion 2 in SHARED mode with Unity 2021.3.34f1. I am trying to spawn 2 players and have each user move their own player. I am currently testing using 2 PC player but eventually want to move to 1 PC and 1 VR player.
Problem: The issue I am having is when I spawn 2 players. Player 2 cannot move the player, however player 1 can move both players.
What I've tried and observed:
-I have a GameController script that spawns the player. I originally did not have the else statement. However, the second player would not spawn so I added the else statement. This allowed the second player to spawn. I feel like this is my first mistake adding that else statement.
-I did notice that Player 2's state authority is still player1. So I'm 99% sure that's the problem but I can't figure out how to get to have state authority be player 2. See Player2prefab.png (this is during player mode)
-I've also tried changing CharacterController component to NetworkCharacterController component but same result (which makes sense, because that has nothing to do with authority). See PlayerPrefabComponents.png
-I have a GameController script in my Game Scene that spawns the players. See GameController.png.
-In my Lobby Scene, I have a FusionLobby script that sets GameMode to Sharedmode. See FusionLobby.png
-The way I move my player is in PlayerMovement script. See PlayerMovement.png
If anyone has any ideas, let me know. Thank you!
i have a maze that gets generated but it wont generate for all players the same
Your randomness needs to be generated by the server. You can sync that random seed to the clients if you need to
okay but i dont know how i can sync it with the server i followed the tutoriel from bananadev using Photon.Pun;
I don't use Photon, but you would use Network Variables or RPCs to sync values to the clients
okay i try it
public void SendMessageWs(TouchData message, string command)
{
string messageJson = JsonUtility.ToJson(message);
JsonMessage jsonMessage = new JsonMessage
{
data = messageJson,
command = command
};
string json = JsonUtility.ToJson(jsonMessage);
if (_ws != null && _ws.IsAlive)
{
_ws.Send(json);
//Debug.Log("Sent message: " + json);
}
}
how to serialize random.state to turn it into a networkvariable?
i guess turning it into json string
You could do that. But its way easier to just sync the seed value
what if the random is desync?>
reset the seed to a new one??
As long as Random is called on all clients it cant desync. But randomness should really only be handled by the server and the results sent to the clients
im using a client-base Randomnumber,
client will retrive random number localy then call server and to let it generate the random number so when the client is call but if the server call package is lost then it will desync
in NGO, RPCs are sent reliably so that won't be dropped.
oooo i ll keep that in mind
Hello, is it default behaviour for my clients to not receive Network Manager Scene Events when the host calls NetworkManager.SceneManager.LoadScene()?
they only receive messages after the host has already loaded into the scene?? (which seems odd considering its meant to be synchronous)
to clarify, they only receive the events after the host has set allowSceneActivation = true (meaning the scene loads)
That should be true by default.
Does anyone have any good resources to help me get the hang of netcode for gameobjects?
I want to use steam for matchmaking and etc but I don't understand how using steam as the transporter actually works... I just end up with a weird situation where I have to handle 2 connections and can't wrap my head around what I'm meant to be using to do what?
EG: I start a steam host. I start a unity host... Then what? I don't understand how I'm meant to manage the connection if you get what I meant?
If you are using Steamworks.net then you can use the transport here
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/Transports/com.community.netcode.transport.steamnetworkingsockets
Thanks, but that's what I am currently using... I'm just really struggling to understand how to use it properly
I've watched a lot of videos on it but they mostly seem incomplete, out of date or just wrong?
As soon as I get my 2nd account to connect, I get these
It confuses me because on both games I can clearly see the 2 players spawned, I connect to them through steam but I am getting that warning that client 0 isn't in a connected state? Which is what.. Me the host?
Oh okay... so when I disable the movement script on !IsOwner instead of destroying the script, it doesn't all break... Why is that?
Destroying the component will mess up everything. RPCs are tied to component index so they have to be identical on all clients
I see, makes sense. Well it seems the networking stuff is actually working after all.
I guess now that I can join lobbies via steam, I just have to do all the networking using the Netcode for gameobjects way
Okay I think I have the hang of it now. Thanks 
It is set to false initially while the other clients load the scene, except obviously the clients never load the scene because they are waiting for it to be set to true…
which makes me think this method simply doesn’t work
Would you know another way of holding back the host from loading into the scene?
Do you mean the player objects loading into the scene? It sounds like you need to listen for Scene Events to wait until all the clients have loaded the scene.
thats the thing: im trying to use scene events on the client but they are not receiving any OnSceneEvent until the scene has already been loaded into by the host
as said here
and by then they are no longer in sync
unless youre referencing other scene events...
I guess it depends on when you are subscribing to it but LoadEventCompleted gets fired when all client have loaded
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
I subscribe to it as soon as the client connects. I'm loading up the project now so I'll be able to provide more detail
I subscribe to the OnClientStarted event, then call NetworkManager.SceneManager.OnSceneEvent += SceneManager_SceneEvent when the client spawns
am i wrong in thinking OnSceneEvent is called for every single event from the network scene manager?
with that i have a debug.log inside of the this
so any event called should show a sign
every scene load and unload should call a scene event
right..
and i use NetworkManager.SceneManager.LoadScene() to load a scene
so is it just a bug the client doesnt recieve it till after
make sure that's only being called on the host. and that ActiveSceneSynchronizationEnabled is true
def only being called by host
is ActiveSceneSynchronizationEnabled = true by default?
cuz i haven't set it to false at any point
but if not, i havent set it true at any point either
Hey, i have a problem, i have a game with 2 players with lobby and relay and it works normally, but when one of the players quits to menu, i disconnect the connection with Network.shutdown(), but when the players connect again and go to the gamescene, i get this error
and the client player doesnt spawn
Does anyone know how to join games via P2P by using a generated code rather than IP address?
You'll need to explain what you mean by generated code and, more importantly, why you think it let's you avoid using an IP address?
I'm assuming you mean something like the Relay Service
If im not wrong im pretty sure the Code that are in games are like a encrypted version of a persons IP, and the game inside contains a key for it to decipher
and it contains the port also
So for my current P2P i have to connect via IP address but for games like among us they connect via a code to join a host lobby so i was wondering if theres a way to "disguise the IP with a generated code"
Ah, so you don't mean "programming code".
You should be clear about that.
Ye
that is not how those work at all. almost no games use direct P2P anymore
Like game code but still sounds progammy so dont know the right term
Oh really?
even like small games
Probably a relay or matchmaking service/server.
This looks like exactly what i need
hey guys, im using unity relay for multiplayer but somthing weird is happening, it used to work perfectly but now the player spawns for the host, but on the clients side nothing happens. im not sure when this error started happening but recently i went from unity version 2022 to 2023 so does that have to do with it ?
and if not do you guys have any solutions ?
You are seeing the player objects for the other clients on the host? You'll need to check for errors on the client side.
yes im seeing the player join on the host mobile, but on the client mobile nothing happens
public async void JoinRelay(string joinCode)
{
try
{
Debug.Log("Joining Relay with " + joinCode);
JoinAllocation joinAllocation = await RelayService.Instance.JoinAllocationAsync(joinCode);
RelayServerData relayServerData = new RelayServerData(joinAllocation, "dtls");
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData);
NetworkManager.Singleton.StartClient();
}
catch (RelayServiceException e)
{
Debug.Log(e);
}
//StartMenu.SetActive(false);
}
this is the code and it doesnt give any errors
it just says Joining Relay with XXXXXX
Any errors would be happening sometime after Start client. If the players are spawning on the host then there is no issue with the connection.
but there are no other errors as well, its just blank
the player spawns at the host
but on the client nothing happens
oh i got this warning now
do you know what it is ?
That's the message telling the client to spawn. If it's delayed too long that warning will happen. It's likely that your scene is taking too long to load
soooo what can i do to fix it
Hey guys, I'm trying to make a 2D multi-player side scroller but I'm having camera issues. I've tried making it into a child of the player but due to the player's rotation flipping when they go left, the camera flips as well. Is there anyway to fix that or another method I could follow?
You could use a script to set the transform position of the camera object to be the same as the player
Make your scene smaller. Make multiple scenes and load them additively. Use coroutines/Tasks so it doesn't freeze the program
Your camera probably shouldn't be part of the player prefab anyways. I would use a follow script or Cinemachine to follow the local player
Hey so ive had this bug for over a month and i cant fix it. I think I had it in the past but I cant remember how I fixed it. So my player uses
-Network Rigidbody
-Client Network Animator (Only thing working properly)
-Network Object
-Client Network Transform
The player is Client authourative and it is completely broken. It stays in the same spot that it spawns in and doesnt fall, which makes me think the Net Rigidbody is broken.
Its rotation and position also updates with huge gaps which makes me think the transform is messed up in some way. The Net Object might also have issues. It was working fine on my old player and all the settings are EXACTLY the same. I completely redid the prefab with a new model and ragdoll and it just doesnt work anymore. I also verified that it isn't just the separated body that isn't catching up but the whole Object itself. Any reason why this might happen??
(For reference I am using NFGO with steamworks)
any guides for connecting to UGS from a Netcode dedicated server?
Figuring out networking is a pain... I'm not sure what is synced and what isn't, so far it seems that practically nothing is synced and I feel I'm definetely going the wrong route to try and sync things...
I was thinking of having a PlayerConnectionHandler which would have this clas
public class Player
{
public string name;
public ulong clientID;
public int playerId;
public ulong steamID;
public GameObject character;
}
```
And then I'd store it in a dictionary
```csharp
public static Dictionary<ulong, Player> players = new();```
Can just use the client ID to get all the players information then but I have no idea how to sync this dictionary
So to populate that I have the event
private void OnClientConnected(ulong clientID)
{
Debug.Log($"Unity: New client connected with ID {clientID}");
if (IsHost)
playerConnections.AddPlayer(clientID);
}```
Which calls this function
```csharp
public void AddPlayer(ulong clientId)
{
Player newPlayer = new Player();
newPlayer.clientID = clientId;
newPlayer.playerId = AssignPlayerNumber(clientId);
GameObject playerInstance = Instantiate(playerPrefab);
playerInstance.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
players.Add(clientId, newPlayer);
}```
And a script on the player
```csharp
public override void OnNetworkSpawn()
{
Debug.Log("On network Spawn", this);
if (!IsOwner) return;
PlayerConnectionHandler.FinalizePlayerSetupServerRpc(NetworkManager.Singleton.LocalClientId, SteamClient.SteamId, SteamClient.Name);
}```
which goes back to my connection handler
```csharp
[Rpc(SendTo.Server)]
public static void FinalizePlayerSetupServerRpc(ulong clientID, ulong SteamID, string name)
{
players[clientID].steamID = SteamID;
}```
And that's where I am at....
This all seems like way too overcomplicated for what I want to do
At this point, none of it is even synced with the players, not even sure how to go about doing that
My new game "Tips: Word Game" is on Google Play Store. If you want to support me, you can download and try it. Waiting your feedbacks, thank you 🙂 https://play.google.com/store/apps/details?id=cam.whitelotus.TipsWordGame
hmm, damn, we've got a hybrid of self hosted and amazon fargate hosted game servers
probably just roll a basic api interface for now and make the rest calls myself
I would save the steam id and player id as Network Variables on the player object. Then you can loop through all the players and add them to the dictionary if you want
Scroll down and there is a sign in with service account that you can use in that case
Right, I think I've definitely gone the long way of doing it.
I'm not sure what I'm meant to be looping though? So I have a script on my players with the network variable for their steam ID and Player ID but I don't understand what you mean about looping through all the players?
Wouldn't I just have it on the "OnNetworkSpawn" to call a server RPC with the details and then the server update the dictionary? But how do I give all the players it? Can I just pass it with [Rpc(SendTo.NotMe)] when it's done?
OnNetworkSpawn is called on all clients so no need for RPCs at all really.
But you get all the player objects by going through NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject;
You can use SendTo.Everyone if you still want to use RPCs
The problem that I've had before is that I went the OnNetworkSpawn route which would then call all clients to update the textMeshPro.text and then when people joined after, they didn't have any of the names of people from before they joined
So I'm worried if I rely on locally updating the dictionary, that people who join late will be missing the players before them? like the text does
Also yeh RPC is called for all clients but only the user who joins has access to SteamClient because it's local
You would send the player id and steam id in the RPC.
And I would have the player loop that Connected clients dictionary to get already connected players and grab their player id and stream id network variables
ConnectedClients[] might be server only though. In that case I would use FindObjectsByType()
Do I always have to micro manage sending all the information back out when people join mid game? It's a hassle...
So what it seems I have to do is
- New Player Joins and sends their information to the server
- Server sends the new information to everyone
- Server sends all the player information to the new player
Yeh it is server only, but generally I've found it's probably easier to just rely on the server to handle catching people up and etc
I honestly thought unity would automate this, I thought the whole idea was that people join and then Unity makes sure that the new client matches the state of the game as they joined, I didn't realize I had to handle syncing everything up myself, I'm not quite sure what is kept synced and what isn't? Is there a rule of thumb with that?
Only Network Variables, Network Transforms, Network Animations, and Network Rigidbody are synced automatically
You can make a NetworkVariable<Dictionary> but it's currently buggedr
So scripts that need to sync, I would be best off having an "Awake" in it which sends a request to the server to be updated and have the server send the information of the object back?
Bugged how?
OnChangedValue is not getting sent when they are updated
A fix is in develop but not yet released
Lets do an example with NetworkVariables because I haven't used them yet.. If I have enemies spawn and the player jumps in late, if I set the HP text in Awake would that be correct when the player joins?
Basically is the NetworkVariable updated before or after Awake?
fishnet forum question I hope somebody can help me: https://discussions.unity.com/t/fishnet-stuttery-jittery-movement-extreme-latency/1507683
I’d say you’re better off scrolling the background than actually moving the players down the entire time.
But if you’re experiencing too much jittering under ideal networking conditions, you probably have to play with the interpolation settings.
Yeah I undestand that but latency is allready way to much
and interpolating would just higher it even more
You’re never going to beat the delay of latency unless you have some sort of prediction in place.
That’s why I recommended moving the background instead of the players, it’ll hide the latency much better.
so its normal what I am getting here?
The delay between the local and remote clients, yeah.
The jittering, not so much. Not sure how FishNet’s interpolation works but adjusting it should help to make the movement jitter-free.
Hm ok but lets be honest even if I move the background the situation wont be much better. Isnt there any solution to this? arent there any host/client games that need to have low latency because my kind of has to not in a competetive way but atleast a bit
Moving the background is how almost every game that is a similar style to yours handles constant/endless movement. You’ll probably notice a slight delay between clients for the background scrolling but I’d say that’s a lot better than what you’re experiencing now.
It means your players will be right next to each other the whole time without delay or jitter.
You can't prevent latency. You can only work around it. That is mainly what a client prediction system is for
And it’s also important not to fall in to the trap of comparing delay in side by side windows. As long as it isn’t effecting gameplay, latency is normal.
Something like a slight delay in background scrolling will be largely unnoticed by two clients playing on separate machines.
Yeah but the problem is that in the end the game shouldnt be endlessly down
And for example idk if you know the game "stick fight: the game" but its a fighting game and with my latency im producing here that would be unplayable and its also client/host.
Sorry guys youre just trying to help
but thats disappointing
Just means you have to stop the scrolling and handle your players landing on the ground.
no they have to go in circle round first fall down and then get up with ventilators and stuff
and flying rounds
You can scroll the background in any direction needed.
What you’re wanting to design probably requires a dedicated server as well as some sort of client side prediction system.
No its host/client
I’m aware that it is currently. I’m saying a dedicated server is probably the ideal choice for what you want to make.
But then I would have to synch the position to the other player and that would be essentially the same
No i meant the game i am talking about is host/client
And that would just cost me money wouldnt it?
The game you’re talking about is peer-to-peer I’m pretty sure. It’s also pretty known for desync and delay issues.
You can self host it. or have the players host it. But you can also do client prediction with a client/host setup
Ok but again my difference of heights in my video are huge or am I overreacting and its totally normal?
As I said previously, the delay between positions is quite normal without a client side prediction system.
Designing multiplayer isn’t about “beating” latency, it’s always going to be there. It’s about masking it as best you can with good mechanics and by playing within the limitations of networking.
The only reason it’s noticeable is because you’re only applying a constant downward force and staring at the windows side by side.
If the players were moving around the screen and only looking at their own screen, the delay is going to be a whole lot less noticeable.
I hope its ok that i send it here but as you can see this is a p2p game and I believe that the latency is 1/4 of mine
1/4 is generous. There's maybe a slightly smaller delay than your setup. It just looks better because the movement is smoothed without jitter and there's animation.
If you're really unhappy with the delay, you can try increasing the tick rate of your server. It looks like in FishNet you can change that on TimeManager.
Ok thanks for your time I think Iam just trying to do the best out of it with: smoothing out, googeling about this prediction thing slowing the players down and hoping for the best! thanks
I also think FishNet has client side prediction built in to the solution in one way or another. Probably worth checking out
Seemingly simple question, but I cannot find a good answer in the documentation. What is the idiomatic way to estimate server-client latency in Netcode for gameobjects ?
this is usually provided by whatever transport you're using, i think you're looking for GetCurrentRtt?
There is pretty good Ping Tool that was added a few weeks ago
Its in the NGO 2.0 branch. I don't know if it works with 1.x.
Hi everyone, I am researching for a top down 2d shooting game(ANDROID) that I am going to start working on, I want to add offline multiplayer in it where users can host/join the match by connecting to the same network with or without internet, I am trying this for the first time but am unable to find any good resources for this I was wondering if anyone here has worked on it before and can guide me through this or provide links to articles or tutorials. All that I found is at least 3,4 years old
For Lan multiplayer, you would need to use something similar to Network Discovery here
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
Have you used it recently? I read in some forums that UNET API's no longer works with newer versions of unity
BTW thanks for the link I didn't know about this repo it will help a lot
That is not using UNET. But it was made with an older version. should still work with the current NGO with minimum changes
I will try it thank you so much
Hey guys, I'm using Netcode for Gameobjects and everything is working with the exception of the character flipping. To flip I rotate the player but it doesn't show the other player flipping on their screen, it only shows them facing 1 way. ``` private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
// rotate if we're facing the wrong way
if (movement.x > 0 && !facingRight)
{
flip();
}
else if (movement.x < 0 && facingRight)
{
flip();
}
}
private void flip()
{
facingRight = !facingRight;
playerSprite.transform.Rotate(0, 180, 0);
}```
Flip() needs to be an RPC
Thank you, I fixed it!
Am I blind? I remember networking in the past, the network manager would have latency simulation options but I can't find any
https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/
Why can't I add this component to anything? It doesn't exist and I urgently need it
The Network Simulator tool allows you to test your multiplayer game in less-than-ideal network conditions, enabling you to discover issues in simulated real-world scenarios and fix them before they surface in production. It facilitates simulating network events, such as network disconnects, lag spikes, and packet loss.
did you add the multiplayer tools package? it doesn't come with NGO itself
do you have any errors in the log?
None
I can start my game, I can play, I just can't add that
I have issues where some of my network stuff isn't syncing with clients not in my house and it's impossible for me to debug and fix it because I can't get latency locally... I can't get my friends to download my game every 2 minutes to test things and yeh... I have the package but that component just isn't showing up
Pretty sure it's built in to the Transport now
Debug simulator?
Yeah
@unique moss
It lacks a lot of things though like testing disconnects and etc
I'm not using unitys transport anyway... But I'll see if I can use it just for testing, thanks. I still think it's weird that the scripts are not showing up in my add components at all
Even if it was deprecated, it should still be there?
I don't think it is deprecated
Don't think it's built to work with other Transports
Oh wait mine has unity transport 1.4.1 but I don't have the option to update
Nvm I see it
Thanks
Yeh that fixed it
I didn't realize my transport was outdated
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
uhhh can someone help me a bit
!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
so with netcode, how do I synchronise rigidbodies and objects between clients?
NGO has a NetworkRigidbody component that you can pair with NetworkTransform
I have paired them... I think
ok ughh ive paired them but this happens
Probably has to do with your code that moves the objects
oh ill check it out
prob missed smth
Feel free to send it in here
yup i forgot to make it networkbehaviour
headslapemoji
thank you
oop nothing changed
i thought it resolved for a sec
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class spinObject : NetworkBehaviour
{
public bool hammer = false;
public float rotationSpeed = 100f; // Speed in degrees per second
void Update()
{
if (!hammer)
transform.Rotate(0.0f, rotationSpeed * Time.deltaTime, 0.0f, Space.Self);
else
transform.Rotate(0.0f, 0.0f, rotationSpeed * Time.deltaTime, Space.Self);
}
}
You're moving your objects on all clients with that code
NetworkTransform is designed to move objects from the server and it will automatically sync the position changes to all clients
You just need if (!IsServer) return; at the top of your Update function
Hi everyone 🙂
Anyone know some resources or tutorials about the Dedicated Server ?
You are going to have to be more specific. But you can check the NGO docs here
This is part one of the Porting from client-hosted to dedicated server-hosted series.
Hi, question. I want to use the Unity Cloud services Relay, Player Auth, and Lobby. With NGO
And I have "Multiplayer Services" (1.0.0-pre.1 with Unity 6000.0.15f1) installed, I also installed "Relay" and "Lobby" deps, but it throws ambigious reference everywhere
So I gess Multiplayer Services already includes this two deps? which one should I use?
Yea. you can remove the relay and lobby packages
Multiplayer Services wraps all of those packages in to one for ease-of-use.
I've never used it but I would assume you don't need to go out of your way to install Relay or Lobby on your own manually.
ok, thank you
I would install the Widgets package as well.
Thanks !
yo in what channel I could ask for help in general stuff?
Whats that for?
Im not sure if you were talking to me or someone else
It makes using sessions stupid easy. It gives you a bunch of UI prefabs to make connecting and managing sessions as breeze.
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/build-your-first-session
The only problem I see reading this, it that is uses matchmaker and multiplayer hosting, which afaik does not have free tier
You don't have to Server Hosting. And Marchmaking can now matchmake into Relay
Not able to get Network Transform in Owner Authority Mode to syncronize from the joining players side (that owns the transform), only the host clients character transform is syncornized.
Whenever i update the joning players "Slerp Position" settings through the inspector it seems to force the Network Transform to send an Update to the host....
Unity 6000.0.15f + Netcode For Gameobjects 2.0.0-pre.4
Is this a bug with these versions of netcode/unity? It seems tow work fine with the "AnticipatedNetworkTransform" but plain does not sync (unless fucking with it in the inspector) with a regular one? I cannot figure out why it is not syncing client -> host, only host -> client, it is owner autorative, and the client owns the object, everything else works, just not the networktransform.
Can anyone help me figure out why this code doesn't work properly?
If there is no latency, like if I join from a local network laptop, the name updates.. But if I add artificial lag, when a player joins, they don't update the names of any players that joined before them? How am I meant to do this?
I really don't understand how I am meant to sync up the players...
Ok downgrading to com.unity.netcode.gameobjects@1.9.1 + Client NetworkTransform seems to work for me, there might be something wrong with com.unity.netcode.gameobjects@2.0.0-pre.4 and the NetworkTransform set to owner authority??? I guess thats what i get from using prerelease versions..
This should work. Are the network variables not getting set? Lag should not effecting anything there. If this is on the player then DontDestroyOnLoad is not needed.
That is strange. I'm using NGO2.0 and client network transform is working fine.
Oh I think that is left over when I tried to manually spawn objects myself, but it ended up harder
And the value is set, it's in the code in "IsOwner" and the host always stays up to date... Like if 4 people join then it has all 4 names correct
But if a 3rd player joins it doesn't have player 1 or 2's
Try using IsLocalPlayer or HasAuthority instead. Ownership might be being set right away if there is lag
Hello, what's the current state of networking assets in unity?
I am looking to have this sort of an architecture:
- Client Server
- Fully server authoritative
- Tick based and fixed delta time
- Clients rollback on predicted object(s)
I have been trying out fishnet for quite some time but its predictive features seem to change quite often.
And the latest version doesn't seem to have any examples.
Hi,
Netick (our free networking solution) is exactly designed to satisfy those requirements.
The prediction API is close to writing a single-player game. There is actually not much "API", it's designed to be as transparent and simple as possible, yet very powerful.
Regarding examples, we have a free full Rocket-League clone coming soon, in addition to other existing samples.
Thanks, I am looking into it.
Hello, i'm trying to make a system where :
When you lunch the game you spawn in a lobby where you can move (this is done)
When you join an other lobby you spawn at a specific coord and the player who joinded he can see the other players (here is my problem)
I can't manage to spawn the players for the one who is joining and i have this message
NetworkPrefab could not be found. Is the prefab registered with NetworkManager?
if (NetworkManager.Singleton.IsServer)
{
foreach (var client in NetworkManager.Singleton.ConnectedClientsList)
{
if (client.ClientId == NetworkManager.Singleton.LocalClientId) continue;
player = Instantiate(playerPrefab);
player.GetComponent<NetworkObject>().SpawnWithOwnership(client.ClientId);
}
}``` here is the code where i try to spawn the player
Not to be a broken record.. but is the prefab registered with NetworkManager?
Yea. sounds like that prefab is not in the Network Prefab list
well it was saved but got deleted i'm trying by re binding it
well it worked that was quite fast
thank's guys
Is what not working? Is it not connecting or the debug simulator not working?
Hi.
Im trying to hide a player object (from ALL people on the session including himself).
so, im doing this:
public class PlayerHiding : NetworkBehaviour
{
public override void OnNetworkSpawn()
{
if (IsOwner)
gameObject.SetActive(false);
}
}
But this gives a problem the second time, not the first time, I start the network manager. It starts spamming this error every frame:
MissingReferenceException: The object of type 'Unity.Netcode.NetworkObject' has been destroyed but you are still trying to access it.
When I remove this line, everything works perfectly. how can I achieve this?
NGO: 2.0.0 Pre.4
Unity: 6000.0.15f1
just in case
Is there a way to buffer RPC in Netcode?
what do you mean buffer RPC?
Like Photon Unity Networking, buffering RPC so that the RPC will gets called for newly joined player if they were not in session when RPC originally called out.
No, that is a very bad idea.
That's what networked variables are there for.
I think Netcode in built does not support it yet
In my usecase network variable cannot help me with that.
Buffered RPC are actually very useful
whats your use case
Why not?
I once tied with buffered RPC, but they are actually bad
The Timer starts for other player via RPC. And when new player join the timer does not start for it because that player was not there when RPC triggered
I know a workaround for it but wanted to know if RPC buffering can be done
I can do that without network variable tho
Ohh
Use the change event of the networked variable for this.
the buffered RPC was the workaround. The solution is using timestamp
Ohh never tried events
Buffered RPCs in my opinion is one of the worst ideas in game networking.
I'll checkout timestamp, never knew it existed
no, the concept is
I switched from PUN to Unity and I was very much dependent on buffered RPC :- (
Ohh
You are learning bad practices.
This is not something Photon even recommends anymore in their newer solutions.
Dang, ima not use that now
There are a handful of other ways to implement timers with NGO. A buffered RPC is probably the last way I'd try to implement that.
No, the timer runs on Server time not on RPC. RPC only used to send the trigger that timer started and the duration
Even less reason to want to use a buffered RPC.
nvm i use network simulator instead
Anyone here messed with client side prediction alot,I have a few questions regarding principles you should follow when doing client side prediction
I am currently trying to figure out, how to share webcamtextures from different users across the network. Is there any reasonable solution available or should I just fetch the webcamtextures data and send it over websocket or similar?
What questions do you have?
I use it in every one of my games. If you are using the right library, it's trivial to set up.
I am currently using fishnet but cannot for the life of me get the jitter in the physics to stop
because with it i need to do the replicate OnTick and reconcile OnPostTick but when i use the time manager instead of unity physics alot of bizzare stuff happens
I am not familiar with using FishNet.
However, I have seen multiple people having jitter issues with it. Are you sure the issue is in your code and not the library itself? What does the jitter look like?
If all you are doing is a basic physics controller, there shouldn't be any noticeable jitter, in a proper CSP system.
Unless there are mispredictions bugs etc.
I am using a physics controller called sci fi ship controller and i dont know if the real issue lies there since its physics is just being done on fixed update
Interesting.
That's usually the problem with CSP bugs when people use non-CSP-ready controllers.
Anything that effects the movement logic must be networked. All timers, etc. Anything that is not properly networked will cause mispredictions that lead to jitter.
You think it will be a problem if i transfer over the fixed update code over to the replicate method that it might fix the issue?
Any advice you can give will be helpful
Though looking at it, it looks like the movement is not very complex, so I assume fixing this should be simple, if it's a misprediction bug in that asset, and not the networking library.
I wonder if it could be a bit of both
Not really familiar with that networking library. So I can can only give general advise or an insight on what I personally use.
What we do in Netick is simply define an input, and a bunch of network variables vital to the movement. Then simulate the vehicle/player inside NetworkFixedUpdate.
That's all there is to a full working CSP movement.
Socket IO implementation in unity
Yea i am subscribing to the OnTick for the replicate code
So its the same as fixed update
You could ask the author of that asset to help you find what the issue might be.
Ask them what variables change over time, that affect the movement of the vehicle?
Then you simply network those variables.
Thx will do