#archived-networking
1 messages · Page 30 of 1
If there are random variables, you will simply have to use a synced variable that will act as the random seed.
Funny thing after i commented out the fixed update in the ship controller and made it a public method to access inside of the replicate method it looks alot better already
#1277919825771102269 Hello everyone, I ran into some issue with socket IO. can someone help me out. Thank you!
Ah, alright. Will checkout the webrtc package and see, if it fits my needs 🙂 Thanks a lot!
Bump, anyone know?
Thanks
You can't disable the gameobject and still get updates for it. You should probably just disable the renderer if you just want it invisible
I have a pretty hard time with my game manager. Someone can help me for basic network stuff ?
It would be great to do a call
in 20min you will help me a lot 🙂
Yea I also dont care about updates
I think what I should do to be more clean is instance the player objects at a later moment, in another scene
Hey guys. How can I use rpcs and/or network variables to send data from the server to clients? More specifically, I have enemy projectiles that are spawned on the server and I need to tell the client version of the objects the color and amount of damage. Ive tried using rpcs and network variables but have been struggling to get it to work. Any help would be appreciated.
If those are just values then I would use network variables on the prefabs. You can use OnSynchronize() to set them before they spawn
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.
does anyone know why part 1 seems to be missing?
They are all listed here
Thank you
Thank you. I figured it out.
I had the network variables on the child of the network object so i moved them to the network object itself and it worked.
Hey, if I want an fps character to have a muzzle flash and bullet be visible not only to the local player but to everyone in the multiplayer session what steps would i take for that? Thank you!
You could either spawn the effect as a network prefab or you can send an RPC to everyone to trigger the effect
For anyone who uses/has used Unity Cloud Storage, is there any console or tool in the dashboard itself to make queries(SQL or otherwise)?
Is webRTC still a thing in Unity? It has not been updated since Oct 2023 and that makes me curious, if that has just been dropped and would require extra work to make it available in Unity 6?
I believe the devs said that they were working on getting queries in the dashboard.
Did you get errors when installing the 3.0 version in Unity 6?
There seems to be the plugin register part missing when building which was a common issue before from google results. From there i discovered it hasnt been updated for so long and am not sure if its still relevant at all anymore
how does NGO handle adding components to networked objects? I need to add rigidbodies to objects at runtime, server side only
does this invalidate the prefab when trying to spawn it on a client in the same way that adding and removing game objects does?
For spawning only the ID is relevant
It can be associated with entirely different objects if you do choose (at the loss of all convenience)
So you can add non-network behaviors without affecting the client
hm, okay
I'm going to have to figure this out then
trying to look at destructible buildings, though I think I'm going to have to change thinks up a fair bit with how I'm handling things
Anyone run into stuff like this before using native C# TCP socket APIs?
https://discussions.unity.com/t/native-c-tcp-socket-apis-have-multiple-bugs-in-unity3d-but-not-native-console-apps/1512087
I'm really wondering if Unity overrides the .NET Standard 2.1 Socket APIs with its own version? (I have this old memory of reading something like this long ago but can't remember). I'm stumped at what else this could be given it works fine on console apps with the native .NET 8 or Mono runtimes running on Windows or Linux.
.NET standard 2.1 is just a specification, the implementation unity uses is mono (as opposed to microsoft's dotnet) and yes i think it's customized to unity somewhat, but i don't know about sockets specifically
Well Mono is just a runtime. The same libraries are either compiled by Mono Jit or IL2CPP.
And if I manually copy the .NET Standard Socket libs over in Assets folder I wonder if it uses those instead of whatever Unity is including. (which I should probably try)
If Unity is in fact modifying socket libs, why? And if its for platform support, does this mean MS libs wouldn't run on say PS5 and Switch? (which is another reason I'm trying to figure this out)
mono is also where the libraries come from in the first place, they're not the microsoft ones, so trying to paste in system DLLs from a different library might not work as expected
obviously you can add whatever extra libraries you like if they're pure C# but stuff like sockets usually needs some kind of OS specific code to work at some level
This isn't true. .NET Standard libraries while yes are a standard are shared across runtimes. As the runtime has nothing to do with the framework here. The Mono runtime can still load the same libraries. This is why when you pull Nuget packages, it will just pull the same ones.
https://www.nuget.org/packages/System.Net.Sockets
Like I can just manually download that
The Mono runtime used in Unity is also 6.13, while the last version is 6.12 on legacy repo. So Unity must be pulling Mono runtime from MS dotnet repos. Which means they're also just sharing the same .NET Standard implimentations
i think you're mixing up .NET framework and .NET standard here, standard is a specification that unity's mono libraries implement, but mono is a totally separate third party implementation that had nothing to do with microsoft when it was created
I'm not mixed up. .NET Standard has standard implementations of libraries not just specifications. While yes, you're correct Unity could be using a different implementation based on the spec.
there's "the standard version of .NET" which is microsoft's .NET SDK, but ".NET Standard 2.1" is just an API that both mono and .NET implement
Mono is a runtime, its legacy stuff based on .NET Framework yes was a reimplementation BUT the modern Mono runtime just consumes the same libs as .NET 8 runtime does for example.
I don't need a lesson in .NET. I'm already an expert on this topic.
But you're probably right. Unity is probably using a different version of these socket libs.
i wish unity ran on .NET 8 lol, they're working on porting it to modern .NET but unity's mono is based on an ancient copy of mono
No kidding
Well it was actually updated. It says its Mono 6.13 which isn't an old version. Ubuntu 24.04 is on Mono 6.8
And it works perfect on Ubuntu 24.04
Anyway as an experiment I'm going to try to force Unity to use the Microsoft version of these libraries just to see what happens. I'd like to confirm this is actually the issue going on in Unity.
@fluid walrus So it does look like System.Net.Sockets implementations are standardized around runtime in this case. I would have thought the implementation here would be more standardized as I'm sure it is more in .NET 8 for platforms. Now given Mono's .NETFW implementation works correctly, I'm going to assume Unitys has bugs and is in fact old or based off old buggy versions. Unity also seems to ship with a bunch of versions and IL2CPPs seems to use a different one.
I can probably override some of these to fix the issue on some platforms. But IL2CPP must have its own for reasons.
Unity is shipping a .NET Core one a little behind the main .NET Core one. Not sure what one the editor actually loads
Anyway, not much I can do here really thats practical outside report the bug
i want to receive data in unity through serial connection to raspberry pi pico ...i am able to open port but data is not being received
Anyone know how to serialize a byte[] ?
I want to get a byte[] stored on the server from the client using a NetworkVariable<byte[]>
I don't really understand the Unity documentation about that 🤔
NGO serializes byte[] by default.
How are you declaring and initializing this?
public sealed partial class GameManager : NetworkBehaviour
{
[SerializeField] public NetworkManager _networkManager;
public NetworkVariable<byte[]> addon = new();
}
@tame slate
Hello! Im having an issue with Unity's Transport . . . I believe that is the issue. When you client/host or start the dedicated server using unity.netcode, nothing happens. The server is not actually listening on the port that it was assigned. The correct port was forwarded under the correct ipv4 address and im using powershell to ping the server after it starts. I tested this on a terraria server and the pings come back just fine if there is a service listening to that port. I am lost and cannot proceed. With fishnet, this part, the most important part, simply worked
Yeah, I'm not sure why this is firing errors when the docs says it should be built in. Maybe there's some extra consideration when using it in a NetworkVariable vs an RPC.
https://docs-multiplayer.unity3d.com/netcode/1.11.0/advanced-topics/serialization/cprimitives/
C# primitive types are serialized by built-in serialization code. These types include bool, char, sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and string.
That being said,
public NetworkVariable<List<byte>> addon = new(new List<byte>());
seems to work just fine
and is what I would probably prefer to work with
There are sometimes some settings you need to set on the "SerialPort" object for it to work.
I forget off the top of my head but go though some of them
And sometimes you need to use a different baudRate. Make sure those match etc. (I'm guessing you're using 9600?)
Try setting these
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
Try setting rate to: 9600, 19200, 38400, 57600, 115200
Try forcing the encoding: serialPort.Encoding = System.Text.Encoding.ASCII;
Try setting buffer sizes
serialPort.ReadBufferSize = 4096;
serialPort.WriteBufferSize = 4096;
Try setting line ending: serialPort.NewLine = "\n";
Try setting timeouts
serialPort.ReadTimeout = 2000;
serialPort.WriteTimeout = 2000;
Try setting: serialPort.Handshake = Handshake.None;
Try setting: serialPort.StopBits = StopBits.One;
Try setting: serialPort.DataBits = 8;
Just make sure you have parity on both devices. And try with .NET 8 runtime not just Unity3D as their library implementations sometimes have bugs I've recently found out
Ok let me try these
thanks i am now able to send data.
I simply start the server with console commands, connect the client and then try to create a player for the client from the server, but I keep getting this error
Player prefab has networkObject comp.
What i am doing wrong ?
NetworkBehaviour index 0 was out of bounds for Player. NetworkBehaviours must be the same, and in the same order, between server and client.
I try to practice typing simple commands to understand the flow and network operation.
Sounds like you are destroying a component on the network object. You will also need to make sure that the Network object is spawned before calling the RPC
I dont destroy anything how can it be 😄 also i am checking spawn status in OnNetworkSpawn is that imp. correct ?
Don't know. For some reason its seeing a difference in the player prefab on the server and clients
GameObject player = Instantiate(_playerPrefab.gameObject);
NetworkObject playerNetworkObject = player.GetComponent<NetworkObject>();
playerNetworkObject.SpawnAsPlayerObject(clientId);
this is working but
NetworkManager.Singleton.SpawnManager.InstantiateAndSpawn(_playerPrefab,clientId,false,true);
this is not working i think its a bug i cant understand ...
When i set forceOverride = true problem gone but why anyone can explain
Its already in my default network prefab list why i have to set force to true
What version of NGO are you using? There was a bug where InststiateAndSpawn() was ignoring ownership
1.10.0
The bug I was referring to was fixed in 1.10. This seems to be something else. You can enter a new issue here https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues
I've had a problem for 2 days and I can't seem to solve it.
I'm trying to make my player move script multiplayer but I can only move on the host side. I can't move other clients
Everything is configured correctly, I've followed the same tutorial 2 times but it doesn't work and I'm at the point where I don't know if I'm the problem or if Unity has a problem 🤯
The player have:
- Have the NetworkObjects script
- Have the NetworkTransform script
I also tried to put this code on the player i have the same problem:
public class NetworkClientTransform : NetworkTransform
{
protected override bool OnIsServerAuthoritative() => false;
}
}
- The player spawn automaticaly from the prefab set in the NetworkManager
There is my code:
private void Update()
{
if (!IsOwner) return;
_hasAnimator = TryGetComponent(out _animator);
JumpAndGravity();
GroundedCheck();
Move();
}
If anyone know how to solve that 🙏
(I use Unity 6)
If you look at IsOwner and IsOwnedByServer, the owner seem to change everyframe, true, false, true, false...
OwnerClientId change to, 0, 5, 0, 5...
The host:
How are you spawning the players? and where are you checking IsOwner?
Yeah i have checked IsOwner, the player spawn from a custom player spawn script
public class PlayerSpawner : NetworkBehaviour
{
[SerializeField] public GameObject playerPrefab;
public override void OnNetworkSpawn()
{
if (IsServer)
{
NetworkManager.Singleton.OnClientConnectedCallback += SpawnPlayer;
}
}
private void SpawnPlayer(ulong clientId)
{
var playerInstance = Instantiate(playerPrefab, Vector3.zero, Quaternion.identity);
var networkObject = playerInstance.GetComponent<NetworkObject>();
networkObject.SpawnAsPlayerObject(clientId);
}
}
You need to make sure that only the server/host is calling SpawnPlayer().
Hello, i am building an 2d mmo ,and right now i working on the latency system , i went with two approach, the first one is trying to sync the time between the server and the client and adding in the packet header a timestamp of the time the packet sent, and that how the server can calc the time took for the packet to arrive, but this approach can cause a const delay that not really coming from the network and even a 20 ms offset is important in term of ms , my second approach is i know i have a 30 snapshot of the game a sec so it mean 1/30 is the time each snapshot need to come so i did is
delay = current_snapshot - last_snapshot - 1/30
( and each 10 snapshot is giving an avrg of the delay)
but now the delay is only come from the snapshot and i am not sure if it ok to do this way.
You are going to have a bad time if 1 frame delays break things. But it sounds like you are trying to implement rollback netcode. which is going to be an even worse time with more than a few players
i am not sure what you saying here,
i don't want a rollback
all i am saying is if my server is 30 ticks a sec, is it valid to know the network latency from getting the delay between the snapshot?
The quick and dirty way to use 1/2 of the GetCurrentRtt. A more full featured way is to use the PingTool
i am not using netocde 😦
If snapshots are being sent every frame then comparing timestamps should work. A more accurate method would be to send RPCs(or whatever you have in your framework)
Only the server call the host
I have tried to create a simple move script and its sync on each client ! (i update the transform position)
So, i think the problem come from the ThirdPersonController script but i dont know why..
The ThirdPersonController use the _controller to move the player, did you think that can be the issue ?
Check out how the Client Driven Sample uses the Third Person Controller.
Im creating a multiplayer first person game, how to make your camera cant see your own character but can see other?
Hey guys I'm trying to get Multiplay + Matchmaker to wrok but I'm having some issues. I was getting the error "Multiple Allocation Error: request error: maximum capacity reached (1)" when trying to connect as a client, so I went to the server logs to check if my code was working properly, and after a few debug logs I noticed this:
private async Task<MatchmakingResults> SubscribeAndAwaitMatchmakingAllocation()
{
if (_multiplayService == null) return null;
Debug.Log("- Got to SubscribeAndAwaitMatchmakingAllocation pre-subscribe");
_allocationId = null;
_serverCallbacks = new MultiplayEventCallbacks();
_serverCallbacks.Allocate += OnMultiplayAllocation;
_serverEvents = await _multiplayService.SubscribeToServerEventsAsync(_serverCallbacks);
Debug.Log("- Got to SubscribeAndAwaitMatchmakingAllocation pre-allocationId");
_allocationId = await AwaitAllocationId();
Debug.Log("- Got to SubscribeAndAwaitMatchmakingAllocation pre-GetMatchmakerAllocationPayloadAsync"); // <--- Gets to this log
var mmPayload = await GetMatchmakerAllocationPayloadAsync();
Debug.Log("- Got to SubscribeAndAwaitMatchmakingAllocation post-GetMatchmakerAllocationPayloadAsync"); // <--- Never gets to this log
return mmPayload;
}
private async Task<MatchmakingResults> GetMatchmakerAllocationPayloadAsync()
{
try
{
var payloadAllocation =
await MultiplayService.Instance.GetPayloadAllocationFromJsonAs<MatchmakingResults>();
var payloadModelAsJson = JsonConvert.SerializeObject(payloadAllocation, Formatting.Indented);
Debug.Log(
$"Matchmaker Allocation Payload: \n {payloadModelAsJson} \n in {nameof(GetMatchmakerAllocationPayloadAsync)}");
return payloadAllocation;
}
catch (UnityException e)
{
Debug.LogError($"" +
$"Failed to get Matchmaker Allocation Payload: \n {e.Message}");
throw;
}
return null;
}
None of the logs in GetMatchmakerAllocationPayloadAsync() are even showing. Can anyone help?
Here is the full code
I'm trying to get multiple players to more through Steam + Facepunch stuff. running into the issue where the host can move around while the client can't do anything. Value's are going through the script properly since client still is owner and inputs are still reacting to him, they are still not allowed to move through and I'm not sure why. Any help would be appreciated!
value's of the cahracter who isn't allowed to move
usually, you will put the local player on a different camera layer
I'm having some Vivox issues.
Whenever the player joins the voice channel they immediately leave right after. I can't find any fault in my code that would cause this as they are never logged out (which is where I have any code for leaving the channels).
Been debugging this for a while now and I can't find any solution. They stay connected for about 3 seconds before they leave which then closes the channel.
is there something in Vivox that makes it automatically leave channels if certain conditions are not met?
No, in fact it should automatically try to reconnect if it looses connectivity
how odd
I've tried the sample scenes and they work fine. But none of the sample scenes include 3D so I'm curious if I've just set it up wrong
hey guys, whats the difference between this https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-signin-google and this https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-signin-google-play-games
i have an online game, and im trying to make it so that when you play online your name would show above your head, normally i get the player name from the players data which is saved on a server and i get through httpclient code with a signin, but i couldnt figure out how to do that in multiplayer, like there is a sign in panel and i take the email and password from there, but the email and password are different on each device so on other peoples devices it just shows everyone has the same name as theirs
They are technically 2 different id service providers. I believe Google Play is Android only
like i use the network manager player prefab to spawn the players, but how can i spawn a player with a different name if the prefab is the same
If you are using NGO then you would use a network variable or RPC to set the player name
i tried using rpc to set the name afterwords, but i cant access the name on the other devices, like for example the hosts name is john, and the clients name is jimmy. on the hosts side when the player tries to do the rpc command. it puts the name that is saved on the game manager which i get by using the http clients sign in method, but the name that is saved is the hosts name so everyone on the hosts sides name becomes john, and the same thing happens for the client and everyone becomes jimmy for the client
It would be easier to use a network variable for player names. that way you don't have to request it for each player
can you explain what a network variable is ? i dont think i have ever used or seen it before
What Networking Solution are you using?
If you are using Netcode for Gameobject the docs are here
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
thanks i will check it out
im using netcode for gameobject and relay
I have been using NodeJS + Socket.IO + MongoDB for my game. Though, I think I'd prefer also using C# for the server instead of JavaScript.
I think SignalR is the most popular choice for a C# socket server, however I read SignalR client (C# web socket client) does not work with Unity IL2CPP, so that's stopping me for now.
Does anyone here use C# socket server successfully for Unity client?
Any Websocket server library should work, including the one included with .NET.
Right, but what socket client do you recommend to use inside Unity? SignalR client won't work: https://github.com/dotnet/aspnetcore/issues/12102
I am having a similar issue as #10080. I am using preview 6 of asp.net core SignalR client inside of unity and compiling with IL2CPP. I created a small git repo with the code I use to reproduce thi...
Here are a few
https://docs.unity3d.com/Packages/com.unity.transport@2.3/manual/index.html
https://github.com/James-Frowen/SimpleWebTransport (Used by Mirror)
https://github.com/endel/NativeWebSocket (Used by Colyseus)
hey guys, im trying to use a network variable but i get this error.
what should i do ?
i think you'll need to use a FixedString
im not sure what that means, but i just did some research and turns out i cant use network variables with strings
what is a fixed string ?
FixedStrings are from Unity.Collections, they're fixed length strings so you pick the type that matches the size you need
im using the network variable like this
private NetworkVariable<string> characterName = new NetworkVariable<string>("placeHolder", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
how should i change it ?
private NetworkVariable<FixedString64Bytes> characterName and so on
pick your size, it comes in various byte lengths
do i have to use the .tostring for the fixedstring ? becaues it says i cant change type fixedstring to string
where does it say that?
ok yeah, you can assign a string to a FixedString but you have to use ToString or ConvertToString in the other direction
i see
thanks i will try them right not
now
the error message is telling you what to do there, this isn't really a NGO thing it's just C#! remove the type constraint
there's an example in the NGO docs: https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior-synchronize/
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.
thank
The server will sync it with the clients, yes.
👍
Hello. I couldn't found any answer or related post. Is it possible to use netcode for entities with Steam p2p relay sevice? I want to use DOTS/ECS
hey guys, i have this code for changing the player name in my multiplayer game. i want the name to be shown above the players head.
private NetworkVariable<bool> changePlayerNamee = new NetworkVariable<bool>(default ,NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public TMP_InputField playerNamePanelName;
public TMP_Text playerName;
public GameObject playerNamePanel;
public override void OnNetworkSpawn()
{
if (playerName.text == "" & IsOwner)
{
playerNamePanel.gameObject.SetActive(true);
}
}
public void changeCharacterName()
{
changePlayerNamee.Value = true;
}
void Update()
{
if (IsOwner)
{
playerName.text = characterFixedName.Value.ToString();
}
if (changePlayerNamee.Value == true & IsOwner)
{
characterFixedName.Value = playerNamePanelName.text;
changePlayerNamee.Value = false;
}
}```
but when the name is changed the name is only displayed on the players device and doesnt show on other players devices
I think you should be able with this sample and using one of the steam transports
non owners will need to set the playerName.text = characterFixedName.Value.ToString(); as well
You should also try to make use of characterFixedName.OnValueChanged instead of doing this logic in Update()
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#onvaluechanged-example
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
I'm having some Vivox issues.
hey guys i have an inventory for the player and made the canvas on the player but now if a player joins it overlaps the other canvas
any idea how to fix it
Hey, its been few years since I quit gamedev. But wanted to get back into it, I have experience in many fields. But was wondering, is HTTP/REST a thing in Unity networking? I want to create Idle mobile online game and I feel that HTTP would be enough for it, while TCP/UDP would be too heavy.
What are your thoughts on HTTP as networking? Are some bigger games written using HTTP?
Ofcourse I dont need any collisions etc, only time and state management
I'd say it's probably doable if your game is simple enough. WebSocket could be an alternative is you need a bit more responsiveness.
hmm, maybe I should look into WebSockets more then, I never used it, but good suggestion
thanks 🙂
You want to make sure that only the local player is displaying any UI.
Cloud Code would be pretty good for something like this
what Cloud Code you mean?
Specifically Unity Cloud Code But Amazon, Google, and Azure all have some version as well
yeah, will look into it, but the idea of writing my own backend appeal better to me, since I'd like to have Java code somewhere aswell lol
When using subtick system, how am I supposed to fix jittering of remote players?
Currently in my game I am sampling user inputs every frame, and sending them every tick. Each tick's duration is 25ms due to tick rate of 40hz. Each input includes the deltaTime used for movement.
On server every tick I am accumulating each player controllers accumulator by 25ms, and only
executing the next input if accumulator >= nextCommand.deltaTime (and advancing next command, executing
all inputs that we can in a while loop)
However with this approach the remote players seem to jitter because on one tick player may move
0.16 units and 0.34 on the next.
Using Lerp should help smooth that out.
The so called "cs2 subtick netcode" is to simply use the alpha of the frame you shot at, instead of the input tick alpha, when doing lag compensation.
The clients will load whatever scene the host is currently in. If you load scenes additively, then all those scenes will be loaded when the client connects. Network Manager will get placed in DoNotDestroy so only the scene when you call StartClient/Host needs it
LoadSceneMode.Additive lets you load multiple scenes at the same time. So you have a scene that is just your game UI, and one that is the level, and one that is just managers and whatnot.
Technically, you can. You can use Custom Scene Management but you then need to sync everything manually. I don't recommend it unless you really know what you are getting into
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
I would use additive scene loading to load dungeons way offscreen like down -1000 then teleport players down there.
There is no best solution. You can use whatever works. I prefer using prefabs for my UI.
Streaming scene loading is fine but just keep in mind that the server will need to have scenes for every connected client load. There are limits to how big the world can be
Sure. You would use the regular scene manager to load the scene additively rather than the network manager scene manager.
anyone have experience networking plain c# classes with netcode? should i just make my own networkobject style class for non monobehaviours?
Not sure what you’re asking exactly. Seems like you’re just describing NetworkBehaviour
Sort of. I want the functionality / ease of use of networkbehaviour but for objects that dont physically exist in the scene.
multiple scenes
You want to use Custom Messages for that
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
i keep getting this error
Frequent RenderTime before m_StartTimeConsumed
ive checked on the internet theres only 1 github thing about it and it doesnt say anything about fixing it
I saw this in the networking discord earlier, but haven't seen anyone give a solution yet. Are you on NGO 1.11?
I've only see a handful of conclusions/solutions from that error before:
- Moving the editor/build window pauses the application which creates some desync in NGO components which can cause that error
- it's a bug
- you're doing something with NetworkTransform that you reeeally shouldn't be doing lol
yeah
i am not moving the window of the editor nor the build
wdym im doing something that shouldnt be done?
He was just saying that as a general statrment, like you're doing something super unintended
Maybe newb question, because I've been out of gamedev for few years.
So I was thinking how to Implement mobile game user account authentication. So the game session is not tied to the device but can be used on multiple devices. What are solutions for that?
I tried installing Clash Royale and I noticed theres something related to google play oauth, is it oauth or something else, anyone knows?
I know I can write my own auth, like theres also SupercellID (or whatever its called in Clash R), but would prefer to avoid the security path atleast at the dev/ early stage
Unity Authentication Service can handle all this for you.
would this work if I will have Rest / WebSocket server outside of unity?
I mean, the server will be in Java
Sure. There are rest APIs listed under references there
Thanks, havent looked into it yet. But from your saying, its what Im looking for! 🙂 Thank you
is there an easy way to get a list of all connected clients FOR clients to reference in netcode ? since i dont feel like rewriting half my script
my idea is that i can make the players spawn under a parent so i can make other clients reference the player objects easily through it but the question is will it work ? and if yes then why is .TrySetParent not working ?
I usually like to store that locally for each client. When clients join, you use the ConnectionEvent or the OnNetworkSpawn of the player objects to store reference of the players for each client locally
i'm kind of new to netcode , so like does the OnNetworkSpawn function get called when the player object spawns ? and is there a way to detect if a player despawns ?
It runs whenever a NetworkObject spawns, player objects included
You could simply use OnDisable or OnDestroy of your player object script
i see , tysm !
Player Script:
public static Action<PlayerScript> PlayerObjectSpawned;
public override void OnNetworkSpawn()
{
PlayerObjectSpawned?.Invoke(this);
}
Player Manager Script:
public List<PlayerScript> playerControllers;
private void Start()
{
PlayerScript.PlayerObjectSpawned += AddSpawnedPlayer
}
private void AddSpawnedPlayer(PlayerScript playerScript)
{
playerControllers.Add(playerScript);
}
This is roughly what I do usually
and you can make the Player Manager script a singleton so you can access the list easily
ohhh okay this is much better than what i was about to do
Does anyone know of any thing built in to unity that can be used to pull the OS arp and routing tables?
Guys, what's the actual reason to use playfab? I keep finding videos and articles about how to use playfab, but not why would I use it. I mean what is the difference between playfab and your own rest api except the fact you are responsible for the api hosting?
It looks like buying the host yourself is a lot cheaper than playfab pricing
scalability, uptime, and SaaS
its like why would you want to use google drive instead of your own hosting?
All of those backends as a service are way more then just a rest API. Most of them offer dozens of services from server hosting to player authentication to payment processing. The security aspect alone is worth the price. Playfab is just one such service. Amazon and Unity also have game services available.
Hello there, i am making a project in unity using netcode for gameobjects, and it runs perfectly on my machine. I want to test in two machines now, that are in the same network, one via wi-fi and another in a ethernet cable. I tried this, but didnt work. The client on another machine cant connect to the host:
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
using Unity.Netcode.Transports.UTP;
using TMPro;
public class NetcodeUI : MonoBehaviour
{
[SerializeField] private Button startHostButton;
[SerializeField] private Button startClientButton;
[SerializeField] private TMP_InputField ipAddressInputField;
private void Awake()
{
startHostButton.onClick.AddListener(() =>
{
NetworkManager.Singleton.StartHost();
Hide();
});
startClientButton.onClick.AddListener(() =>
{
// Get the IP address from the input field
string ipAddress = ipAddressInputField.text;
// Set the connection data on the Unity Transport
UnityTransport transport = NetworkManager.Singleton.GetComponent<UnityTransport>();
if (transport != null)
{
transport.SetConnectionData(ipAddress, 7777);
}
else
{
Debug.LogError("UnityTransport component not found on the NetworkManager.");
}
NetworkManager.Singleton.StartClient();
Hide();
});
}
private void Hide()
{
gameObject.SetActive(false);
}
}
do you guys reccomend using rigidbody/physics for online/multiplayer movement? If not any idea on an alternative?
This should work. But try just manually entering the host IP in the editor on the other PC. Also the host should be set to 0.0.0.0
It should work fine unless you need to implement client prediction for fast paced games.
it would be a fast paced game, you will need to parry and shield against attacks, i could see that becoming frustrating if not a decent prediction system
If it's animation based(Dark Souls) then you could probably get away without using physics
hm ok not sure if it will be animation based, its 2d side scrolling if that helps, havent implemented it yet.
It might be worth it to learn DOTS and use Netcode of Entities and it's built in physics prediction systems
So on the other pc im using just the build, not unity. The ip of the host should be 0.0.0.0 ?
On the host PC, the ip address in the editor should be 0.0.0.0
You might also need to turn off the firewall on the host just incase
im gonna try that, thanks a lot
and in the client i just put in the input field 0.0.0.0 ?
No, that need to be on the host. The client need to enter ip address of the host pc
Okay, and do i allow this?
It didnt work, i tried with allow remote connection on and off
With it on i could connect on the same machine using my host ip
But couldnt connect another machine as a client
Disabled the firewall on the host and didnt work, and disabled both firewalls and still nothing
Hi, I'm looking for advise on a networking setup. The game essentially has 2 players and their own map. They can only control their own unit's on their own map and they can view each other's map but no interaction. Do I have the map prefab spawn as network players or it's better that I just spawn their player controller in?
If the map itself is not changing or moving, I don't see any reason for it to be a network object.
hey guys, i have an online mobile game that uses netcode relay for the multiplayer, when i build an apk and try to test it the multiplayer works fine, but when i make an app bundle for google play and publish it on internal testing and try it, the multiplayer doesnt work and i get this warning message [Netcode] Deferred messages were received for a trigger of type OnSpawn with key 1, but that trigger was not received within within 1 second(s).
what should i do ?
i remember you told me something about the scene taking too long to load, but why doesnt the same thing happen in apk ?
Not sure. Might be because asset bundles take a little bit of extra time to load?
when i asked on copilot, it said this : Increase Timeout: If 1 second seems too short, consider increasing the timeout for deferred messages. You can adjust this in your Netcode settings.
do you think it would work ?
or should i just make a new scene for joining and then load the main scene ?
Increasing the timeout should work. But I would work to decrease the load times so players don't have to wait. Splitting the scenes up would help with that
which option do i need to increase ?
I don't think you can see it in the inspector. For that error I think its SpawnTimeout in NetworkConfig
what is network config ? and where can i find it
found it
how much should i make it ?
umm i dont think i can change it from here
did anyone here ever use vivox ?
i just want to know if it's my mic being bad or if the IsInjectingAudio works differently than how i'm assuming it does
because i'm trying to make the mic icon be different when talking or not when the mic is unmuted
because the function is returning true all the time unless the mic is muted
I could use some advice with my game, I have a multiplayer shuffleboard game using the latest netcode for gameobjects multiplayer library. Right now there is one kind of shuffleboard table and one kind of enviornment so the game flow works by having the network manager trigger loading the game scene for all players and start when they all load in.
I want to add a new shuffleboard table, and a new environment that the users can choose indepently of each other. Is the best way to handle this using additive scene loading? Due to contraints in baking lighting would I need to have 4 separate scenes to be additively loaded, (table 1 with env 1, table 1 with env 2, table 2 with env 1, and table 2 with env 2)?
Maybe I don't quite understand additive scene loading and it's relationship with baked lighting. Is this even the right approach? Thanks for any advice
If it's just a local graphics change then I would just change out the models/environment locally. You could use the plain Scene Manager to load the scene additively as well
hey, i didnt know how to change the spawntimeout so i tried to make a new scene for the multiplayer, i made a scene that only has the network manager and a plane, and i made a new capsule character for the player with a simple movement script. but i still got the same problem, the player spawns on the host side, but on the client side nothing happens
so it shouldnt have to do with the load times being long
Are you certain the app bundle has finished loading on the client? This might be a question for #📱┃mobile I'm not too familiar with mobile development
I'm unsure on where to start learning: I already have moderate unity/programming experience but I'm trying to get into networking and make a simple hearthstone-like card game.
Most of the tutorials I find on YouTube are using a host-client setup but I definitely wanna end up using a dedicated server I think. Are those two things similar to work with in nature--could I start learning with host-client and switch to a dedicated server? (i've been looking at fishnet + playflow im not sure if that would be suited to this)
idk if what i said even made sense
some direction or advice on where to start learning would be appreciated
For such a game to be successful and keep costs down, you must not use Unity in the server side. Most such games, especially mobile card games, don't use an engine in the server-side at all.
Write a highly optimized and multi-threaded C# console server that will be able to handle thousands of matches and players together. You can use a variety of msg-sending libraries to do this. You can even just use the popular LiteNetLib. You just need to be able to handle huge numbers of players in a single server. The game logic for such a game will be fairly simple without an engine.
Note that this assumes a fully server-auth game where cheating is impossible though. If that is not important, then a regular client-auth or player-hosted networking solution would be fine, the only problem would be matchmaking.
There are some differences but the fundamentals are the same. Even if you don't end up using Unity Netcode this is a good write up on the differences and considerations for each
https://docs-multiplayer.unity3d.com/tools/current/porting-to-dgs/client-vs-dgs/
This is part two of the Porting from client-hosted to dedicated server-hosted series.
awesome ty both
I'm using unity servers RN to work on my game and for some reason with errors or messages showing the client players are slower than the host in movement... anyone know a fix?
Client player movement
I'd like to add, that the server doesn't have to be in C#. But can be written in any other language such as C/C++, Java, C#, Python, Go etc.
cc: @indigo cairn
You might wanna checkout things like Nakama for example
would it be easy enough to call a function remotely using networking?
dont need any multiplayer stuff, just calling a function remotely
Unity Cloud Code or any other serverless platform will handle this. Or you can make your own REST API on a Node js server
Hey for some reason only the creator of the server can see not the join code, and so when the server browser is opened only the client that made the server can click on the join button. All of the other text information was set fine the only issue is the join code.
Nvm I switched to using id instead of lobbycode and it worked fine
Networking hmm idk
i saw there is stuff like sendto.everyone or sendto.clientsandhost but idk what that is for? it seems to do nothing, i still have to first call a server and then a client rpc to run something on everyone
(i already asked this but deleted it because i thought i am just being dumb)
Those are for RPC Targets Those two targets can get called from clients and will get run on all clients and the server with no other additional RPCs needed
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
as long as you are on NGO 1.9.1+
uhm yeah i read that but i still don't get what that means, do i have to do anything for it to work, because it cleary doesn't work like normal rpcs
wait 1.9.1? i thought it should work with 1.8.1 because it showed me that it exists in that version already/did compile without errors ._.
sorry it is 1.8
yeah then idk how this works
all you need to do is put [Rpc(SendTo.Everyone)] and have RPC at the end of the function name
The RPC needs to be in a Network Behavior on a spawned Network Object
omg
it took me an hour but i found the problem lol
if (Instance == null) Instance = this;;
else
{
Destroy(gameObject);
}
i have a gameobject that handles the networking, and Destroy(gameObject); was always ran because the instance was not null, because it was spawned by the server on start (i don't understand why this counts tho) and it destroyed itself lol
._. well
This is why I don't use singletons. especially in networking
yeah, learned something today
client network animator suddenly stopped syncing the animations , tho it was working few builds before
netcode btw
also i haven't changed anything related to the animations at all
i may have added some other animators but for other things that are client side but they're for like UI and stuff and not related to the player model , perhabs those might have something to do with it ?
is SyncEnemy throwing an exception?
hmm yea
that would do it!
thank
The given key 'some number' was not present in the dictionary.
what does this even mean ??
the key is not in the dictionary
rpcs and animations stopped working
with this error
apparently it's something related to the issue i was just talking about
Probably means the NetworkAnimator is looking for a certain parameter, animation or layer on another client and cannot find it.
If it's RPC related, it most likely means the NetworkBehaviour that the RPC is being called from can't be found on another client.
i have a script to handle the rpcs on a player and i'm destroying it if !isOwner
Yeah. Don't do that. That's what is causing your error.
Just disable it.
Yeah, never destroy any components.
alright then i'll try
NGO uses the components and other things on NetworkObjects to match or find them between clients
ohhh , well it did work now when i disabled it instead so tysm
still tho could it be the reason the network animator doesn't work also ?
i'll check rq
if it fixed it
Likely if this object also has the Animator that's having issues
nope , one of it's children does tho
yeah it didn't fix my network animator problem
the network animator isn't syncing the animations at all , not to the host or to other clients , as if it's not working at all
it's not server authoritative
it's not throwing any errors either
Network variable delta message received for a non-existent behaviour. NetworkObjectId: 7, NetworkBehaviourIndex: 7
warning i got
That's still pointing to you deleting something on a NetworkBehaviour I'd guess
the main camera maybe ?
does disabling the gameobject of the camera also cause problems ?
or just destroying objects can cause trouble
yeah it's fixed now , thank you so much for all the help ! @tame slate
i'm kinda new to netcode and multiplayer in general , so you've been a great help !
Yea. Network objects should just use spawn/despawning instead of Destroy. And yes, child objects should be disabled instead.
yeah i figured this out , tysm !
did anyone here ever use vivox ?
i cant set network animator during runtime?
i want the parent to have the network animator that reference to the child sprite gameobject's animator
and because i set the child parent during run time the networkanimator seem to act first before OnNetworkSpawn can set the network animator on the parent
so it throw alot of error
You might need a default animator so its not just null
yea just went for that solution
still checkingg if something is wrong
holy shiet it work
wack
What do you think about this?
I used Kaillera. It allows you to record sessions or matches and share the playback.
Hi! I was wondering if anyone has any tutorials or knows how to create an account system for an app where users can have a unique username, log in from other devices, and access information across devices (think iCloud but without the cloud storage and just the multi-device connection).
Any assistance is much appreciated.
EDIT: My app is open source. Will that be an issue?
im using mirror and on one of my objects i try and call ClientRPC but in the NetworkBehaviour 'netIdentity' has not been set and gives me a null why is this happening?
You can use Unity Authentication or other services like Azure Playfab
Does anyone have a problem linux terminal running the unity server doesn't stop when I press Ctrl+C? How do I stop the server?
Make custom handler for stop
Ctrl+Z helped
Thanks! I will check it out. Will it be an issue if my app is open source? Should I make a closed source version?
No issues with that. They are just web apis for the most part.
anyone using pun2?
What would you guys recommend to use for implementing voice chat in a game made with mirror (not photon) other than paid dissonance one?
hey guys, im using relay with netcode. i see this in the network manager.
can someone explain what it is and what i should put in it ?
That is a scriptable object that contains the network prefab list. There should be one called DefaultNetworkPrefabList
and what should i put inside the network prefab list ?
and i am experiencing a problem with clients joining the game. i think i asked you about it before.
im getting an error that says : Exception: Scene 'Assets/Scenes/testing multiplayer.unity' couldn't be loaded because it has not been added to the build settings scenes in build list.
yes the scene isnt in the build list because its in an addressable group so im not sure if thats the problem.
and something i figured out is that when i disable scene management in the network manager the client connects and joins successfuly but only the player and the environment appears. all the canvases are gone on the client side and some objects that hold scripts are gone too so i was wondering if i should put them in this prefab list or something for them to spawn when the player does or something im not sure
I don't believe its possible to load scenes on the network through addressables at the moment
This only needs to be network prefabs that you are spawning. in scene network objects don't need to be in that list
damn
sooo i need to maybe disable scene management in network manager and then maybe try to spawn things using network prefabs or maybe putting them in the player prefab ?
isnt there any other way thats kinda sad
because i need to use addressables to upload the game on google play, but now turns out i cant use multiplayer with addressables ? xd
You can. It's just not necessarily plug and play.
I use Lobby to help with addressable scene loading.
Clients update their player data to alert the Host when they have finished loading a scene addressably. When the Host sees that all clients have the scene loaded, it can make the networked scene change.
Granted, I did this with another Networking solution that's not NGO but you may have luck doing something similar.
hmmm, maybe i will try using lobby
and do you guys know what this error is ? [Netcode] Failed to create object locally. [globalObjectIdHash=3299131434]. NetworkPrefab could not be found. Is the prefab registered with NetworkManager?
and how do i know which object its saying it cant load ?
there is this one as well: [Netcode] Failed to spawn NetworkObject for Hash 3299131434
you should be able to see the ID of each prefab in the inspector for the NetworkObject component on it
bear in mind instances in scenes and the prefab asset itself will have different IDs, but it sounds like you're not using scene management so i don't think you'll be able to have instances in scenes?
im not sure
i wanted to ask something as well, if i turn off scene management in the network manager can i still use the network prefabs list to spawn objects or not ?
you can, but you can no longer have non-prefab network objects in scenes
so everything has to be spawned as a prefab basically
hmmm i seee
i will try my best to make it work
thanks!
im trying to use the NetworkObjectPool the problem is when running NetworkObjectPool.Singleton.ReturnNetworkObject(NetworkObject, prefab);
the object wont disappear on the client side the tutorial I was watching just called NetworkObject.Despawn(); but i get this error when running it
InvalidOperationException: Trying to release an object that has already been released to the pool.
am i supposed to just run a clinetRpc and pretend the objects off on the client?
You shouldn't have to call ReturnNetworkObject manually. Calling despawn on the host/server should do that for you. The pooled prefab handler sets that up
thank you I'm actually so dumb lol
Does anyone know what's the proper way to connect to a Unity server from a WebGL build with ssl? I'm using Netcode.
Without ssl, no issue, I have a simple node server for the WebGL build on port 8080 with a nginx reverse proxy redirecting 80 to 8080. But once I have an ssl, I can't seem to be able to configure it. The webgl build works great but the minute I try to connect to my distant server, it crashes and tell me that I have an invalid endpoint.
I've tried many nginx config and different ip / ports with no success.
If someone has a working example, I'm curious 😄
Thanks
SSL I'm not sure about.
Unity Transport has built in support for WebSocket though.
Which is intended for WebGL builds.
Yes sorry, I'm using web socket indeed, so wss I suppose, what I mean is that it doesn't work since I added a certificate on my website
Ah, makes sense.
Does anyone remember spatialOS? What happened to that?
Someone (not naming names) sued them and that kinda soured the relationship. They are still doing stuff but mostly bespoke or UE-based
Hi, just learning about the new netcode (I've done very old netcode) and trying to understand why code is set out like it is in Unity's example here:
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/goldenpath_series/goldenpath_one/#adding-basic-movement-to-the-player-object
Specifically, why do we run Update() if we are the server - we already updated our position in the Move() method?
{
transform.position = Position.Value;
}```
Tutorial that explains adding scripts to objects, editor modes (Host Server and Client), basic player movement and basic RPC use.
it looks like Move only gets called once on spawn, so Update is keeping the object's position in sync with the network var as it changes? the RPC only changes the value of the network var, not the actual transform
I see, since non-server objects need to sync position on the server. Thanks
You can use the regular scene manager to load non networked scenes if you want
are you supposed to use a Network rigidbody2d and network transform or just one or the other?
also is there a client network rigidbody? As in similar to the client network transform?
There are many different ways to manage physics simulation in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.
thx Dylan!
dylan idk if u work at unity but thought you would find it cool that i talked to wilhelm of landfall games and he said hes moved from photon to NGO 👀
I was hosting a server on multiplay which is using Mirror's simple web transport. While hosting do i need to specify the Websocket transport is being used? Because i read somewhere that UDP is the default.
I am getting into an issue with hosting the dedicated server on Unity Game Hosting service.
I am building a multiplayer car racing game on a dedicated server architecture. I have made a custom network manager and am using Simple web transport,
when i built the server locally and tested the game it works fine. But after hosting on Unity Game Service the client is not able to connect.
Unity Server Hosting requires linux build.
What I checked after hosting: Checked correct ip address and port. Tried with enabling and disabling "Client wss"
Thanks a lot in advance
Does anyone know a good place to learn how to do peer to peer hosting with also using a server running on linux as a middleman?
so then the player doesn't have to do port forwarding but one person still does logic
after a few months still hoping the bug would be fixed where anytime defaultnetworkprefablist gets updated the networkconfig is mismatched. Have to restart unity every time
Whats a good solution for making a multiplayer project using Hololens 2? I have been trying to use Mirror Networking but Hololens is not cooperating with it at all.
Hey guys, did anyone had trouble with connecting to unity relay in the past few days ?
Some playtesters of my game had an error 400 bad request, I never had trouble like that before so i'm wondering if anyone had similar issues ?
Could I get some help regarding the mirror networking issue that I am facing? I am at the stage of having started a server through my Hololens (UWP build) but its not being detected by my PC's build (Windows build).
I have made a custom script from NetworkDiscoveryHUD and I have set the Network Address to localhost and left the broadcast address empty.
I have managed to see the IP address of my Hololens in the UWP build but when it comes to detecting it on the PC its not being detected.
I have fixed the problem.
Hello in netcode for gameobjects, why does the player disconnect each time I start the client? I am using the multiplayer play mode tools btw. And this happens randomly, sometimes it works sometimes it doesn't. What could be the cause?
This is the logs from the editor(bottom) and a player from multiplayer play mode(top)...the two errors are these:
Screen position out of view frustum (screen pos -nan(ind), -nan(ind)) (Camera rect 0 0 875 216)
UnityEngine.EventSystems.EventSystem:Update ()
This is usually caused by non english lanuage settings in the OS(Windows)
Anyways… I figured out a workaround. Activate more than 1 virtual players and do not allow the editor to be the first active player.
i got this error "PUN got region list. Going to ping minimum regions, based on this previous result summary: cae;52;asia,au,cae,eu,hk,in,jp,kr,ru,rue,sa,tr,uae,us,ussc,us"
i have a client network animator on the parent, each body part is individual. Every animation plays on host and client except for running? Any ideas?
Hi. I'm learning Netcode for GameObjects and having some trouble with jittering. My code rotates the local GameObject in the scene belonging to the player and synchonises it. However, the Client machines are slower/jittery. Almost like its fighting itself. The host machine rotates smoothly.
You should be using Anticipated Network Transform for this. The values you get from the Network Variables are going to be behind the local ones
Client anticipation is only relevant for games using a client-server topology.
I'm making a VR game and I want to know how I could use sync the players hands and not just it's body
Can I just add a network transform to anything I want synced? or is it only 1 per player.
Also another question. Does the server sync the object every second or just when the position or rotation has changed?
Check out the VR Multiplayer Template Yes. you can put a Network Transform on any Network Object or child of one. Transform data is only synced when it changes
Yea. They just announced a new mixed reality multiplayer template at the roadmap talk. I'm super excited about that too
Ooh That would be fun! Btw would you say adding a server as a middle man which all the players connect to, be hard to add?
I'm thinking of doing that so they can avoid doing port forwarding
This is what the relay service is for
does anybody knows how NetworkLists work? Im using Netcode and I want the client to be able to change a list
They work similar to NetworkVariable except they can not be initialized inline like variables can. See the example in the docs
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
thanks
i'm trying to instantiate an object locally , the information is sent correctly with the client rpc and everything works correctly BUT the instantiation method , what am i doing wrong
Are you seeing any error messages when you instantiate?
nope
normal objects with no network objects , supposed to be instantiated locally for every client
something i haven't mentioned sorry , the instantiation works only for the client that called the server rpc to call the client rpc , as if there's an if statement in the client rpc checking for the client id of whoever called the server rpc tho there isn't
because everything else in the client rpc works but the instantiation , the instantiation only works for the person who called the server rpc that called the client rpc
@honest moat much easier for us to help if you just send your code
📃 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.
gimme a sec
[ServerRpc(RequireOwnership = false)]
public void SendMessageServerRpc(string playerName, string message, int messageImportance)
{
SendMessageClientRpc(playerName, message, messageImportance);
}
[ClientRpc]
private void SendMessageClientRpc(string playerName, string message, int messageImportance)
{
if (message == "" || message == null)
{
return;
}
if (messageImportance == 0)
{
if (playerName == "")
{
GameObject _message = Instantiate(normalMessage, chatContent);
_message.transform.SetSiblingIndex(0);
_message.GetComponent<TextMeshProUGUI>().text = message;
PlayMessageSound(normalMessageClip);
}
else
{
GameObject _message = Instantiate(normalMessage, chatContent);
_message.transform.SetSiblingIndex(0);
_message.GetComponent<TextMeshProUGUI>().text = playerName + " : " + message;
PlayMessageSound(normalMessageClip);
Debug.Log(message);
}
}
else if (messageImportance == 1)
{
if (playerName == "")
{
GameObject _message = Instantiate(importantMessage, chatContent);
_message.transform.SetSiblingIndex(0);
_message.GetComponent<TextMeshProUGUI>().text = message;
PlayMessageSound(importantMessageClip);
}
else
{
GameObject _message = Instantiate(importantMessage, chatContent);
_message.transform.SetSiblingIndex(0);
_message.GetComponent<TextMeshProUGUI>().text = playerName + " : " + message;
PlayMessageSound(importantMessageClip);
}
}
}
i'm probably doing something wrong but i have no idea what it is
and the calls of SendMessageServerRpc?
the calls are in update , it calls for it with checking for an input
let me just send it
if (eventSystem.currentSelectedGameObject == textInput.gameObject)
{
controller.inMenu = true;
if (Input.GetKeyDown(KeyCode.Return))
{
SendMessageServerRpc(LobbyScript.instance.playerName, textInput.text, 0);
textInput.text = "";
textInput.ReleaseSelection();
controller.inMenu = false;
}
}
else
{
controller.inMenu = false;
if (Input.GetKeyDown(KeyCode.Return))
{
textInput.Select();
}
}
the problem isn't with calling the rpc , because it does call for it successfully and PlayMessageSound() does actually play for all clients
the only function that doesn't happen is the instantiation for the clients other than the client that called the server rpc for some reason
I'd just start throwing some Debug.Log() calls in there. Because if it truly wasn't working, _message would be null and you'd be getting errors
i did do that , and i logged the message string and it did deliver the message correctly just not instantiating the game object for some reason
and also the PlayMessageSound() function works correctly
so i'm really confused
not the message string, _message the GameObject
oh alright i'll try that
GameObject _message = Instantiate(importantMessage, chatContent);
_message.transform.SetSiblingIndex(0);
_message.GetComponent<TextMeshProUGUI>().text = playerName + " : " + message;
all of these would be null if that instantiation wasn't working
yeah but it's not throwing any errors for some reason
i thought it was some weird netcode restriction
That's why I'm saying to log the values/results surrounding these things, will probably lead you to the answer
i'll try to do that
Yea, this isn't a Netcode issue. Are you sure those message objects are not getting instantiated? It seems those other clients might not be getting the message prefabs set properly
i just checked , it is not a netcode problem , for some reason the object instantiated is getting parented to another object even tho the instantiation parent was set to a specific parent , sorry for the inconvenience
everything is working as intended on netcode's part
Using unity's NetworkObjectPool Unity.BossRoom.Infrastructure I want to add a Empty NetworkObject Gameobject and set it to DoNotDestroy for the networkObjects to go back to after despawning so if I switch scenes they all despawn and go back into a holder is this possible?
I don't think this is necessary. The network object pool is already a Singleton so it will persist between scene loads. The prefab handler will despawn and return the objects to the pool when the scene unloads
Hi, I am making a unity card game 1v1 , I have server that handle all the things , but I don’t know how to handle the game itself . When the player finds a match I don’t want the server to handle the game It’s too much for the server I think , i think the server needs to redirect to game room server that handle the match itself how can i make it? Any tips?
For a card game, the load on the server is not that much. The player plays theirs cards and sends that to the server. The e server will resolve combat and/or card effects. The server will send the new board state to all clients. Finally the clients will update their UI with the new game state. Animations and particle effects will hide any latency
@elfin token !collab
: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
Even if 100 games runs on the server ?
You'll need to profile to see what the resource limits of you server hardware is. But it's possible
I thought about the main server will redirect the player the another server room
But I don’t know how can I do this
That is very complex thing to pull off. spinning up a new server and passing clients over to it is non trivial
If my game is completely client auth am I benefiting at all from anticipated transform?
Unlikely.
However, features such as prediction or anticipation help solve problems when multiple players interact with the same object, since you can't just give "ownership" to one client and not the other, the system falls apart.
You should code the server in a pure console c# app.
That's what card games do. They don't run a game engine in the server-side.
That way, a single server can handle thousands of players and matches.
That's like saying he should just make his own game engine at that point
No. A card game is pretty simple.
This is something that is done regularly, nothing particularly hard about it.
Yes, for a beginner, it will be difficult.
However, I am just presenting the proper way of how to do such a game in a way that will make it successful.
Running a Unity server for each 1v1 game will cost way too much resources, when a single pure c# app can already do it at orders of magnitude more efficiency.
You can use an RUDP lib like LiteNetLib or ENET, or even a msging lib to do it.
It's not really that hard. As I said, a card game does not even have physics.
You actually can't. Anticipated Network Transform is fully server authoritative.
In the first version of my game I did the server with python flask
Python is a slow language.
With C# and modern .NET, it's hundreds of times faster than Python.
It was very difficult and stupid decision for unity , so I switched to riptide
Is Riptide multi-threaded?
Multithreaded?
It's a standalone C# library.
Yes sorry
I think if I will build the game server on Linux and without render at all it should be good
I just don’t want to change from riptide to pure c#
Riptide is pure C#.
It has no dependency on Unity.
So it will be fast enough?
I can't tell you that, since I never used it.
But what I have used is LiteNetLib.
It's fast, and should do what you need.
Thank you so much 🙏
Np.
The way I might attempt this, in LiteNetLib, is by spawning hundreds of servers in a single process.
Each server can handle like 1000 matches, you can find the proper number when testing.
Spawn a single thread for each server. Each thread will handle the 1000 matches in a completely isolated manner from the other servers.
Use a very low send rate like 1HZ or 5HZ. Depends on how fast-paced your card game is.
Note: what I mean by server is an abstract object in your app that represents a server. But all these servers will be in the same single process.
Basic multi-threading knowledge will be needed to do this. But it shouldn't be too hard.
You will be able to handle the entire player base of your game in a single process, if you want to.
This channel is for gameplay networking
If I spawn an object and set a network variable on it like so:
MyScript instance = Instantiate(myPrefab);
instance.myNetworkVar.Value = someValue;
instance.NetworkObject.SpawnWithOwnership(clientId, true);```
Is `someValue` guaranteed to be populated on the client during `OnNetworkSpawn` ?
That should work but the proper way would be to use OnSynchronize
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.
Oh this is perfect, probably exactly what I need/want. This would let me avoid the NetworkVariable entirely assuming the value never changes after the object is initialized, right?
Yep. that's exactly what this is for
Perfect, thank you!
Is there a way to change tickrate in NGO?
I see NetworkManager.NetworkConfig.TickRate is adjustable, but it causes clients to become mismatched in configuration. Are there any guides on synchronising this?
Make sure that you are changing the tick rate on all the clients as well as the server
hello
i am new to multiplayer stuff
wanted to ask some stuff
like what is the difference between dedicated server, server hosting, multiple server hosting and peer to peer connection
and how to take a start
I mean you can look those things up but:
dedicated server:
- a server you run all the time dedicated to hosting the game
server hosting: - a service that... runs servers for you
multiple server hosting - i don't really know what you mean by that.
peer to peer connection - P2P is when one of the player's local machine acts as the host for the game instead ofa dedicated server
How to get started would be:
- Pick a network framework
- Look up the documentation for it
- Follow their Getting Started guide
i have worked with unity transport before
so i have a pretty good idea how to send and recieve data from and to server
and how to host a server
but what is a dedicated server
I said that here
do we have to buy it?
A server that runs on its own machine
You either buy/rent from a service, or make your own
you buy it, or rent it, or use hardware you already own
like anything in life
ok lets suppose i created a dedicated server
i played many multiplayer games
people play in more than just 1 server
each server having its own team and players
while i am hosting only one 1
how does that work
or i am misunderstanding something?
You're mixing something up.
You just said there's more than one server, but that you're only hosting one.
so people actually pay for more than one server
i thought you can only host 1 server for a game
how does it work?
You use software to determine what server to connect players to. Depending on the game that could be for matchmaking reasons, server load reasons, etc.
how much can it cost?
i mean if i buy 50 servers
There's no one size fits all answer to that.
how much can an estimate be?
10k$
i have one last question
can we host more than 1 dedicated server on a single machine
Most of the time, yes. Depending on the game and the machine.
is it possible that a person plays the game we make
and we allow him to create a dedicated server on his machine and host it for other players to join?
I mean, yes. But by definition that wouldn't be a dedicated server as the sole purpose of the machine isn't to be a game server for people to connect to and can be shut off whenever the user feels like it.
can a machine as for example i have a good pc with rtx 4090 and a better cpu
how many dedicated servers i can host on my single machine
considering my pc works all the time
and never shuts off
and how does ping work?
That will totally depend on your game. A card game would take less resources than a FPS shooter
Ping is the network latency between the server and clients
10 is out of question if it is a fps shooter
how is it calculated
i have my internet speed 80 mb/s
Ping is literally built into the internet. Its primarily a function of distance between to machines.
understood
thanks for the guide
Hi, I wonder is it okay to network player ammo count? Because I am thinking of putting in in a network list that store as a whole player data, I am worried if it takes lots of data to update the changes and the latency to receive a new data.
Ammo count would just be a single int. Or at most an int for each type of ammo. It's would be no different than any other inventory item.
I am leaving the lobby in a multiplayer game. There are 3 scenes. When it says leave the lobby in the 3rd scene, it sends the others to the 1st scene. Even if someone who is not the lobby owner clicks on it. mirror library
I don't believe so. It should be treated like the player object and will get respawned in the new scene
Hi I am using a dedicated server to send clientRpc noticing players that the scenes has done loading, the server has done instantiating players prefabs, and now it's sending clientRPC to let clients know that they can update the player list from a network object that each of they should have. I encountered this weird bug that I can't seem to find anywhere on the internet, and this log only showed up since I used Quantum Console. Does anyone know what they're talking about or how to solve this problem? Thank yall so much
"[Netcode] [Deferred OnSpawn] message was received for a trigger of type ClientRpcMessage associate with id (4), but the Network object was not received within the timeout period of 1 second(s)."
This is usually when then RPC is sent before the object has spawned on the client.
But you really should be using scene events for this anyways
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events/
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
I do use it and it is called on the dedicated server (I checked the engine log), just the client RPC never actually got called on any client.
Does anyone know if Meta OVR library works with Relay?
I don't know if this intended behavior by NGO - however a simple bandaid fix to your problem is just calling DontDestroyOnLoad(gameObject); whenever a scene gets loaded
network behaviors get respawned when the scene loads. The singleton might be destroying itself
If that object is in the scene being loaded, yea. The existing scene should not respawn objects
I think you want to turn off Active Scene Synchronization
Netcode for GameObjects Integrated Scene Management
Can anyone help me with photon throwing this same error at me no matter what i do? im doing this:
void Start()
{
Debug.Log("Started");
if (PV.IsMine)
{
Debug.Log("Creating Controller. . .");
CreateController();
}
else
{
Debug.Log("Somethings Wrong. . .");
}
}
void CreateController()
{
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PlayerController"),Vector3.zero,Quaternion.identity);
}
``` and i see it create the player for a fraction of a second and it disapears and throws the error. (this is Pun2 in photon)
the PhotonNetwork.Instantciate is whats throwing the error
You may need to space the calls out a bit.
You have an entire scene for a dropped item?
Loading scenes is computationally expensive. Loading 3 all in the same frame might not be a good idea.
i don't think that's a reason NGO should stop working though 🤔
there's an OnSceneEvent event you can subscribe to, maybe do that and log which events you're getting on the client, that should give you some more info to work with
LoadScene() is already async which probably the problem. Your drop item scene is finishing first then the MainGameScene loads on top and overwrites it
Hey Im having some issues, I think my client doesnt connect properly, because it only spawns one Default Player prefab, and once one has been spawned, none ever spawn after. Does anyone know why this happens? Or is this intended behaviour? If I didnt misunderstand it should spawn one instance for every player, right? Restarting unity fixed it, Id still love to have any idea of what was going on if anyone knows anything?
How were your clients connecting? What're you using to test?
Im using ParrelSync to have 2 instances of unity up, but I also tried a build to an editor. Theyre connecting with the Start Host/Client buttons on the Network manager (Or a method that calls NetworkManager.Singleton.Start...()
Some additional info:
I tried setting up a new scene and used a different object as player prefab, it didnt work - I restarted unity, and that different test scene worked.
Then I went back to the main scene, looked if it worked, it didnt, so I restarted unity again, and then it worked.
I have even more info and I personally dont understand what was going on
The prefab in the main scene had a component that basically made it a singleton, so ofc new instances get deleted immediately, why didnt I catch it? I disabled the components so didnt bother to look into the code on them, somehow it still executed far enough to enforce the singleton.
Now the real kicker is the test scene tho, in that scene, as I mentioned, was another prefab used, and that had no singleton on it, yet, it destroyed any 2nd instance immediately. I understand my mistake up until the singleton, but I dont understand:
- why did it execute when disabled component
- why did it delete on a different scene
- why did it stop executing after unity restart
ParrelSync can be finicky when making changes and switching scenes. Stuff just gets out of sync between the clones sometimes. Probably why a restart fixed things.
Then why did it behave the same in a build?
Or, at least I think it did, I only properly logged half of the testing there obviously
You can use SceneEvent.AsyncOperation https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events/#sceneevent-properties
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
can anyone help me with this
You might have better luck on the Photon discord. But make sure that only the Host is trying to instantiate the player object.
Oh ok, i didnt know there was one. thanks
so far so good gang?
I'm trying to create a lobby, within it
store the RoomCode, HostID, and each player that joins' name
public async void CreateLobby(string lobbyName = "Lobby")
{
_hostNameText.text = SecurePlayerPrefs.GetString("_displayName", "");
try
{
int maxPlayers = 2;
CreateLobbyOptions options = new();
options.IsPrivate = false;
Allocation relayAllocation = await RelayService.Instance.CreateAllocationAsync(2);
string relayJoinCode = await RelayService.Instance.GetJoinCodeAsync(relayAllocation.AllocationId);
options.Data = new()
{
{
"RelayCode", new DataObject(
visibility: DataObject.VisibilityOptions.Public,
value: relayJoinCode)
}
};
options.Player = new Player(id: AuthenticationManager.Instance.PlayerID(), data: new()
{
{
"PlayerName", new PlayerDataObject(
visibility: PlayerDataObject.VisibilityOptions.Public,
value: AuthenticationManager.Instance.PlayerName())
}
});
Lobby lobby = await Lobbies.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options);
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new(relayAllocation, "dtls"));
NetworkManager.Singleton.StartHost();
}
catch (LobbyServiceException e)
{
Debug.LogError(e);
}
}```
is this good?
do you have the link to the discord server because i cant find it anywhere
We, the Photon Team (sometimes referred to as Photonians :), are dedicated to help you.
If you've got questions or your app doesn't work but you reall
ty
kk
I don't know if this is okay, I would like some help
I want to create a lobby, where it will show both players name
The Host and Guest, also what character they have selected
and when both players are ready, they will be transported to the game scene. (It's a cards game, like hearthstone pretty much)
Should I start the relay allocation like I'm doing? I'm creating the relay allocation along with the lobby, in the same function
public async void CreateLobby(string lobbyName = "Lobby")
{
_hostNameText.text = SecurePlayerPrefs.GetString("_displayName", "");
try
{
int maxPlayers = 2;
CreateLobbyOptions options = new();
options.IsPrivate = false;
Allocation relayAllocation = await RelayService.Instance.CreateAllocationAsync(2);
string relayJoinCode = await RelayService.Instance.GetJoinCodeAsync(relayAllocation.AllocationId);
options.Data = new()
{
{
"RelayCode", new DataObject(
visibility: DataObject.VisibilityOptions.Public,
value: relayJoinCode)
}
};
options.Player = new Player(id: AuthenticationManager.Instance.PlayerID(), data: new()
{
{
"PlayerName", new PlayerDataObject(
visibility: PlayerDataObject.VisibilityOptions.Public,
value: AuthenticationManager.Instance.PlayerName())
}
});
Lobby lobby = await Lobbies.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options);
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new(relayAllocation, "dtls"));
NetworkManager.Singleton.StartHost();
}
catch (LobbyServiceException e)
{
Debug.LogError(e);
}
}```
I'm sorry but what is that background lmao
I've started using Multiplayer Sessions https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual
But that way works too
multiplayer sessions huh
hmm I ... I would love to use it xD
it took me so much to get this far with what I'm doing but
100% willing to switch if it's better, and also get help
thanks, I hate it
same
It does what you're doing in like 5 lines of code.
But it's for Unity 6
yup, am using that
XD?
any... guide on that?
It's all combined into one API
When you install the package, you'll need to remove Relay and Lobby
on it, dad
There is also a neat Widgets package they showed at Unite. It has a bunch of prebuilt UI prefabs for multiplayer stuff
oh yes! I did see that
it's the first Unite I watch
Unity 6 is coming in hot
oh okay
should I change something there? - Inspector/Network Manager or UnityTransport
so that's literally all I need? XDDDDDDDDDDDD
Yea, basically. You can store player info in session.CurrentPlayer I think.
One of the widgets is a session/lobby browser
Checking that out
btw this is cool, but what if I get an error?
I call my create lobby from another script
is there a way I can do
{
}
else
{
}```
as well as for joining them
If (Lobby found with room code)
{
if (Room is not full)
{
SwitchToLobbyRoom();
}
else
{
Debug("Room found, but is full");
}
}
else
{
Debug ("No room found with this code");
}
You can use a try catch to get any session exceptions if something fails
in the script where I'm actually creating the sessions?
or I can do that outside, in my "UI Handler"
That might work. You would need to catch(SessionException e) if you want to full error message
what's below, will it wait for the try and catch first?
Yes
You can also use finally { } to run code after a try-catch block no matter what the result is
catch is never being called, I'm inputting no room code for testing
I assume it has to be called within the actual room creation huh
oh, so without the "finally"
what's below will not be called?
try
{
//Stuff
}
catch (Error)
{
Debug.Log(e);
}
//What's here will only be called if there is no error?```
No, it’ll still be called
👀
I’m your current case, I guess not. It ensures execution if your try or catch contains a return or break call. I also just find it cleaner to use regardless
You may have to await the call if you want it to catch
Just a guess
I’ve done something similar and have had it work
oh okay
that makes sense xD
Yea, I think thats right
getting somewhere with this, thanks guys c:
now I would like to have the names updated on Join...
but let's see
session.CurrentPlayer
I have the player name in PlayerPrefs
Later I will use actual authentication and have it stored somewhere else
But for now that's where I have it
Should I make 2 network variables,
-HostName
-GuestName
And have them update onValueChange ?
Or there's a better approach for this
To update the Display Text of the host and guest
Either way is fine. Network variables or you can use session player properties and SaveCurrentPlayerData
I think I like that one
I can't find proper documentation on it tho
what I did found is this (Don't know how to use it tho)
🔥
found it
xD I wish... documentation was more rich...
I read this and it just helps me know it exists, but I have to figure out how to use it
which, I guess it's fine, cause it's still in development but 🤮 old documentation is kinda the same
how tho?
this?
I can't figure it out... xD I'll go to sleep and try again tomorrow
Session Player Properties
I'm not understanding what your issue is. Just show a loading screen until you receive OnLoadEventCompleted and then hide it.
@restive arch you would use this to make a loading bar. Otherwise, you can just implement what I described above.
^ interesting
hey guys I'm struggling with something
whenever ya'll get the chance
I need help to create player properties, in this case the players' names
I haven’t really worked with Sessions, just Lobby on its own - but I don’t think you want to store the player name in the Session.
ah fair enough
in the session options, true
When using lobby you would store the name in Player.Data, not Lobby.Data.
I’m assuming the same thing applies here
Session properties are pretty much identical to Lobby Data
Yeah. Shouldn’t be a problem. If you’re loading the game scene first and then the additive scenes, just unsubscribe or set a flag after the first event is received.
What's in these additive scenes?
Just my two cents, but I think you're overusing scenes a bit. Stuff like menu, inventory, etc. are usually UI based and can just be handled inside of a prefab.
There's not really anything wrong with using additive scenes for some of these things, but I think it's just complicating how you're having to network things.
Premature optimization is the devil. I think it's always best to get things functioning in a simple form, and them expand/polish from there.
And there's plenty of ways to sort GameObjects under a single scene hierarchy. Not that I would ever let the cleanliness of my hierarchy influence development decisions, but.. yeah.
The loading scene does not need to be a scene at all. Just instantiate a full screen prefab
For networked scene you should be listening for the scene events to load your additive scenes in order
I would just put everything in these additive scenes under one parent GameObject. Disabled by default and enabled whenever all additive scenes are loaded.
Why not? 😁
Not the scene itself
Everything in it
It would be done locally.
Normally, you'll want to wait until OnNetworkSpawn() before changing network variables.
Anyone have an example of fetching lobbies using Facepunch.Steamworks?
I can create lobbies but can't retrieve them with a filter
class x : NetworkBehaviour
{
public NetworkVariable<struct1> s1= new NetworkVariable<PlayerData>(new PlayerData(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
// somewhere..
s1.OnValueChanged += (PlayerData PreviousValue, PlayerData NewValue) =>
{
// Code
};
}
public struct struct1
{
public struct2 s2;
public void ChangeS2(struct2 _s2){s2 = _s2;}
}```
How can I make it so that `s1.OnValueChanged` gets called when I change the s2 inside s1?
sup gang, ^ I also have a question, also about suscribing to an Action/Event
in here, when a player joins a room I have them suscribe to "OnPlayerConnected"
which I also call when creating the lobby
all it does for now is to get the player name and set it to a Text Mesh Pro
but I get this error
they will only show their own names btw
Thread to not flil this with my code xD
is there anything visible I'm doing wrong?
Why does RelayService.Instance.GetJoinCodeAsync not work? It barely connects, most of the time it just gets stuck and returns nothing. This my code for joining as well as creating:
public override async void CreateLobby()
{
try
{
await InitializeUnityServicesAndSignInAnon().WithTimeout(1000 * timeoutInSeconds);
var allocation = await RelayService.Instance.CreateAllocationAsync(MultiplayerManager.LobbyOptions.GetValue<int>("MaxPlayers"))
.WithTimeout(1000 * timeoutInSeconds);
var joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId).WithTimeout(1000 * timeoutInSeconds);
if (!_transportManager.Host(allocation))
{
CallCreateLobbyFailed("Failed to host the relay server.");
return;
}
Debug.Log($"Join code: {joinCode}");
}
catch (Exception e)
{
CallCreateLobbyFailed(e.Message);
}
}
public override async void JoinLobby()
{
try
{
await InitializeUnityServicesAndSignInAnon().WithTimeout(1000 * timeoutInSeconds);
var allocation = await RelayService.Instance.JoinAllocationAsync(JoinLobbyOptions.GetValue("JoinCode"))
.WithTimeout(1000 * timeoutInSeconds);
if (!_transportManager.Join(allocation))
{
CallJoinLobbyFailed("Failed to join the relay server.");
}
}
catch (Exception e)
{
CallJoinLobbyFailed(e.Message);
}
}
Sometimes it throws the exception that the code isn't found while the relay server is created. After some searching on google, i am assuming it is a bug with relay if you test out 2 clients on the same device/network it bugs out relay services. However this is my guess.
Anonymous Unity Authentication on the same device does not work without some extra consideration.
Ahhh, however isnt it weird? That the problems occurswhen calling joinalloc and not when calling signinanon
The authentication should only be an issue if you're using editor clones, IIRC
Thats nicer to know since i was using to parrelsync to test
Alr thanks man, i know atleast there is nothing wrong with my code
One of their samples shows how to set up profiles and assign it to ParrellSync clones to avoid conflicts with anonymous authentication on the same device
Don't remember which one it is off the top of my head
Which events?
You should always unsubscribe when a component is disabled or destroyed in order to prevent memory leaks
Not really resource heavy at all. Although you always want to unsubscribe from events when possible.
Outside of memory leaks, it can actually cause other unintended effects. Especially if you're going in and out of the same scenes within the same app session.
[Netcode] NetworkBehaviour index 29440 was out of bounds for PlayerStand-in(Clone). NetworkBehaviours must be the same, and in the same order, between server and client.
UnityEngine.Debug:LogError (object)```
I get this error when connecting to my server, "Player stand-in" is my Default Player Prefab, I have no idea what it is trying to tell me, what does it mean with index? The NetworkObjectId? That one is not 29440, but the number it is supposed to be. Why does this happen and how do I fix it?
are you destroying any components on your player object?
No Im not
Does it have any singletons that might be destroying itself?
No it doesnt, the object spawns with every component it should have attached and active
something is causing a mismatch between what is spawned and what's in the network prefab list
adding components at runtime could also cause this
The issue would appear to be a class reference in my INetworkSerializable implementing struct, when I remove it, the error disappears, that class reference does not get serialized (on purpose, not like it could lmao) because it is only needed locally to build the serializable object from (Its a ScriptableObject reference and I identify which ScriptableObject it is over a seperate struct). When I remove that reference the error disappears, but why does it matter in the first place since it never tries to get serialized and should only exist locally, anywhere else it can, and should, just be null
If it only needed locally, then it shouldn't be implementing INetworkSerializable
Not the whole struct, just a field of the struct is local
I'm still not following. If a single field within a struct that implements INetworkSerializable is only to be used locally, why is it in that struct at all?
Best to keep things like that separated. Especially if it's causing errors.
Hi. I'm trying to keep track of the Player Count when Players join and leave. On the client, playerCount.Value is correct (2). On the Server, playerCount.OnValueChanged doesn't trigger, but i'm unsure why
Just a guess here but isnt server only local player when Server is actually Host? Standalone server shouldnt have a local player I believe, if my assumption is correct your code should work when starting as host only
Thanks for pointing that out. I am using Host (client 1) and Client (client 2). It seems the issue is with the RPC side. I added more logs. The Before Value debug log prints 0 :/
!code
📃 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.
You shouldnt need an RPC since you already use NetworkVariable
if you just put it into if(IsServer) it should have the same effect but not need a remote call
I suspect I'm misinterpreting how NetworkVariables work. Am I right in thinking a NetworkVariable is synced only to the owning Player Object on every client and not every Player Object on every client?
No, every player gets the updated values.
Only the server or owner can write to the variable. But everyone has read access by default
Every connected client will get the NetworkVariable updated. If you have a NetworkVariable on a Player object that represents Health and you set it to 50, all clients will get that NetworkVariable updated to 50 on their copy of that Player object. Other Player objects will not get their Health NetworkVariable set to 50 unless you set it.
With photon. I can set the multiplayer to only work when the game was launched using the meta store. Does unity relay have this same authentication?
The null value here is NetworkList<T>.m_NetworkManager I cannot access this variable in any to me known way, why is it null? Why doesnt it know my NetworkManager?
Im trying to use the Add() method of the NetWorkList, containing currently just an int for testing purposes. I initialized the list, it is not null, just has 0 entries
How are you initializing?
private NetworkList<int> _ints;
public NetworkList<int> ints
{
get
{
if(_ints == null) _ints = new NetworkList<int>();
return _ints;
}
set
{
_ints = value;
}
}
cant just do _ints = new... becasue of CS 8773
NetworkList has to be initialized in Awake()
There is no awake this struct doesnt derive from MB
Its just for storing data
If I cant use NetworkList like that then how DO I store a collection?
NetworkBehaviour inherits from MonoBehaviour, so at some point during your use of NetworkList, you will be able to initialize it in Awake()
The only thing I use is INetworkSerializable
per the docs:
private NetworkList<AreaWeaponBooster> TeamAreaWeaponBoosters;
void Awake()
{
//NetworkList can't be initialized at declaration time like NetworkVariable. It must be initialized in Awake instead.
//If you do initialize at declaration, you will run into memory leak errors.
TeamAreaWeaponBoosters = new NetworkList<AreaWeaponBooster>();
}
I understand that. But you literally have to make use of it inside of a NetworkBehaviour, or you will never be able to use it.
I understand the definition doesn't lie within a NetworkBehaviour. That's not what I'm talking about.
Okay so I initialize the field in the class in which I use the struct, are you sure I do it on Awake and not OnNetworkSpawn?
As I said - per the docs:
and I would avoid doing any of the get, set stuff you're doing - may be causing issues as well.
Im only doing it because of CS8773
Ill try with awake 5 min
this
Oh - I didn't even realize what you were doing.
Why are you putting a NetworkList inside of a struct?
Because I need a networkable collection
Its the struct storing all the player data, such as gear, so I need a collection of the owned gear
Nesting synced types is often unsupported, if not really messy to do.
Netcode for GameObjects has built-in serialization code for arrays of C# value-type primitives, like int], and [Unity primitive types. Any arrays of types that aren't handled by the built-in serialization code, such as string], need to be handled using a container class or structure that implements the [INetworkSerializable interface.
There's a handful of options for collections
I did try NativeArray
It synchronized that A change happened, but not what the change was
I honestly dont know what it did but the data was incorrect
The other recommendation I would make is to just make the owned gear its own NetworkList
I understand you want to wrap everything in your PlayerData struct, but sometimes that's more trouble than it is worth.
Ill try NativeArray/list again and come back with the precise issue Im having
For the NetworkList:
I cant initialize it in Awake because Awake doesnt have IsOwner set, so it will certainly try to set ones it doesnt own, even if it doesnt succeed, I dont think I want the possibility of that in my code since it would just make everyone start over when a new player connects if an update ever makes it succeed
For the NativeList - well, image attached
I am now trying to use the StringContainer example with an integer and see if that works
I am now trying to use the StringContainer example with an integer and see if that works
Even if it does Id much prefer a List since I obviously dont know the required array size for how much equipment my player owns
I cant initialize it in Awake because Awake doesnt have IsOwner set, so it will certainly try to set ones it doesnt own, even if it doesnt succeed, I dont think I want the possibility of that in my code since it would just make everyone start over when a new player connects
This would not be an issue.
A new player connecting would initialize in Awake() and get the most up to date value after OnNetworkSpawn()
Trying to get my players names shown in the Lobby Room - Unity 6 Multiplayer
A new player connecting would initialize
can anyone help me with this error i cant find or fix with photon's pun2? the error: Got DisconnectMessage. Code: 104 Msg: "InvalidEventCode". Debug Info: {}. the script I believe is causing this is:
who can help me. i create a linux server unity project. i run it on linux. i need listen its profiler on Public network. i donot know how to Specify listen profiler port number. (image cannot use)
./TestLinuxServerProfilerBuild.x86_64 -profiler-port 55360 (this cannot listen)
^ well, sorry I leave this message after yours is attended
what the heck... 😦
I have this being called when players press the ready button
Thread to not spam ~
but it's giving me a null reference error, which I find weird
I already am initializing both network variables btw, not sure if that's relevant or necessary
Not necessarily multiplayer, but probably best place to ask:
Trying to determine general network connectivity, what's best practice? NetworkReachability sure. But should a UnityWebRequest be used to just ping say google.com (or 8.8.8.8) or would it best best to use Unity.CoreModule.Ping pinging 8.8.8.8 instead?
Or should I roll out a custom Pinging solution such as this?
https://discussions.unity.com/t/how-to-check-internet-connection-in-an-app/615779/47
or https://discussions.unity.com/t/how-to-check-internet-connection-in-an-app/615779/34
i would say you should probably ping whatever server it is you're planning to connect to instead 😄 so many factors can go wrong in networking, being able to reach google doesn't guarantee anything else will necessarily work
that's true but ironically I am using Google, specifically their Firebase Authentication service but I don't exactly know what endpoint I should ping and the Unity Ping API requires a raw IP address with no DNS allowed so... yeah... 8.8.8.8 is just easiest.
Unkess there is a specific endpoint you are trying to reach I think just using NetworkReachability would be easiest
Doesn't account for airport hotspots that require to log in or agree to w/e
ultimately there's not really a way to say for certain whether it'll work without trying the request, there's no guarantee being able to ping a DNS server means a HTTP request will go through successfully either, there's a lot of steps in between there
you can put a lot of work into trying to guess whether it's going to work or not and the user might still end up getting an error, so a lot of the time NetworkReachability is enough information
Update: Unity's Ping API might not have a timeout which is annoying... Have to roll out my own which means I might as well have used the .NET one.
what about me? 😦
am I doing something wrong wrong with me NetworkVariable<bool>?
nvm I just realized I got a reply xD
Is there some one good at netcode and facepunch ? I need help!!
I would say just post your question and then people can judge if they're able to answer...
Thanks Maeve!
I have a working prototype game, I used netcode and tested multilayer locally. Now I want the game to run online through steam server (space war). I referred few tutorials, which introduced facepunch transport for netcode. The problem is I couldn't get a client connect to the same lobby as the host.
Hello, I'm learning RPC's and having some trouble. I'm wanting the server to send a RPC to clients, updating an int. My client is getting the value, but on the wrong Object. Here is my code:
public class PlayerNetwork : NetworkBehaviour
{
public int playerCounter = 0;
public override void OnNetworkSpawn()
{
if (!IsOwner)
return;
if (IsServer)
{
NetworkManager.Singleton.OnClientConnectedCallback += (ulong value) =>
{
playerCounter += 1;
FileManager.Log(LogType.Server, $"Server :: Connected Players Increased :: {playerCounter}{Environment.NewLine}", true);
UpdatePlayerCountRPC(playerCounter);
};
}
}
[Rpc(SendTo.NotServer)]
void UpdatePlayerCountRPC(int value)
{
Debug.Log($"{this.gameObject.name}: Test Client RPC Recieved from server. Owner? {IsOwner}, Value: {value}");
if (!IsOwner)
return;
playerCounter = value;
Debug.Log($"{this.gameObject.name}: Player Counter is now {playerCounter}");
}
}
Here is the result. As you can see, Other Player (Server) gets the message, and not Our Player (Client)
but on the wrong Object
can you expand on this?
You're calling UpdatePlayerCountRPC inside of an IsServer block. Meaning the object receving is always going to be the Host Player Object.
If you wish to see which Player is connecting, it tells you as a parameter of: NetworkManager.Singleton.OnClientConnectedCallback
with a ulong ID
Ahh. I don't understand why that is the case. I thought SendTo.NotServer dictated who received the message?
It does. You're mixing up connections with instances of objects.
Anyone have any good examples of Server Auth movement for FPS games?
For NGO?
Yeah for NGO
Check out the Anticipation Sample. It can be adapted for FPS games as well.
does that mean that we can now make in-browser multiplayer games?
Have been able to for a bit now, IIRC.
so it's official support now right? No need to combine some stuff anymore?
I guess so! Pretty sure you had to use a different Transport in the past.
Are you sure? issue with FPS is it needs to seem responsive on the clients side.
That's what Anticipation helps with.
Yea, it's been officially supported for some time now. Web browsers can't be the server or host so you will need to use a dedicated server or relay service.
why you can't be a host?
Can you have a host if you use relay service?
Its a limitation of all web browsers
but if you use relay service you can?
Yea. with the relay service you can
can anyone help me with PhotonNetwork.LoadLevel() not working? my error is: Invalid scene name (empty string) and invalid build index -1. When im trying to load it with a buildindex of 1, someone told me to ask here so here i am
How is onSceneLoaded getting called? Seems like it's getting passed an invalid scene.
this method here (the scene does exist i checked)
You might want ask in the Photon discord. Is Photon LoadScene looking for a string name instead of index?
nope it wants a build index
ill go ask in photon discord server
can you log or debug to check what's in the scene object you get by calling GetSceneByBuildIndex? it seems like the only way the index could be invalid later is if it's not finding it there
i have it printint that and it prints: "loaded level 1"
up here i have it print the buildindex
where exactly are you seeing that error? can you paste the whole thing?
hey so I'm thinking about how to reduce network traffic for my game. Currently I know i have vector3 pos, vector3 rot, and int actions, however I'm thinking I can fit this all into a single int, or definitely 8 bytes. Question: Regarding this compression, I would lose most of the decimal precision. As long as I scale my game properly, this shouldn't be a big deal, right? Also, is it bad to have all tick data in a single int or long, or does it not matter? Thanks
does anyone know how to get localip address for webgl?
i tried using DNS. method.. its working in editor but not working when i imported in webgl
Yes, as long as it works, it's good. Networking is a complex problem and no two games do everything exactly the same. A general rule of thumb though is definitely what you are suggesting—lop off every single extra byte that you can. Also, you probably don't need a long, even at a 60hz server tickrate, it would take over a year to exceed the int.MaxValue limit.
depending on the type of game, you might additionally need to use other strategies to reduce network traffic (network prioritization, culling, etc), but it all depends
ah the int in (vector3 , vector3, int) isn't for tick , its meant to represent the set of actions a client executed this tick (used in combination with position and rotation for server authorization). I'll look into network prioritization adn culling fs
Oh sorry, I see what you are saying, yeah nothing wrong with packing it all into an int / long
at the end of the day, it's all just bytes
It's really fun to do imo
yeah bit-level packing is fun to do, the optimizations are satisfying
I just learned that I could be paying upwards of 10,000 on servers so this takes my mind off it lmao
funny how in multiplayer the best and worst case scenario are the same
I wont be paying this anytime soon I was just calcing how much x players would cost me
well, for most server solutions, the less bandwidth, the better. Usually there aren't flat rates but rather a dynamic cost based on bandwidth. Additionally there is often auto-scaling of servers so servers not in use will be pooled for other projects to use, and it won't cost you anything even if you are "reserving" it (maybe a really low minimum rate in some cases)
Yeah its good that you dont pay for what you dont use, but its scary to think of the possibilty of a player spike that doesn't lead to any increase in revenue.
I feel like optimizing bandwidth is very important for performance, but doesn't actually impact the cost of servers much? I always though cpu and ram was the main expense
The mindset I usually take is that too many players is usually a good problem to have to worry about, but I suppose if you aren't earning anything then it would be the opposite.
Also, well, yes all performance metrics matter but hard to generalize because it depends on the details of the game. I think yes CPU / ram matter most but computers are pretty fast and for most cases you don't need that much unless you are working on some huge scale game: tons of interactivity (physics, many server-controlled enemies, etc.), or something as responsive as modern AAA games.
OR if your game is just very unoptimized performance-wise
i see
yeah thats a good minset and the objectively correct one, just sucks that there's an element of risk to it but thats the genre in general
Is there any YT videos going over how to set up SeverAuth Movement for FPS games using the anticipation system in the newer versions of NGO?
Anticipation is relatively new, so probably not. The sample is going to be your best bet.
Check out the Player Movement script from the Anticipation Sample. The basic idea is that you move locally then send a RPC to server. The server will also move the player and send its update transform back to the client. Ideally the server transform and the local transform will be the same. If not then you can use OnReanticipate() to reconcile/smooth.
A collection of smaller Bitesize samples to educate in isolation features of Netcode for GameObjects and related technologies. - Unity-Technologies/com.unity.multiplayer.samples.bitesize
Hi, guys. I animated my 3d character and it is synced online (pun )just fine, except one thing. My melee sword attack is not sync consistently. Sometimes (1 from 10) it is missing. The animation works local 100% but sometimes just not syncing. And concerns only melee attack. Any ideas?
Only thing that comes to mind is if you act on the animator using the SetTrigger on the local instance, not the networkanimator. All trigger sets should be done on the NetworkAnimator, maybe you don't do that in some part of your code?
He's using PUN, not NGO.
<@&502884371011731486> surely this Trolling and/or Spamming and/or Unsolicited Advertising?
!warn 751340700213313557 Don't spam the channel with whatever that is.
goodnewsjim has been warned.
Hello 🙂
Does anyone know vivox?
I know how to use "Speech Detected" but
is there a way to retrieve the audio energy (speech detected) of a VivoxParticipantTap?
I don't think you can get it directly from it the tap. There is a ParticipantAudioEnergyChanged event that you can listen for
when i run webgl build and start server using netcode for game objects, it gives error:
Exception: WebGL as a server is not supported by Unity Transport, outside the Editor.
I am using unity transport 2.3 and NGO 1.11, still getting the above error
A WebGL build can not be a server
Then if I want to make a web game then do I have to make the desktop build for the server and webgl build for client ?
You'd have to have a dedicated server that is not through WebGL or use Relay.
so a dedicated server can communicate through webgl clients ?
From what I know, yeah.
may i ask what did he say?
A rant about a supposed infinite multiplayer engine they developed from a literal schizophrenic who occasionally posts here during one of their episodes
they announced it would be possible to create a server instance sometime while improving unity6, but that's just on the roadmap for now. Until then the solution is to have a standalone server to facilitate communication between clients
In the editor you can do that now in Unity 6 with Multiplayer Play Mode. A standard PC build as host would work too with another webgl client. A dedicated server is not the only solution.
The async operation has to be on the client side for it to mean anything. Client will listen to their own OnSceneEvent and display loading screens accordingly
Right.
It should work as normal. just be sure to unsubscribe from the OnSceneEvent when the object is disabled or destroyed
Just need to make sure to check for IsOwner before subscribing
you need to unsubscribe eventually or every time you switch scenes it will get called duplicate times
I apologize if this is the wrong channel, but would it be a good idea to use you unity as a webhost?
How would Unity help you here? I would rather use a modern .NET runtime and ecosystem if possible.
sup gang
now that I have both players in my Session
they're in the lobby room
I would like to now, send them to another scene
where they're also "synchronized"
but before so, Instantiating 100 card gameobjects, maybe in a loading screen
what should I look for here? 😦
also, I would like to Remove the player from the lobby session when they leave
Because you can use unity to run game servers.
so, how should I manage my scenetransitions?
Sure, but the use cases for using Unity as a game server are more obvious than Unity as a webhost.
So you can't use unity as a webhost?
... you can use Unity as a webhost.
You would use NetworkSceneManager
Netcode for GameObjects Integrated Scene Management
can anyone help me with setting an objects parent with Pun? its not in the scene but it exists and im getting no errors,
i tried tagging the object and searching for it that way but it didnt work either
the path it prints is just /PlayerController
Are you instantiating during a scene switch? Attach a script that logs OnDestroy to see if it's being destroyed.
Hi. I recently began using the Unity Cloud to save some data. I was wondering if it was possible to make a system similar to the "Find My" feature on iPhones, but instead of trying to locate a device, two instances of an app logged into the same account could ping each other (e.g. a button is pressed on one and the other shows something).
You should be able to use use Cloud Code Triggers for something like this
Great! I will check that out. Thank you.
Hi.. Using 2021 LTS... how do you add "dedicated server windows support" module to existing engine install. In 2022 LTS, in the hub, Add modules is available for that version.. but it doesnt show up for unity 2021 LTS
and no sign of it in Package manager
Open the Hub.
Select Installs.
Find the Editor you want to add the components to.
Click the three dots to the right of the version label, then select Add Modules. ``` In latest hub.. there is gears. And of the 4 engines I have installed, only 2022LTS has add modules as described
Do i need to re-install the entire engine so I can choose to include the module?
Are you sure that module is available for 2021? Dedicated server profile is relatively new.
this is what it wants..
I havent fixed it yet, but Im pretty sure how to now.
The issue isnt just not seeing that module in the hub options.. the issue is NO add module option is there for any of my engines, accept for 2022lts.. I researched and it says the "add options" button, only appears if the editor was installed via the Hub.. They were initially.. but then i changed the Installation folder inside the hub.. Since then, i installed 2022LTS directly.. and I just 'added " the other engines in manually.. So, it appears I need to re-install 2021 LTS from the hub, to enable the 'add modules' option in the hub.
When i do a fresh 2021 LTS install, i will download hte build support with it..