#archived-networking
1 messages · Page 8 of 1
Well it's existed since '74 and it's still widely used so
Unity Services's status page provides information on the current status and incident history of Unity Services.
Is working now
stream.ReadPackedUInt(StreamCompressionModel.Default)
can`t readpackedint read the value 0 using 1 bit?
{
bool result = true;
if(value == 0)
{
result &= writer.WriteRawBits(0, 1);
}
else
{
value <<= 1;
value |= 1;
uint buffer;
do
{
buffer = value & 0x7F;
value >>= 7;
if (value > 0)
buffer |= 0x80;
writer.WriteRawBits(buffer, 8);
}
while (value > 0);
}
return result;
}
public static uint ReadVarUInt(this ref DataStreamReader reader)
{
uint value = reader.ReadRawBits(1);
if(value == 0)
{
return 0;
}
else
{
value = 0x0;
uint buffer;
int shift = 0;
buffer = reader.ReadRawBits(7);
buffer <<= 1;
value |= (buffer & 0x7F) << shift;
shift += 7;
while ((buffer & 0x80) > 0)
{
buffer = reader.ReadRawBits(8);
value |= (buffer & 0x7F) << shift;
shift += 7;
}
value >>= 1;
return value;
}
}
public static bool WriteVarInt(this ref DataStreamWriter writer, int value)
{
uint zigzag = (uint)((value << 1) ^ (value >> 31));
return WriteVarUInt(ref writer, zigzag);
}
public static int ReadVarInt(this ref DataStreamReader reader)
{
uint value = ReadVarUInt(ref reader);
return (int)((value >> 1) ^ (-(int)(value & 1)));
}```
i have created this and has much better compression than unity native (and much faster)
ReadPackedUInt(StreamCompressionModel.Default) is only good for really small numbers (like 1, 2, 3, 4, 5). More than this and it is wasteful
hey so right now im spawning something on the network and assigning its position right away, but in the client it shows the item spawning in the center of the world and then flying to the assigned position due to the latency. it works properly in the end but it looks terrible lol. is there a way to spawn something on the network with an assigned spawn position so this doesnt happen?
oh wait im dumb, i just had to set the position to the instance of the object before spawning it 😭😭😭
Anyone know how I can get around sending a Client RPC that isnt Serializable Values to the clients?
Essentially I Spawn a Loot Drop from a dying Enemy and Assign its Item from its loot table. Ofc it works server side but I don't know how to get said Data across to the clients.
public void SpawnLootDrops(ulong player)
{
GameObject loot = Instantiate(
_pickupObjectTemplate,
this.gameObject.transform.position,
Quaternion.identity
);
loot.GetComponent<NetworkObject>().SpawnWithOwnership(player);
Pickup itemPickup = loot.GetComponent<Pickup>();
itemPickup.item = _lootDrops[Random.Range(0, _lootDrops.Count)];
SetLootClientRpc(itemPickup, itemPickup.item);
itemPickup.SetSprite();
loot.GetComponent<Rigidbody2D>()
.AddForce(new Vector2(Random.Range(-5, 5), Random.Range(10, 15)), ForceMode2D.Impulse);
}
[ClientRpc]
private void SetLootClientRpc(Pickup itemPickup, Item item)
{
itemPickup.item = item;
itemPickup.SetSprite();
}
Bascially like this, yes I know the bottom method doesnt work. That's what I would like to get working
you can send networkobjects and networkbehaviours over the network (client/server rpcs) by using NetworkObjectReference or NetworkBehaviourReference. so if your Pickup class is a networkbehaviour you could send that, or send its network object and then get the Pickup component from it
apart from those two, you can only really send basic data types
Interesting, you have an example by chance ?
yea sure
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
Thank you!
I think im just stupid. I'm trying to wrap my head around how this will even help me though. I pass the reference of the Servers Object, but how am I going to be able to set the clients.
public void SpawnLootDrops(ulong player)
{
GameObject loot = Instantiate(
_pickupObjectTemplate,
this.gameObject.transform.position,
Quaternion.identity
);
Pickup itemPickup = loot.GetComponent<Pickup>();
lastSpawnedLootItem = itemPickup;
itemPickup.item = _lootDrops[Random.Range(0, _lootDrops.Count)];
NetworkObjectReference networkObjectReference = new NetworkObjectReference(loot);
SetLootClientRpc(networkObjectReference);
itemPickup.SetSprite();
loot.GetComponent<NetworkObject>().SpawnWithOwnership(player);
loot.GetComponent<Rigidbody2D>()
.AddForce(new Vector2(Random.Range(-5, 5), Random.Range(10, 15)), ForceMode2D.Impulse);
lastSpawnedLootItem = null;
}
[ClientRpc]
private void SetLootClientRpc(NetworkObjectReference lootReference)
{
if (lootReference.TryGet(out NetworkObject lootObject))
{
lastSpawnedLootItem = lootObject.GetComponent<Pickup>();
}
}```
Hey guys, Just getting started with NGO, trying to port a project over from Photon PUN... Just wondering, how would you go about setting and sharing player data?
For example, Let's say I want to display the player's Display Name, profile image etc... Where is the best place to store and retrieve that data during a multiplayer game?
I'm also using the Lobby service, where I can store such information in the Player's custom data... just not sure how to associate which players in the game are which in the lobby
should i send timestamp or frame number?
You can send data either using Network Variables are RPCs. You can store data in a Lobby in custom Player Data. When to use which depends on your game design
why not both?
i don't even know lol
Thanks... so in my game, the player joins the lobby, then automatically connects to the relay allocation (if it exists)... I guess what I want to achieve is a way to link each client in the game with their corresponding Player object in the lobby. So that way when a player connects, other clients can grab the correct player data (display name etc)
You want to Lobby Player Data in that case
https://docs.unity.com/lobby/update-player-data.html
Right... and I guess I'd have to store the "OwnerClientId" in the player data in order to associate each client with their corresponding player object?
I would use their Authentication Service PlayerId. Save that as their in game ID. So have a Dictionary or Struct List of <PlayerID, ClientID> for easy lookup
And make that a network variable?
If you do a List, sure. Dictionaries are not serializable. I keep mine local and update them with RPCs if I need to.
how to add simulated lag/packet loss to com.unity.transport
using photon pun 2 how can i get players view id from the playerlist
This the place to ask about netcoding, and creating network objects and syncing player data?
I made a player object prefab that tracks the mouse and I setup the Network Manager and had an outside client connect so the Server is working its more the coding portion IM very beginner. I was able to get both mice tracking on both client and host. THE ISSUE: I made a card game in "singleplayer" ie no networking just input from the player, I watched a couple videos on Netcode for Game Objects and found the RPC docs. The HOST can move the deck and syncs movement on both client and host, the issue is the CLIENT either doesnt seem to have permission, or the server is not recongizing the input. Ive tried a bunch of different ways Client Network Transform/ Network Transform switching the two. Adding ServerRpc/ClientRpc Commands to the Decks script that they call the function that handles the movement but then I get a disconnecting error when the client joins. Any help would be greatly appricated, Im very new coding in general.
I think you want to use the Multiplayer Tools
https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator#network-scenarios
The Network Simulator tool allows you to test your multiplayer game in less-than-ideal network conditions, enabling you to discover issues in simulated real-world scenarios and fix them before they surface in production. It facilitates simulating network events, such as network disconnects, lag spikes, and packet loss.
Does anyone else have any issues with relay ?
Joining a relay allocation works sometimes
Other times I get this error Error joining relay allocation: Not Found: join code not found
Does relay cache allocations or something throwing an error if trying to join an allocation that you are already joined?
This error seems to arise when I leave the lobby on a client and try to rejoin it. Lobby callbacks show the player is leaving the lobby no problem
Are you certain that the Relay is still running? I've also seen some people mistakingly use the lobby code to try to reconnect to the relay. The relay code looks similar to the lobby code.
Is relay down? I connect and then it immidiately freezes and kicks me out with those messages
Nothing reported here
https://status.unity.com/
Maybe open a support ticket.
Unity Services's status page provides information on the current status and incident history of Unity Services.
I tried 2 different projects and i get the same issue when it was working 20 mins ago
Okay nevermind something else is going on here. mb relay seems fine
@sharp axle do you have Multiplayer Tools installed? it's not working for me
installed 2022
Watch videos made with Clipchamp, the best video maker for everyone.
Anyone know of a way to fix the teleportation of respawning enemies for clients
I try setting the position of where they should respawn before setting the GO active and multiple other things but they still fly across the screen and hit the player
turn off interpolation on the network object then change the position and turn interpolation back on
🤔 GIving it a try
On just the client or both Client and server?
Trying it on the RPC but still isnt helping
[ClientRpc]
private void ReviveEnemyClientRPC(NetworkObjectReference enemy, int spawnLocation)
{
if (enemy.TryGet(out NetworkObject enemyGO))
{
NetworkTransform enemyTransform = enemyGO.GetComponent<NetworkTransform>();
enemyTransform.Interpolate = false;
enemyGO.transform.position = spawnLocations[spawnLocation].transform.position;
enemyGO.gameObject.SetActive(true);
enemyTransform.Interpolate = true;
enemyGO.GetComponent<MoreMountains.CorgiEngine.Health>().Revive();
}
}
Network Transform is server authoritative. If you are moving them on the client then you should be using ClientNetworkTransform
Understood, yeah i'm only moving them on the server. I just want this jumping to quit when they get reactivated.
private IEnumerator RespawnTimer()
{
while (true)
{
var respawnEnemy = GetPooledEnemy();
if (respawnEnemy != null)
{
var waitTime = Random.Range(.5f, 1.5f);
var randomSpawn = Random.Range(0, spawnLocations.Count);
NetworkTransform enemyTransform = respawnEnemy.GetComponent<NetworkTransform>();
yield return new WaitForSeconds(waitTime);
enemyTransform.Interpolate = false;
respawnEnemy.transform.position = spawnLocations[randomSpawn].transform.position;
respawnEnemy.SetActive(true);
NetworkObject networkObject = respawnEnemy.GetComponent<NetworkObject>();
if (!networkObject.IsSpawned)
{
networkObject.Spawn(respawnEnemy);
}
enemyTransform.Interpolate = true;
respawnEnemy.GetComponent<MoreMountains.CorgiEngine.Health>().Revive();
ReviveEnemyClientRPC(networkObject, randomSpawn);
}
else
{
yield return new WaitForSeconds(1);
}
}
}
[ClientRpc]
private void ReviveEnemyClientRPC(NetworkObjectReference enemy, int spawnLocation)
{
if (enemy.TryGet(out NetworkObject enemyGO))
{
enemyGO.gameObject.SetActive(true);
enemyGO.GetComponent<MoreMountains.CorgiEngine.Health>().Revive();
}
}
So i removed the Transform stuff out of the RPC and put it in the Main function. Still doesn't seem to work for the client. When it spawns it comes back right where it died and then flies to the correct location
I see. You need to leave it active. just disable the renderer
ooof , is there another way than that?
Cause id have to turn off collision and whole bunch of other stuff too
I thought the ClientRPC would allow me to set its Position
So it would automatically match the Server
wait
what if i turn off network transform and set the position and then turn it back on
ima try that
Nope didnt do anything lol
Check out how their object pooling example does it
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/object-pooling
Netcode for GameObjects (Netcode) provides built-in support for Object Pooling, which allows you to override the default Netcode destroy and spawn handlers with your own logic. This allows you to store destroyed network objects in a pool to reuse later. This is useful for frequently used objects, such as projectiles, and is a way to increase th...
Im essentially doing the same thing but a really dumbed down version
i've never blanked this much on something programming related
ur telling me
No matter how much I fiddle with this it doesn't work
what's the model called where the server looks at old data to determine if a client's shot hit someone?
god this stuff is complicated
Thanks for pointing me in the right direction. I missed the part of the code where you had to call .StartHost() or heartbeat the relay yourself.
You might be thinking of rollback netcode
lookup Client server reconciliation and interpolation
You'll need to figure out exactly what the clients need to know according to your game design
Hoping someone can help me with this.. I'm trying to manually spawn my palyer object... the docs say to use GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId); but If I run this on the client (so that the client can spawn their own player object) I get an error saying that Client's can't spawn objects
Yes. That has to be run on the server. You can have the client send a serverRPC to get the server to instantiate and SpawnAsPlayerObject their prefab
OK great. makes sense
should i be sending packets in LateUpdate() ?
Hey everyone, another 'teleport' question...
I spawn a clientnetworktransform on the host, it's controlled by anotherplayer... on spawn it interpolates from 0,0,0 to where it's suposed to spawn, i try to 'teleport' it but it throws me an error: 'Teleporting on non-authoritative side is not allowed' - is there no way to do this ? - i tried this from the host, from the owner, - i then tried changing the clientnetworktransform to a networktransform, and i keep getting the same error. Anyone can shine some light in this ?
You'll need to make sure the Network Object is actually Spawned and that CanCommitToTransform is true on whichever has authority over it
Its supposed to be set in NetworkTransform.cs
`private void Initialize()
{
if (!IsSpawned)
{
return;
}
CanCommitToTransform = IsServerAuthoritative() ? IsServer : IsOwner;`
Hey so I am planning on making a very small multiplayer game and I was wondering if I should go with photon or fishnet. Photon fusion looks really easy to work with but I have heard the fishnet can support more ccu so I’m trying to figure out which one to go with. I was wondering what are some pros and cons of both of them and which one a complete beginner to networking should choose. Thanks!
How do people handle the host disconnecting ?
or even a client disconnecting for that matter
but client side
im having trouble finding a callback for the timout within network manager
ive tried using unity multiplayer tools to simulate a network error and nothing happens
Lobby continues to ping on the server with no exceptions
The only time i can make an exception throw to handle a client disconnect client side is when the internet connection is straight up turned off. Then transport throws an error that im able to capture
How does one tap into the timeout/ping of network manager
is there a way to pass a reference to a networkbehaviour via serverrpc?
is my best bet to pass its NetworkObjectId?
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
thanks a bunch
In a multiplayer game, clients may get disconnected from the server for a variety of reasons (network issues, application/device crashes, etc). For those reasons, you may want to allow your players to reconnect to the game.
https://hastebin.com/ofetigoviz.cpp
hi so i am having a little bit of trouble, i have a script called instantiate players which instantiates them across then network then sets there view id in a list and randomly assigns a tag, and this script works great, but im having a problem with is the EnableUi script is suppost to just simply wait 3 seconds when the scene loads and then activate a ui for 3 seconds depending on the tag which was set in the previous script, but when i run the game all of the clients see the UI HiderUI. and unity is setup perfectly both are disabled and the script is on the gameobject
im using photon pun 2 btw
I can`t build game with dots
```PackageCache\com.unity.transport@fe9ce94216\Runtime\Utilities\ManagedCallWrapper.cs(22,16): Burst error BC1099: Calling conventions other than 'C' are not supported for calli. Found: Default
at Unity.Networking.Transport.ManagedCallWrapper.Method(void* functionPtr, void* arguments, int argumentsSize) (at .\Library\PackageCache\com.unity.transport@fe9ce94216\Runtime\Utilities\ManagedCallWrapper.cs:22)
at Unity.Networking.Transport.ManagedCallWrapper.Initialize() (at .\Library\PackageCache\com.unity.transport@fe9ce94216\Runtime\Utilities\ManagedCallWrapper.cs:31)
have this error
how do i fix it?
Is it possible to fix if i fork the main repository of unity.transport?
Just a quick question so I'm clear on this: collision detection is purely server authorative by default right? So callbacks like OnTriggerEnter and OnCollisionEnter are only computed on the server?
On the clients the rigidbody will be kinematic. Trigger events will still be fired but collision events will not be fired when colliding with other networked rigidbodies.
Thank you!
Hi! Is there any package for DOTS netcode profile like NetStatsMonitor or something like this? As I understand multiplayer tools package is for game objects only
any resource on where to read and write packets? FixedUpdate() vs Update() vs LateUpdate()?
If you are using Unity Transport the docs are here
https://docs-multiplayer.unity3d.com/transport/current/about
Unity Transport provides the com.unity.transport package, used to add multiplayer and network features to your project.
hm ok. thanks. i already went through one tutorial
Does anyone knows how to fix it?
How do I teleport the player with NetworkTransform (which is client authorative).
The player moves using CharacterController
Client Authorative network transform
public class ClientAuthorativeTransform : NetworkTransform
{
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
and player controller
private ClientAuthorativeTransform networkTransform;
public override void OnNetworkSpawn()
{
// Check if local player spawned
if (!IsOwner) return;
// get client authorative transform and teleport
networkTransform.Teleport(new Vector3(0, 0, 100),
Quaternion.identity,
transform.localScale);
}
The player does not seem to teleport.
Upon further inspection I get an error with content being Exception: Teleporting on non-authoritative side is not allowed!
I believe you have to wait a frame for the ownership to change if you are using the automated player prefab spawn.
Awesome.
This worked.
private IEnumerator Teleport()
{
yield return new WaitForEndOfFrame();
networkTransform.Teleport(new Vector3(0, 0, 100),
Quaternion.identity,
transform.localScale);
}
Cheers! ♥️
But I'm guessing doing a custom network manager would be much better than Unity's standard one.
That is so strange though, that you have to wait a frame for ownership to change after NetworkSpawn
Null is supposedly "unreliable", but I can't find how to make a reliable packet
It's not an enum, somewhere you have to create a NetworkPipeline
https://docs-multiplayer.unity3d.com/transport/current/pipelines Just a quick look on the docs site reveals this
Well I am on the docs site for Unity Transport
Passing in null likely uses the default values given a struct cannot be null
Whatever .Null is will be some set defaults
Question: I am working with the netCode package for multiplayer. I put the player prefab into the networkManager, But it creates the instance of the prefab at (0,0,0) but the transform position of the prefab is elsewhere. I'm not sure how I fix this
Edit: I got it. just had to override the at onnetworkspawn: public override void OnNetworkSpawn(){
@olive vessel I copy/pasted this code from https://docs-multiplayer.unity3d.com/transport/current/pipelines/index.html#use-the-reliability-pipeline:
m_ServerDriver = NetworkDriver.Create(new ReliableUtility.Parameters { WindowSize = 32 });
m_Pipeline = m_ServerDriver.CreatePipeline(typeof(ReliableSequencedPipelineStage));
and it's saying the first line is Obsolete
Pipelines are a feature which offers layers of functionality on top of the default socket implementation behaviour. In the case of the UDP socket this makes it possible to have additional functionality on top of the standard unreliable datagram, such as Quality of Service features like sequencing, reliability, fragmentation and so on.
Best off joining the Unity multiplayer networking Discord pinned to this channel
@olive vessel ok thank you very much
lol i think i found the answer in the 3rd latest post
(nvm) that wasn't it
got it
hey I'm trying to give someone a playfab item through script, anyone know how to do that?
Does anyone has a good crc32 for burst? with SIMD?
Hi, what's the best way to do multiplayer for a 2d soccer game that will fit 16-32 people?
Just use netcode for entities
I won't need my own servers?
You can do local multiplayer if you want
or peer to peer
it will use one of the peers as server but players can host too
Will I be able to add a search engine for such servers?
So i would need a script?
yes
okey, thx
Hi, just wondering, is UnityEngine.Networking package still around?
I'm using mirror networking and I'm trying to use synclist to sync structs with 2d arrays in it.
From searching online, mirror can't sync arrays and needs to use NetworkArray<> from UnityEngine.Networking.
After trying the method, it says NetworkArray namespace can't be found and I can't find where to add the networking package.
How to solve this problem or are there any workarounds?
You are generally expected to custom build collection sync. Any examples that come with a framework are typically not intended to be used in production
No that's the old unet framework and that's been completely deprecated in the latest versions. Netcode for GameObjects is the new system
Ah, thanks!
Um, what is a collection sync?
Is it recommended to use netcode or mirror?
If I made a game in singleplayer and I want to make it multiplayer, do I have to make two versions of the same script? one that handles singleplayer and one that is networked?
For example playermovement, does the game object need to have two scripts one for monobehavior and one for networkingbehavior?
A collection is a datastructure that contains a variable number of items (items can be structs or object references)
Both are recommended
If you build your game from the ground up as a multiplayer game you can unify multi and single player, where single play is just a ‘host’ with no external client connected. Depending on the game it can make sense to separate the single and multiplayer experience though since multiplayer puts significant constraints on what you can do and how much effort it is to implement
I built it from the ground up as singleplayer, its a card game so the movement is just based on weather or not the user is clicking and holding on the card. I got the network manager setup and added player objects and those seem to work, I can start the Host join as a client. The Host can move the cards and it updates to the clients, but none of the client movement is coming over.
You will end up rewriting everything if you started with no provision for multiplayer needs
Would it be possible to attach another movement script to the game object that uses serverRPC and calls the functions with the script that is actually handling the movement?
in theory you can patch individual parts to work over a network but this will become an unholy mess really fast
so if you plan to add multiplayer to anything like an actual game (complexity wise) you need to rewrite most parts to not melt your brain
Often enough you also will find that your (single player) game can’t realistically be a multiplayer game (design wise)
Thanks!
Is there a reason, it isnt easy to switch between a "Mono" object and "Networked" Object. Im very new to network coding, so im ignorant and just dont know what there actual separation aside from the name.
The main problem is that the entire architecture of the game usually has to change in order to accommodate sending data over the network. Unless it was designed that way from the start
Im very confused now, this my understanding. 1. Make a game object 2. Assign a script that allows the user to move the object around by clicking and holding with their mouse. 3. Add a network Object script to game object. 4. Prefab the object. 5. Assign the prefab in network manager. This is where Im confused. 6. Somehow call that network object from another script and instantiate on the server instance. 7. Test. I am thinking I am going wrong at step 2 or step 6. Or all of them. When I make the script do I have to start with it being Networked Behavior?
check out the new Getting Started guide
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo
Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).
THANK YOU, I dont know why that isnt first thing that pops up when looking for anything Unity, Netcode.
Thats excatly what I was looking for!
That particular page was just added today, lol
Sweet, ChatGPT sorta hits it wall when I got to networking because from what I read Netcode for Game Objects came out in 2022 but ChatGPT only knows up to 2021.
is it possible to sync a variable between all clients and the server?
that represents milliseconds since the game started
LocalTime and ServerTime
thanks. i don't think i'll do it anymore
Should I build my game first and then convert it to multiplayer or build my game with multiplayer?
Depends on if you want to make your game twice or just once
If I want to make it once should I just build multiplayer with it instead of after
That would be easiest, yes
Got it thank you!
Dont be a me, I made my game, came here to get some help networking and I have to start all over.
Glad it was only the base of the game (90%) but now I wont get farther and be like welp
Well using ChatGPT to make any sort of code is likely a bad idea
When it was first released, we saw so much code that either didn't compile or crashed Unity
ChatGPT is just good enough to fool you into thinking it knows what its talking about.
That sucks, thanks for the warning. I was planning on making my project then converting it to multiplayer cause I thought it would be easier. Glad I asked here first. Thanks!
Yeah, Same My thinking was whats the difference, just add a couple more lines of code to make it network. NOPE. That is not how it works. Start Multiplayer, Finish Multiplayer/Single
It doesnt help because if the code works the code works. If it doesnt then I try more responses, if it doesnt get it then I think its something wrong with my thought process. Which is most of the time true, but CHATgpt would never be able to know. So its useful for a foothold but as soon as I hit multiplayer and ChatGPT couldnt help, Im pretty much reading alien
using Photon.Pun;
public class EnableUI : MonoBehaviourPun
{
public GameObject hunterUI;
public GameObject hiderUI;
private void Start()
{
if (!photonView.IsMine)
return;
if (gameObject.tag == "Hunter")
{
hunterUI.SetActive(true);
Invoke("DisableHunterUI", 5f);
}
if (gameObject.tag == "Hider")
{
hiderUI.SetActive(true);
Invoke("DisableHiderUI", 5f);
}
}
private void DisableHunterUI()
{
hunterUI.SetActive(false);
}
private void DisableHiderUI()
{
hiderUI.SetActive(false);
}
}
i need help this script is on each player object, and when it enables from another script using playerview.gameobject.getcomponent.enabled that gets each viewid from each player it runs but only displays on the masterclient, and i think its because all the players are instantiations of 1 prefab and every client has the same script i dont know how i can make this run on only the client who owns the gameobjects and the script. each player has there own HunterUI and hiderUI gameobjects but it wont enable them for the client only them master basically
using photon pun 2
anybody come across an easier way to call APIs from unity
i'm using web requests right now and its makin my head hurt lol
is there a way to add a networkbehaviour on runtime to both clients and server? I am adding it locally at both places atm but idk if it is creating different ones as opposed to 1 "linked" networkbehaviour, additionally, is there a way to specify ownership when creating/adding a new networkbehaviour?
start over
Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).
I have a working project with server authoritative stuff, I am running into an issue though when trying to switch up / add network behaviours to my player object.
I am currently adding the networkbehaviour on server and then calling a clientrpc which adds the same networkbehaviour component on client side but it feels messy and running into some smaller issues which might not help in the long run
welp im out of answers
kk ty though, ill read up a bit though to see if im missing something
to be more specific, i have an autoattack abstract class that inherits from networkbehaviour, and my player prefab has a reference to that and I'm trying to switch it up on spawned player
I'm considering designing it a bit different to work around that if I don't get it working smoothly
ChatGPT is just scraping google. It's not doing any sort of thinking like a human. You are not doing yourself a favor by copying and pasting garbage from that bot.
It was banned from stackoverflow for giving repeatedly wrong answers and being extremely confident about those wrong answers
Im making a card game 😦
So then learn how to write code using your brain
You're not doing yourself any favors
what
You mean web APIs?
Then yeah web requests are your only option. Unless you want to write your own TCP mechanism in native C to do it with producing minimal garbage
Does anyone has a SIMD crc32 with burst?
is there a way to set a networkobjectreference to null? sort of like its initial value? I would think it has an initial value of 0 at NetworkobjectId. Basically im using a networkvariable<networkobjectreference> as a syncd target and trying to set it to null. currently also have a networkvariable<bool> istargeting to use that to know when it is not targetting something, but id like to be able to handle it with only one var by setting networkobjectreference to 0 or null somehow.
is there any specific reason why a serverrpc cant seem to use Resources.Load correctly?
that was my bad, seems to be working fine.
Just a guess but maybe that’s because internally it’s an integer value type that does not support null to avoid the allocations that all references (object types) would cause whenever changed
[PunRPC]
public void Damagee()
{
targetti.GetComponent<Player>().currentHealth -= attackDmg;
}
this is the RPC fonction
if (basAttackScript.spawnedArrow.transform.position == TargetCanvas.transform.position)
{
PW.RPC("Damagee", RpcTarget.AllBuffered, null);
if (targetti.GetComponent<Player>().isDEATH)
{
score();
}
PhotonNetwork.Destroy(basAttackScript.spawnedArrow);
}
I call the rpc here, it works but only i can see that targetti's currentHealth decreased. the other player who is targetti cant see the difference. Any help 😵💫
Anyone know how to serialize a NetworkList<T> when it is part of a custom network variable struct?
Using serializer.SerializeValue(ref MyNetworkListVariable) does not work
maybe this is indicative of a flawed architecture/design that you need to sync nested collections
That’s quite possible
hey
I am trying to connect to Netcode server hosted on a different system
The IP address in the Unity Transport is the public ip address
for the clients
but it fails to join
but when I have them on the same network
and give the local ip address
they connect
what am I doing wrong?
you need to configure your router for NAT or use a relay server
@austere yacht oh
So basically the setup goes like
Multiplay is the hosting service
Matchmaker initializes a server instance
We connect to the IP port of this server instance
using Relay
and then
send rpcs using netcode o.o?
Im sorry for confusing you
I tried the different system approach to test out
remote connections
if the server is hosted in the cloud you don't need a relay
relay is only for host based multiplayer (one of the players is the server)
The match maker gave me a
you need to run your dedicated server on some could service (playfab, unity cloud, aws, others...)
multiplayassign with ip and port
but when i try to connect to this ip address, it doesnt do anything
i've hosted on it on unity's multiplay
technically then this IP should be a virtual machine with your server running
yea
so I just do a unity transport connection to this ip right?
no need of using relay?
or do I have to do a createallocation like in the relay service
idk how unity cloud works specifically, but in theory, you should be able to connect directly, but maybe unity wants you to use the relay anyway
in services like playfab it takes quite some doing (config/api wise) on the server before your clients can connect smoothly
i tried photon fusion hosted on playfab multiplayer servers
was able to set it up
but wanted to try out unity's services as well
the complicated bits are in the dynamic provisioning of servers and security
you can make stuff 100x easier if you ignore security
i feel(personally) that unity's ux was better than playfab
in updating a server and all
well, unity's is more targeted and newer
What method or class do I use to check if a host/server is running on a said IP address ??
Using Netcode..
As far as I know, there is not one. You can try to connect with StartClient() and it will return false if it fails to connect
So how could I set up the fail connection to make a text appear then if there's no way to check?
I create a UI text that says "Failed to connect" and setactive when it fails to connect.. but there's no way to check if it can connect??
So something along the lines of
if (network.StartClient())
is the way you would check it?
basically, yea
Okay that's funny to me for some reason..
Thanks for the help..
is it impossible to have 2 clients and 1 server running on one PC?
since the 2 clients both have 127.0.0.1 and same port
No, you can do that
That's the connection address, each client will have it's own port
How to fix this error ? (I'm using Netcode)
this happens when I change my IP to static
the port that is required is open
ok you're right, thank you
If they are all on the same machine that could work. If the server is on a different machine that will not work
You will need to set up port forwarding on your router. Unity need to listen to the internal address
the port is open in the router
😕
can someone help me with client side prediction & server reconciliation ?
- Client applies user input, saves the frame number and new position into a dictionary, and sends the user input along with frame number to server
- Server applies the given user input, then sends back the new position and given frame number
- Client then does this: new position = current position + server position - frame number position
but in my game at the start the client position goes to infinity in a few seconds
I don't quite follow your step 3, looks like a mixture of positions from various points? With client side prediction you don't need to apply anything from what you've received from the server if it all matches up, you just run your guy locally until you detect a difference with what the server has, then start the server reconcilliation.
I'll outline a general flow.
- Client applies user input. Cache the input + frame data (positions etc) on client side for this frame. Also send the input + current frame number to the server. Lets say it's frame 50 on the client. (Which is a probably a bit a head of the server, lets say server is frame 45)
- Server received this input for frame 50. When Server gets to frame 50 it applies input, saves the frame data and sends this back to Client.
- Client receives Server's frame 50 message (Lets say client is now at frame 55), compare this server data with what we locally cached on the client for frame 50.
If the frame matches there is nothing to do, we're in sync. Job done!
If the server frame and client frame at 50 have different data/positions then trigger a server reconcilliation!
Restore your objects state to that of Server Frame 50.
Now we need to run the client back up to frame 55 as that's where the client was and may have already send some more inputs to the server
Run through the cached frame data for each frame from 50 to 55, reapplying the inputs, if any for these frames again.
Hopefully you're back in sync again!
well i read it twice
sheeeet
can we go back to my number 3 (sorry)
frame 56 xyz = frame 55 xyz + frame 50 xyz from server - frame 50 xyz cached
feel like that didn't make any more sense
ok i get that yeah.
if you're flying to infinity and its at the very start maybe one of those positions if coming out as NaN, havent cached anything, or recieved a server frame etc?
in ur example do u really keep track of the server's frame number?
not sure what you mean? I dont store it anywhere, the server has no need to store old frames. It just sends the number with the frame message to the client so it knows what local frame to compare it against
I’m so bad at thinking about time
Time and family trees I just blank on
i think the only difference between what we do is step 3 - you "reapply inputs" (which i can't wrap my head around) and i try to take some kind of delta (which makes sense depending on my mood)
oh i think i found something!!
This is a good overview
https://www.youtube.com/watch?v=TFLD9HWOc2k
Welcome to this Unity Tutorial where we go over Determinism, Fixed Tick Rate, Client Prediction, and Server Reconciliation. Deterministic Programs and Fixed Tick Rate are more theory but really important to understand in order to implement Client Prediction & Server Reconciliation. I then go into how to code Client Prediction & Server Reconcilia...
I wish there was more people who provide information and explain it like it does. Cause I'm slow and I feel like I completely understood this in 1 watch session.
This is such an advanced topic that a little tutorial will never get you anywhere. The implementation will be so different from project to project that you need to be able to come up with solutions yourself, that means you need to work with different kinds of resources (conferences, papers) and cobble together ideas from scattered articles. Most of the publicly available info on the subject can be found in a few gdc talks and articles linked here https://github.com/ThusSpokeNomad/GameNetworkingResources
is it hard to try and create a peer to peer multiplayer system?
True peer to peer is not something you really want. It exposes players IP addresses not to mention all the NAT issues. A Relay system is what most actually use. Those are fairly simple to setup and use by comparison.
Okay that's cool, would you recommend something like netcode for gameobjects or photon? These are the two ones I've found after some basic research
NGO, Photon, Mirror, and Fishnet are all fine frameworks. I personally use NGO.
is NGO difficult to implement?
nope, here's an easy tutorial
https://www.youtube.com/watch?v=3yuBOB3VrCk&ab_channel=CodeMonkey
awesome, thank you
It depends on your skill level and what you want to implement. But basic functionality is relatively simple
im making a top down shooter game and i wanted to try and make a co-op or pvp mode in the future, i just want to see if i can actually sync clients togethre
Does anyone know when OnNetworkSpawn() actually gets called for an object?
I have a strange situation where:
- Most of my networking exists from the very first second of the game, with DontDestroyLoad on nearly everything
OnNetworkSpawnedis correctly called for all objects (dynamic + in-scene). That (I think) is called once host starts (or client starts)- I call the classic NetworkManager.Shutdown method once everyone disconnects
- This correctly stops the host and all clients (looking at the Unity inspector)
- I boot up another game from my lobby + relay. Game is created, host is correctly started. All objects are still there and everything works as expected EXCEPT
OnNetworkSpawned()is no longer called on my objects.
Anyone had similar experiences?
For it to be called again on the host, you would need to reload the scene
GlobalObjectIdHash is the same. The network object does not get destroyed or anything. Also, it's a prefab correctly assigned to the network prefab list. (so yeah, an in-scene placed prefab)
The only difference running it for the first time vs. the second time for this object seems to be first time round OnNetworkSpawn() is called for it, also making the Unity inspector thing look different, whereas second time around it's as if the fact the host is started is being plainly ignored by the object
When you say reload the scene, do you just mean switching to that scene again? Because I do that
So flow is:
- Menu scene (everything there, nothing is "started"
- Goes to game scene, everything is running correctly.
- Players quit, everything gets stopped. Back to Menu scene
- Goes to game scene again, network manager has host running, but this network object does not get
OnNetworkSpawn()called at all, it just stays there just like it does in the menu scene
You are switching scenes on the host as well?
NetworkManager.Singleton.Shutdown();``` in order
is that NetworkManager.SceneManagement?
Also, player prefab does not have any issues. it works correctly. the only issue is around this network object
nope, is that a thing? 😄
{
NetworkManagerObject.Instance.DestroyObject();
SceneManager.LoadScene(0);
}```
that is what should be syncing sceneloading with the clients
Netcode for GameObjects Integrated Scene Management
I can confirm this worked!
Thanks a lot @sharp axle I also recommend the others check that out, as well as NetworkManager SpawnManager
private void Start()
{
camera = Instantiate(cam, player.position, player.rotation);
}
void FixedUpdate()
{
if (!IsLocalPlayer) return;
if (!IsOwner) return;
camera.transform.position = player.transform.position; ```
heres part of my code for my network manager player prefab
when i spawn 1 camera for 1 player it works great
but when i make a second player the first camera breaks
not sure why as the camera should always be the one that it made
[SerializeField] Camera mainCamera;
Instantiate(mainCamera, player.transform);
this is what i did for my camera but my game is 2D. it just worked right away
Camera camera;
private void Start()
{
player = GetComponent<Rigidbody>();
camera = Instantiate(cam, player.position, player.rotation);
camera.GetComponent<camera>().setplayer(this.gameObject);
}
void FixedUpdate()
{
if (!IsLocalPlayer) return;
if (!IsOwner) return;
camera.transform.position = player.transform.position;```` i have this and it works however theres 2 cameras, and both players see out of the most recent one
{
GameObject player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(player != null)
{
transform.position = player.GetComponent<Transform>().position;
}
}
public void setplayer(GameObject p)
{
player = p;
return;
}
}
this is the simple camera function
theyre not even networkobjects idk how both screens can see it
If you must spawn a camera, then use OnNetworkSpawn and check for isLocalPlayer before instantiating it. Unity really doesn't like having multiple main cameras in a scene
How to connect via an external IP in netcode ?
I put the IP address 0.0.0.0, there are no errors, but the client cannot connect
If you are connecting over the internet then you'll need to use a Relay Service or set up port forwarding on your router.
is this equation what all multiplayer games use for lag compensation? Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation
(taken from https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking)
maybe instead of packet latency i could use client frame number delta divided by 60hz tick rate
if (transform.parent != null)
{
if (transform.parent.gameObject.GetComponent<movement>().dropbutton() && usable) //if the player that posseses this gun clicks Q and the gun is equiped
{
rb.constraints = RigidbodyConstraints.None;
rb.collisionDetectionMode = CollisionDetectionMode.Continuous; //for collision
transform.SetParent(null); //should remove the gun from the palyer but it doesnt work
box.enabled = true; //collision stuff
rb.isKinematic = false;
StartCoroutine(turnoff()); //cooldown on picking up gun
rb.AddForce(Vector3.up * 200); //little throwing effect
}
}```
how come I cant remove my gun as a child from my client player
it works fine with host player
I assume it is because it is a child of the client object, which doesnt have permission to edit hierarchy. not sure how to get around that though
Hello - I'm getting started with Unity Netcode and could use some help understanding what the basic idea is. I'm working on a 2-player strategy card game.
In addition to the Player classes which are NetworkObjects, I've got a Game object that has a Network Object attached to, but itself does not inherit from NetworkBehavior. When I make a call on the Game object, it's not made on the corresponding Game object on the other connection.
How can I ensure that calls get made on each client's instance of the Game object; or, alternatively, do I need to use a different approach? Thanks!
I try to avoid parenting network objects. You'll need to send a ServerRPC from the client if you need to drop the gun
It will need to be a networkbehaviour
OK! So - it (the Game class) now a network behavior, but alas, the issue still persists - I'm only calling the function on the local instance.
If you need to communicate over the network, your choices are Network Variables or RPCs/Custom Messages
so, this is a turn based game, so my gut says RPC is functionally going to be the way. But I guess I'm looking for a kind of more general understanding of how the flow is supposed to look. Right now I have a button that calls StartGame() on my Game object, and that does some stuff. Great.
One thing I notice is that, I keep on my Game object a list of all Players - in my onNetworkSpawn on the player object, it calls a method on Game that adds itself to that list. My host sees this - and I can note that my list of Players now has 2 (or more) clients - so that call is being communicated at least from the Client to the Host without any RPC magic or Networked variables...
That list of Players is local only. You can listen for network events like OnNetworkSpawn and OnNetworkDespawn, those are happening through the network manager. That's not really communicating with the clients.
got it.
when I connect as a client, it's creating that Nth player object locally on the host, and that's the version that's communicating back to the hosts copy of Game. So it's only through the connection that that's happening on both sides (presumably by some under-the-hood RPCs I can't see?). So basically instead of calling StartGame directly, I need to invoke it through an RPC?
lol literally all i did was change it to [ClientRPC] StartGame_ClientRpc() and it works*. Amazing.
How to download Netcode for GameObjects?
I am trying to use the link provided in the guide however it says "Page not found".
Also, would it be recommended to use UNet (although deprecated) if I want a common solution for WebGL and VR platform?
No, there’s no good reason to use a deprecated old networking solution
hii , can anyone tell me why my player is not comming when i start the game
Netcode is in the package manager now
Is your host running?
yes i have clicked on host and its say no dispay to show because no player is there and player has camera
if i directly put player prefab there instead of in netwok manager then it work fines
If the player has a network object on it then it should be Spawned automatically
Harder to come up with lag compensation solution for projectile collision than raycasting
Guys got a quick question, I have players able to SetTiles on a tilemap during runtime, can I spawn these on the network the same way as anything else or is there a different method
also if I have a world that is painted on a grid how do I sync it between clients
I don't think you can Instantiate tiles on a tilemap like you can game objects. It would probably be best to use RPCs to call your SetTiles function
Anybody knows Unity Netcode here? I am struggling with NetworkList sync. Somehow it breaks on client but only on first load. If I add 1 item to NetworkList on host, connect client and then increase value of that item it duplicates it on client. So client's list now has count 2. If I close the client and then connect again, it works fine. No idea why it's only happening on first client load and why NetworkList doesn't sync correctly.
I'd like to design a game which works from both Web and from Desktop will NGO be useful here?
Unity Transport 2.0 supports WebSockets now
Is there any updated documentation which I am missing since the website says there is no support for WebSockets and we have to implement it using third party libraries..
unity Netcode, when I Start as a Host, am /I/ the server, or does it create a server and simultaneously connect me as a client?
It's still in preview
https://docs.unity3d.com/Packages/com.unity.transport@2.0/manual/index.html
Host is both a client and the server
sorry just to clarify, I'm wondering if they can be understood as a singular entity. Like when I hit "Start Host" on one instance and "Start Client" on another, under the hood the other instance is connected TO the host, the host's instance IS the server instance; or does the game see it as 1 Server with 2 Clients attached?
Yea, the host is a single entity. Any checks for isClient or isServer will return true on the host
OK. it'll still run clientRPCs?
and if I want to raise raise an event for the clients, the way to do that is to call a clientRPC method that invokes the event locally, I can't raise the event directly?
Regular events will still work. They just won't be sent to the other clients over the network
thanks for all your answers! I have a ton more but don't want to overload you, i'm still trying to grok how to organize around this workflow and getting there little-by-little.
Hi does someone ever use Lobby for unity ? i got an error trying to launch the sample
Check the readme at the top here. Lobby events are still in beta.
https://github.com/Unity-Technologies/com.unity.services.samples.game-lobby
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System;
// Original code is from https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Post.html
public class AI_SQLTools : MonoBehaviour
{
string url = "http://appticalillusions.com.linux318.unoeuro-server.com/addData.php";
public IEnumerator AddSQLEntry(string _time, string _loudness)
{
WWWForm form = new WWWForm();
form.AddField("time", _time);
form.AddField("loudness", _loudness);
using (UnityWebRequest www = UnityWebRequest.Post(url, form))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}
}
``` I get a 406 error every time. How can I fix this?
👀 does photon only work when you're connected to the internet? (might be a very stupid question)
Yea. Photon is a cloud service
Ill preface this by saying Ive never worked on networking before
and im currently looking at learning fishnet, although im open to other suggestions
but the problem here is i dont quite understand some of the terminology
fishnet provides a networking solution, and as i understand it also an option to play the game locally
however, i dont quite understand how this network is constructed, is it a single global server?
or is it a server you can run on the same as machine your own client (LAN), or alternatively on a dedicated device (that has no client instance)?
take the example of a minecraft server, you can host a LAN game, play singleplayer or play on a dedicated server (which takes an individual to setup the server for his friends)
or is it more like a chatroom with a single global server?
i dont know if im making any sense here, please ask for further explanation if needed
if the game im coding doesnt allow syncing transform does syncing int to getchild it later is actual best option?
[UnityNetcode] When I put ClientRpcParams as an argument to a ClientRPC method, does the networking layer auto-sense this and restrict propagation to only the indicated clients, or do I need to test for that in the ClientRPC method myself? If it's done automatically, does ClientRPCParams need to be the Nth argument, or just anywhere in the list of args?
why is my networkanimator only playing the first frame of animations?
i really need help here
bump
are you setting the animation parameters in code still or something?
did you forget to stop running your animator code on remote players?
Has anyone tried using netcode for gameobjects for a game that is playable both offline and online? It seems like using things like NetworkVariable offline is producing a number of warnings and errors, but I'd like to avoid having duplicate variables in my scripts to handle both modes.
Is there maybe a way for NetworkVariable to be usable offline without issues, or perhaps a better way to solve this?
i am using animation.play
I believe you have to start as a host and just not allow anyone to join
they don't have an offline transport as far as I know
If someone without internet access wants to play, will this be an issue? Meaning the host can't be started or something like that
the host can be localhost
it should be fine
you can start a host with no internet
oh perfect, that should simplify things quite a bit. Thanks!
quick q - can a networkbehavior be passed as an argument in an RPC call?
is using Animation.Play the cause of the problem?
potentially, but the second part of what I originally said is the more important question
if you do not have an understanding of how the NetworkAnimator syncs the animation state to players, you might have a setup that just does not work right now
do you mean checking if the player is local? because i did that
i don't, but don't blame me, there is no documentation online i can find
is your server / client authority set up properly?
i also tried using [ServerRpc] over my activate animation method which produces the same result
?
nevermind yes it is working
i call AddPlayerForConnection when a player joins
I mean is your NetworkAnimator set to the correct sync mode (server authoritative / client authoritative)
if you are changing it on the client it should be client authoritative
it is set to client to server
I don't know how the NetworkAnimator works internally, but it could be that it just syncs parameters and triggers
so it really could be that your .Play is breaking it
could you swap your animation controller out for a new testing one and see if you can get it to sync with some simple parameters?
alright
Seems from the documentation like they want you to use parameters
You should be using parameters to change animation states
https://docs-multiplayer.unity3d.com/netcode/current/components/networkanimator
Introduction
There is a TargetClientIds list that you can set in CkientRpcSendParams
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/clientrpc#to-send-to-one-client-use-clientrpcsendparameters
Servers can invoke a ClientRpc to execute on all clients.
yeah I'm setting the TargetClientIDs - but does the method that's receiving it need to verify them on the Client side, or does the netcode take care of that for me?
its only getting sent to those clients. You can double check on the clients I guess if you want
i'm getting some sort of hash error
netAnimList[index].SetTrigger("Character Run");
gives me this error
Parameter 'Hash -1548500351' does not exist. UnityEngine.Animator:SetTrigger (int)
Because trigger properties have this unique behavior, they require that you to set the trigger value via the NetworkAnimator.SetTrigger method.
netAnimList[index] is a NetworkAnimator
In that case, I guess there is a typo in the name
there is not, do I have to set these parameters in the (not network) animator editor? (which i did)
I'm not sure where else you can set the parameters
turns out you were right
but now i get this
NullReferenceException: Object reference not set to an instance of an object Mirror.NetworkAnimator.SetTrigger (System.Int32 hash) (at Assets/Mirror/Components/NetworkAnimator.cs:425)
I have no clue how Mirror sets up its network animator
Hello, I am trying to understand how reconnection is supposed to be handled in a server client model
I have a PlayerPrefab, and on disconnection would like to preserve this spawned prefab
And upon reconnection, would like to assign it back to the original player
Also an additional question
Do I set the player prefab in the network object and spawn/despawn it when player connects/disconnects? With the "Dont Destroy with Owner" enabled off?
Right now I was able to do reconnection in a very wonky way
Where I have a NetworkList<sting> with my unique ID and on joining the room I see if my unique ID already exists in the room
Hey guys, i was wondering how optimised unity netcode's racing game sample may be for mobile.
Anyone has an idea about it?
If it does, I request the ownership for the old NetworkObject
This seems to be working but I feel there has to be a better solution or way to handle reconnections
I have also integrated the lobby system for a private game. Once all players connect do I push them to a matchmaker queue called "PrivateGame" and then allocate the server? Or do I have another way to allocate and let only my lobby players to get in
NetworkBehaviourReference might be what you are looking for
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization#networkbehaviourreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
I’m working on Lag Compensation and I ran into a problem. On the server I instantiate a “RewindHitbox” game object and then immediately shoot a Raycast. But the problem is apparently at least one FixedUpdate needs to run for a raycast to hit a newly moved object.
I might have found it
But that seems very expensive to do
That should work. Just remember that its just a reference and its not sending any data along with it
Debug.DrawRay is a little cool
is it worth replacing ints with sbytes for networking
The answer is "It Depends". Is it important that its sbytes instead of bytes? Are you bit packing? Maybe ints or even longs are more efficient.
The answer for Anuked is probably no given what we know about the rest of the game...
I am terrified they're doing networking, yet not at all surprised
bump. Could someone answer these doubts please 😛
Anyone know if there is a service within UGS suitable for storing public player data? I know that there is cloud save, but that seems more like private data like game saves or progress etc.
What I’m after is a place to store things like player display name, Elo ranking etc. and have it publicly accessible by other players in the game.
Hi - question about multiplayer workflow. When my player does an action that affects the gamestate (say, sells a weapon at a shop - removing the item from inventory and adding the money, and adding the item to the shop inventory) I have it set up so that the player in the UI triggers a ServerRpc which does validation, checks any game rules, then applies the result to the server instance of the data. OK, great. What's the ideal method for syncing that data back to the player? (let's assume network vars are out). Is the common practice to have essentially a companion clientRpc to every serverRpc that receives the confirmed changes back from the server and applies them? ie I might have SellItem_ServerRpc(PlayerID, ItemID) as well as a SellItem_ClientRpc(PlayerID, ItemID) that is essentially identical?
That’s generally how I do it, not sure if that’s accepted practice or not. Sometimes you send the server RPC and then just do the thing locally on the client rather than wait for the server to confirm - this gets rid of the round trip lag but is no longer the server authoritative
Cool, thanks. Yeah it's turn-based so I can fade seconds of lag if need be.
I kind of settled on a slightly different approach: the ServerRpc does it's things - in my case, usually manipulating lists - then sends back the full set. Then on the client side, I recalculate what items were added to the list and which were removed and then reexecute the data update.
a little pedantic for a game at most 4 people will ever play, but I figure, i'm learning.
Nice. I even go so far as to use a naming convention like:
RequestMethodName_ServerRpc
ReceiveMethodName_ClientRpc
ApplyMethodName
Call the server RPC from the client, who calls the client RPC who calls apply on whatever local scrip needs applying.
oh I see yeah the apply method does your business end so it's identical and you don't need to repeat yourself.
one question, in a host/client relationship, how do you ensure you don't Double modify?
Well the host is a server and a client, so he can call the server RPC does the validation in your case and whatever logic you want to do there, then also gets the client RPC like everyone else. So if you’re doing the same logic inside the server RPC and inside the client RPC, then in the client RPC you would just check if !NetworkManager.Singleton.IsServer and then do the logic, that way you avoid the double ups
so - even more simply: if the ServerRpc validates against it's own data, but then assumes that it will update itself in the ClientRpc call, so don't do any actual state change in the ServerRpc?
or to be able to switch back and forth (between server/clients or host/client), you only call that actual data change function in the serverRpc if it's not a client. otherwise assume the client will do it for you.
Your first statement works, and if setup that way the server code is just acting as a relay of data between all clients.
Your second statement doesn’t really make sense… ONLY the server will ever run a server RPC so checking if it’s not a client is redundant
I'm making a 1v1 fighting game, currently there's only one scene that's the battle arena. I made it so that when one player dies, the scene gets reloaded with NetworkManager.SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);. This works, but I notice in the editor every time I load the scene another NetworkManager object is spawned under the DontDestroyOnLoad hierarchy. Is this something that doesn't matter, or should I be looking to change this? If there are problems having more than one NetworkManager in a scene, how would I go about fixing it so there's only ever one?
Perhaps instead of reloading the scene to begin a new round, I should just reset the player health and positions and begin a new round that way?
I wouldn't reload the scene for a new round, especially if you have destructible stage elements or stage transitions. For the multiple managers thing, you can have an main menu type scene that has the network manager when you first start the game then your stage won't need one in it and you can reload it without issue
Thanks, for now I ended up going without reloading the scene at all until I have some kind of main menu or other entry scene like you suggested.
Well if we're in host/client mode the server will also be a client, correct?
I cant seem to find anything about accessing other players data, just your own right?
by default yes. You would need to use Cloud Code to be able to access arbitrary player data
Hey all. I want to build my first multiplayer Unity game, but I'm struggling to find a suitable solution for a Unity game with a dedicated server. The game will be turn-based, so I'm not looking for the most performant solution - just some recommendations on a good entry point into multiplayer networking.
All of my experience with backend/frontend is through my career as a dev - so I've only ever used .NET/Node.js API's and HTTP for servers. I'd like to learn more about what the accepted Unity equivalent is for a dedicated server and where to deploy.
Thanks very much in advance 🙂
For anyone using netcode for gameobjects, how are you handling player spawning? My gut tells me I should have one object that represents the client (i.e. account data), and one that represents the player (i.e. their character), but the network manager seems to want players to only have 1 "player" object
It all depends on you game design. You don't necessarily even need a player object at all. There is nothing really special about a player object, it's just one with some handy shortcuts to reference.
Is anyone building a dedicated server with ecs?
Can someone tell me why only the local function (the first one) - is executing and neither of the RPC calls - are getting made? The initial call to LogServer is being made by a client and I don't even see the results applied locally let alone along a network
also yes this is within a NetworkBehavior class.
Hello could you create a private matchmaking queue using Attributes?
WIth no relaxation? I want people who have the attribute to join others with said attribute
basically i would like my matchamker to say something like
The roomcode of AllPlayers in the Match must be Equal to "1234"
The 1234 is entered dynamically
found it 😄
its in the equality rule check
ty
You can’t send strings in a RPC
RPCs are not being called
You actually can send strings now in RPCs. They just can't be network variables.
Hello!
I'm reading the doc of NGO and I just unable to find any specification about recommended/max player per server counts written anywhere. I saw a unity vid (on official YT channel) saying it's recommended for 16 player (2-3 month old vid). Is it true?
What BattleBit remastered uses for handling like 254 player per server?
That's because there is no limit really, it's highly dependant on the game and the code you write
You'll find a point where you reach a bottleneck and maybe can't squeeze any more out of it
I would like to create a top down 2d space ship shooter like game, where the players zoom around in their ships, fire (a lot) at each other.
As I can see fusion has this area culling - which is not yet implemented for NGOs. But do I need that, since it's a top down game (idea)?
Who knows, again there's a lot of parameters
I believe Unity does frustrum culling in builds, so things off screen aren't rendered
hey, I am pretty new to photon and I can't find out when I create my player it is not active in hierarchy
this is how i am creating my player
private void CreatePlayer()
{
GameObject player = _prefabPool.Instantiate("Player", Vector3.zero, Quaternion.identity);
player.SetActive(true);
}
I can also provide more info on this if required
Hi, I'm trying to sync player movement in multiplayer using network variables instead of network transform. Anyone with any insight or tips? I'm using character controller and sending the input on the network variables but it's not very precise and the mirrors end on slightly different positions
This sample uses Unity 3rd person controller
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/main/Basic/ClientDriven
my problem that client player is not moving, only host is moving, here is demonstration:
here is the code of player:
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class CursorPlayer : NetworkBehaviour
{
public TMPro.TMP_Text playerNameText;
[SyncVar(hook = nameof(OnNameChanged))]
public string playerName;
[SyncVar(hook = nameof(OnColorChanged))]
public Color playerColor;
private void OnNameChanged(string old, string @new){
playerNameText.text = playerName;
}
private void OnColorChanged(Color old, Color @new){
playerNameText.color = playerColor;
}
[Command]
public void SetupPlayer(string name, Color color){
playerName = name;
playerColor = color;
}
public override void OnStartLocalPlayer()
{
string name = "Player" + Random.Range(1, 999);
Color color = Random.ColorHSV(0, 1, 0, 1, 0, 1, 1, 1);
SetupPlayer(name, color);
}
private void Update() {
if (!isLocalPlayer) return;
playerNameText.gameObject.SetActive(false);
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = pos;
}
}
bumping - would appreciate it if anyone could give this a read 🙂
i've been considering it, but have always had difficulty setting up AWS services in the past. It's a toss up between this and Multiplay at the moment
Unity has a Dedicated Server Service called Multiplay
This is what I'm leaning towards atm, but I'm unsure about a lot of things. Would you typically deploy the same project as a headless build, or a separate project entirely? & if you wanted to develop using a server on a local machine first to cut costs, what would look different code-wise between hooking up to Multiplay/hooking up to a local server? Appreciate if these q's are quite basic and/or dependant on the project, I'm pretty inexperienced
very little actual changes
https://docs-multiplayer.unity3d.com/netcode/current/learn/porting-to-dgs
This is part one of the Porting from client-hosted to dedicated server-hosted series.
i can`t build a dedicated server with ECS. Looks like latest version of entities is broken for building dedicated server
This is very useful! Thanks for the link. However, I was more wondering about the differences between hooking up a client to a separate local (but dedicated) server build, as opposed to a cloud solution.
Ah, rules that out then. I think I'll defo be going for Multiplay - just want to make sure I can make the switch from a local DGS at the last second, so I don't start running down my trial
Its literally the same has connecting to a host from a client
any help for this?
Was hoping that would be the case, just wanted to make sure there was no additional configuration or anything needed. Sorry for the noob question 
make sure you are using a client network transform in that case
One more Q - if you use the same solution for both the server/client code, how can you make sure to keep all of the server logic separate from the client and vice versa? I've seen examples of people using directives and hash ifs everywhere - but that seems like it can get pretty messy.
i will check tomorrow
i dont understand wdym
You can use Assembly Definitions or Compile Defines for code stripping
though honestly it feels more trouble than its worth
Using player movement as an example:
Update()
if (client)
RequestMove()
RequestMove()
{
// client does stuff
}
#IF SERVER
OnMoveRequest()
{
// server does stuff
}
#ENDIF
how onmoverequest is being called? 😄
Yeah, that feels like a lot of trouble to me - I don't like the idea of tangling up the code that would only execute on the server, with client code. But all of my research seems to suggest I'm mad for thinking of creating 2 separate projects for the server/client
Just pseudo-code, couldn't really be bothered to write it up properly haha
In this case you use Server/ClientRPCs that is basically sending messages back and forth. The same code is on both and indeed has to be on both
i'm have mirror networking as my networking library (is someone noticed tihs? 😄)
even with a DGS, the clients need server RPCs? 😮
clients call the ServerRPC, the server runs the ServerRPC. The server will call the ClientRPCs and the clients will all run them
Unity has a good guide for this - https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo
Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).
we are talking about Unity Netcode. But I assume Mirror is similar
😕
Ahhhhhhhhhhhhhhhhhhhh
its just clicked
I had in my head both RPCs only existed in the docs because they were using P2P for the guides, so of course all clients needed the server RPCs
parameters are sent between the 2 as data
Technically, the clients only need the ServerRPC signature defined since they are not running it. But again more trouble than its worth trying to strip that out
right - there's no real benefit to stripping it out except your build being smaller by a negligible amount?
is this way to do movement? (im just looking for example)
dont care that this is not cde about mvement
If you are using server authoritative movement, yes
It could be for security reasons.
make authority server only?
what would the security risk be by leaving server code in the client build? that code won't ever be executed since the client build will never be acting as a server?
yes. i don't know how Mirror usually handles syncing transforms
could be like algorithms for encrypting data or something like that.
oh yeah, oops, big oversight by me
lol, Networking is hard
when you said the clients only need the ServerRPC signature defined, why would they even need that?
yeah man
its blowing my mind trying to get my head around it
not quite as straightforward as web dev
in PlayerMove(Vector3 direction), direction will get serialized and sent to the server
oh, so it would look something like this in the case of 2 separate projects?
assuming this is the server:
[ServerRPC]
OnMoveRequest(ServerRpcParams request)
{
// server does stuff
}
And then the client
Update()
{
RequestMove(dir)
}
[ServerRPC]
RequestMove(Vector3 dir)
{
// empty?
}
[ClientRPC]
Move(ClientRpcParams response)
{
// client does stuff once the server responds
}
am I getting that right for how the client/server would interact?
and in the case of server/client being on the same project, RequestMove would be replaced with OnMoveRequest, with additional checks for if build is the server
Basically. the Signatures will need to be the same so both the server and client would have
[ServerRPC] RequestMove(Vector3 dir, ServerRpcParams params) {}
And RPCs have to make a call somewhere to the opposing RPC? what would you use for something event based?
sorry for picking your brain so much, you just know your stuff
lol, no worries. I took almost a 6 month of banging my head against this during the beta to get my head around this.
For event type calls, you could either use empty parameter like [ClientRPC] StartMatch() or you could use Custom Messages
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages
A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.
cool, this is exactly the type of thing I was looking for. im really concerned about keeping my server/client code together - feels like untangling that down the line would be a mission if I want to improve security. do you have any examples of someone implementing separate client/server projects? I'm interested to see how this would be handled
If you're feeling spunky then check out the Boss Room sample by Unity. But it is not for faint of heart. Its a bit too complex for me
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture#clientserver-code-separation
Boss Room is a fully functional co-op multiplayer RPG made with Unity Netcode. It's an educational sample designed to showcase typical Netcode patterns often featured in similar multiplayer games. Players work together to fight Imps and a boss using a click-to-move control model.
i've been putting it off, on part because the NGO guides so far have seemed to be centred around P2P. But I suppose I should go through it all before stressing about what the end solution would look like
i'll give it a go - and likely come running back soon when I have no idea what's going on haha
this is fantastic - the indepth breakdown of how the team handled client-server code separation is exactly what I was looking for
Greetings, I'm developing a multiplayer card game using Lobby and Relay. I want the host to be the "source of truth" for all the cards. It's a realtime multiplayer version of Solitaire (i.e. Dutch Blitz or Nertz) so it's not turn-based. Because players are playing to the same "foundations" I need to be able to have the "server" determine if plays are legal or not.
But just starting out, I want the server to initialize the cards for all the players. I've defined a PlayerCards class as follows:
public class PlayerCards
{
public string PlayerId { get; private set; }
public Suit Suit { get; private set; }
public DrawPile DrawPile { get; private set; }
public List<Card> DiscardPile { get; private set; }
public TradingPile[] TradingPiles { get; private set; }
public CastlePile CastlePile { get; private set; }
...
}
I am hydrating that in my GameManager's OnNetworkSpawn() method (for the host only) and I want to propagate it out to the clients. I'm wondering the best way to do that? Should I use a ClientRpc method and setup a bunch of serialization? Or is there a better way?
Thanks!
The two ways to communicate between client and server are with RPCs or Network Variables. Network Variables have to be structs that implement INetworkSerializable. RPCs can use classes but I think they also have to implement INetworkSerializable
so, if you have a class that represents a Card - when that card is attempted to be played by the client, you would have to have a struct DTO that implements INetworkSerializable to send that info over to the server?
Hey, noob here, right now my netcode syncs to clients once every second. I'm worried this is not enough for a fast-paced multiplayer game that is similar to smash-bros which i am making. Is there a way to either make netcode for game objects sync to the client faster or to negate this problem?
Well, I just have a list of Cards and I send the IDs. Kind of like a mini database. No need to send the entire class/struct.
First you need to determine if it's actually a problem. Second, you can change the tick rate in the Network Manager.
Where is the network manager?
In your scene
Alright, got you. Another noob question - for a card game, chess game, or any other heads-up 1v1 game - is each individual "match" a different server? Or is it possible to have a server host multiple instances of different games?
Usually its one server instance(Network Manager) per match. Its possible to have multiple matches set up for a single server instance. But probably more trouble than its worth. Hosting services like mulitplay or playfab can spin up new server instances automatically to meet demand.
Makes sense, thank you!
Hey is this where i can ask about like setting up servers for multiplayer?
please @ me when you respond :)
Sure
Hey y'all, quick question on if there are any lifecycle / order-of-execution reference diagrams for NGO? I've referenced the standard unity order of execution diagram on several occasions and it's really helpful. I'm not new to networking in games per se, but I am still getting started with NGO, coming from Mirror, though it's been a solid year or so since I have don anything with that even
if not, i can definitely continue to just sift through the docs. But thought it would be helpful to have. Google searches haven't turned anything up
I think this is what you are looking for
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/network-update-loop-system/network-update-loop-reference
The following diagrams provide insight into the Network Update Loop process and APIs.
Yes! that is exactly what I am looking for, for the most part anyway, thank you. Can't believe I missed that 
bet ty!
Anyone aware of this error? getting it while following this video
https://youtu.be/KHWuTBmT1oI
A step by step guide to make your first VR multiplayer application with Unity and Photon.
▶ Get access to the source code: https://www.patreon.com/ValemVR
▶ Join the Discord channel: https://discord.gg/5uhRegs
Download the Hand Presence Unity Package :
https://drive.google.com/file/d/1xFBs6vA_p9EHLHcwjYIxGHcnHqatxJjz
TIMESTAMPS:
0:00 VR Set...
At what point in the video are you hitting the error? And are you trying to perform operations on the Client somewhere outside of the two callbacks mentioned in the error? Basically based on the error, you're trying to perform some kind of operation on the Client before it's ready and should move that logic to one of the callbacks mentioned in the error.
But if you're getting the error even after doing that or you're not trying to do anything to the client but still getting that error, then you'd probably need to provide more context and code samples
I can provide code and stuff yep! its exactly whats coded in the video too. Its when the game starts and its trying to connect to the server
i presume its why my Oculus quest build and the Unity editor build didnt join a server together
is ther a way i can show the entire log?
what does the stack trace say for that error?
stack tray?
sorry im unfarmiliar with the term
it's the part of the unity console below the log messages. It should have a trace of where the error originated from and gives you file names and line numbers
^ the area in the orange border is the stack trace
Ah!
UnityEngine.Debug:LogError (object)
Photon.Pun.PhotonNetwork:JoinOrCreateRoom (string,Photon.Realtime.RoomOptions,Photon.Realtime.TypedLobby,string[]) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetwork.cs:1850)
NetworkManager:OnConnectedToMaster () (at Assets/NetworkManager.cs:29)
Photon.Realtime.ConnectionCallbacksContainer:OnConnectedToMaster () (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:4126)
Photon.Realtime.LoadBalancingClient:OnOperationResponse (ExitGames.Client.Photon.OperationResponse) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:2737)
ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback (ExitGames.Client.Photon.StreamBuffer) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:872)
ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:583)
ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1771)
Photon.Pun.PhotonHandler:Dispatch () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:226)
Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:145)
can you paste your network manager script?
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class NetworkManager : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
void Start()
{
ConnectToServer();
}
void ConnectToServer()
{
PhotonNetwork.ConnectUsingSettings();
Debug.Log("Try Connect to server...");
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected to server!");
base.OnConnectedToMaster();
RoomOptions roomOptions = new RoomOptions();
roomOptions.MaxPlayers= 10;
roomOptions.IsVisible= true;
roomOptions.IsOpen= true;
PhotonNetwork.JoinOrCreateRoom("Room 1", roomOptions, TypedLobby.Default);
}
public override void OnJoinedRoom()
{
Debug.Log("Joined a room.");
base.OnJoinedRoom();
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
Debug.Log("A new player joined the room.");
base.OnPlayerEnteredRoom(newPlayer);
}
}```
hey guys any one had a problem were the canvas on the client position changes when it connects?
got some q’s. for a turn-based card game, is there any real need for network prefabs? seems like a more intuitive way will just have the client handle any animations, and the server handle any state logic through network variables.
Yea. Network prefabs are only really for spawning things
got it. Think I was getting a little confused - the docs made me assume that any networking has to be done through networkbehaviors on network prefabs
They will need a Network Object component though
yeah, makes sense. i’m wondering if i should be spawning every card through the server, though, to keep the server truly authoritative. but my instinct is to have the server tell the client to spawn a certain card as it’s drawn, and have the actual spawning done by the clients, who can then control the animations etc
Yea. it really depends. There is no real wrong answers
hello
This is something I’m thinking through as well. Instead of just syncing the lists of cards, I want to fire events when a card is dragged from one stack to another so the clients can animate it. And I can’t use network transforms because the location on the screen is from the local players perspective.
im having the same issues. that's why I'm thinking a better separation of concerns (for a turn-based card game at least) is to keep all objects local, and have any state changes controlled by the server. still authoritative, just removes the complexity of having the server create objects at different positions for different perspectives
im not sure what the code would look like given that I'm still planning things and experimenting with networking, but that would be my next go
From what I'm seeing on the forums, Unity recommends that you don't write to a NetworkVariable<T> before the OnNetworkSpawn event occurs. I'm finding this a bit tricky, in that I want to set the initial values of my objects before spawning them, which is giving me a bunch of warnings. Does anyone have a good solution for dynamic network initialization to get around this issue?
i'm so noob, that i can't event make chat
i have this every time trying to send message
and message is not adds to chat
here is code for sending messages to chat:
[Command]
public void SendChatMessage(string message, string author){
if (!chat) {
Debug.LogError("Chat field is not assigned!\nMessage will not be delivered");
return;
}
if (author == null){
chatText += $"{message}\n";
}
else{
chatText += $"<{author}> {message}";
}
chat.text = chatText;
}
and here is code from chat input:
public class ChatInput : MonoBehaviour
{
public SceneScript sceneScript;
private TMPro.TMP_InputField input;
private void Start() {
input = GetComponent<TMPro.TMP_InputField>();
}
void Update(){
if (Input.GetKeyDown(KeyCode.Return)){
sceneScript.SendChatMessage(input.text);
input.text = "";
sceneScript.chat.gameObject.SetActive(false);
}
}
}
Honestly, I've just been ignoring those warnings. But I think the real answer is to use the OnSynchronize() callback
Does this event still exist? I'm seeing it listed in a couple places online but it's not popping up in the IDE for NetworkBehaviour
Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer. - com.uni...
@sharp axle in the boss room architecture, the devs talk about the issues they had with trying to achieve client/server code separation (https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture/index.html#clientserver-code-separation). They came to a lot of the same conclusions we discussed yday, such as asmdef stripping and ifdef classes not being worth the added complexity. They ended up using client/server classes, each with references to the other.
Boss Room is a fully functional co-op multiplayer RPG made with Unity Netcode. It's an educational sample designed to showcase typical Netcode patterns often featured in similar multiplayer games. Players work together to fight Imps and a boss using a click-to-move control model.
had a Q about how you might achieve that, wondering if you might have an idea. The devs mention "use partial classes when separating by context isn't possible". How could you do this without partial classes? Don't networkbehaviors need to have the same signature (ie PlayerController on both client and server, rather than ServerPlayerController on the server and then ClientPlayerController for the client)?
I know it's confusing and probably still overly complex. What they are doing is basically just splitting the classes. The Client classes will have all the clientrpcs and the server classes will have the serverRPCs. Both classes still have to exist in both places, they are just separating the logic not the actual code.
To be honest, if I could understand what they do to facilitate this, it's waaaay clearer to me than stuffing everything in the same class. Monobehaviors tend to get pretty bloated already; failing to separate server/client code is almost certainly a mistake IMO. But I get you, that pretty much answers it for me
Are there any good resources for learning how to setup a very basic lobby/quickplay? The issue I'm having is my network is being initialised on application start. This means that everyone that connects is stuffed into the same server. Ideally, I want the server to always be running, but clients only connect when they're searching for a game. Is this the way to handle it?
Also: I'm aware multiplay has a lobby/matchmaking service that handles a lot of this, but that won't help me learn how they're handling it and I'd like to avoid costs until I'm confident I have a strong enough prototype ready 🙂
You can write your own relay service I guess. But I don't think you'll find any good resources for how to go about that. Same for the lobby system. You would have to make a master server to manage all your lobbies.
damn, was hoping it would be relatively straightforward to scaffold for testing on a local server before moving to a cloud solution. Thanks anyway 🙂
how do games handle this in general? when you're first loaded in, you'll be on a server somewhere, for your account info etc. then when you join a game, what actually happens? is another server spun up just for that lobby?
The Unity Lobby service can be tested that way. The free tier is more than enough
Authentication and account info is usually just a Rest API call. So that can happen before connecting to the game server proper
makes sense. larger games have server-regions that you connect to before/as you boot up the game (EUW, NA etc) - is this just to essentially "lock" your account into a region, so that when you do search for a game, the matchmaking service connects you to a server from a pool of servers in your region? ie you're still not actually connected to a server until you join a lobby?
In Mulitplay for example, your server fleets are tied to a region. They are physically located in those regions. Technically, nothing is stopping anyone from connecting to any region. Just lag will be an issue
The relay service is the same but it will automatically pick the best region for your connection
god that makes so much sense, ty
Lobbies have no concept of region. but that can be added to Lobby data if needed
so really, when clients usually think of a game server being down, to a point where no-one can join a game or even log on sometimes - that wouldn't ever really be 1 individual server that's down. it's more like the whole fleet is offline?
Depends on the type of game. MMOs do have login servers that are a point of failure on launch days.
Sometimes an AWS datacenter catches fire and takes out the entire east coast
same for most major MOBAs or even competitive FPSs - most recently I remember OW2 having a pretty horrendous login queue.
Yea. Live service games are just the new MMO
Not sure why I'm worrying about that - if I've ever got to a point where that's an issue, then I'll be breaking out the champagne lol
have never been very good at taking anything a step at a time
lol, its a good problem to have
if I can't understand it all immediately, I give up
I'm still a little bit lost. Thinking about pretty much any game, once you've been authorised and logged in, you have access to, for example:
- online friends online/offline status
- in game shop
- chat functionality
- account management
some of these are inefficient to rely on a Rest API for - chat functionality for example. So, you're in a server somewhere, before you're actually in a game server. when you do actually enter a game, you still have access to some things that you had before - like chatting to friends that aren't in your game server. how does this kind of thing get handled?
Unity has Vivox which is a separate cloud service from Lobby or Relay. Everything else is indeed an API call. Unity doesn't have friend functionality just yet, though
wow, that shocks me
got to say I'm happy to hear it though, makes sense to me that it's all APIs. my head would have exploded if there was some sort of server-nesting, where you're both in a parent-server able to communicate with other people in your region and in a DGS when you're in a match
thanks again taku
feel like I've learnt more from you in the last couple of days than I have all year lol
I mean technically they are parallel servers just all in the Cloud. Its just that the Chat server, Lobby Server don't know or care about the Game Server.
that's alright, easy enough to separate out into different assemblies
✅ Learn more about Lobby and UGS https://on.unity.com/3XdKEd7
🌍 Get the Project Files https://unitycodemonkey.com/video.php?v=-KDlEBfCBiU
📝 Lobby Docs https://on.unity.com/3OtC0Du
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam G...
hello guys
can anyone help me am trying to make a killer or imposter
i have a list of players photon views
will show you the code now
`
Game Manager Script```cs
using UnityEngine;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
public class MyGameManager : MonoBehaviour
{
PhotonView view1;
private static MyGameManager _instance;
public static MyGameManager Instance { get { return _instance; } }
public List<PhotonView> listOfViews = new List<PhotonView>();
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
}
void Start()
{
view1 = GetComponent<PhotonView>();
Debug.Log(PhotonNetwork.LocalPlayer.NickName);
MakeARandomPersonASus();
}
public void MakeARandomPersonASus()
{
view1.RPC(nameof(ResetKiller), RpcTarget.AllViaServer);
Debug.Log("im in make a random person sus");
int randomInteger = Random.Range(0, MyGameManager.Instance.listOfViews.Count);
Debug.Log(randomInteger + " randomInteger");
//MyGameManager.Instance.listOfViews[randomInteger].GetComponent<controll>().isKiller = true;
// MyGameManager.Instance.listOfViews[randomInteger].GetComponent<controll>().Sword.SetActive(true);
Debug.Log(MyGameManager.Instance.listOfViews);
Debug.Log(MyGameManager.Instance.listOfViews.Count + " players in the list");
Debug.Log("some one is killer now");
view1.RPC(nameof(IamTheKiller), RpcTarget.AllViaServer, randomInteger);
Debug.Log("i did called im am the killer rpc");
}
[PunRPC]
void ResetKiller()
{
foreach (PhotonView id in MyGameManager.Instance.listOfViews)
{
id.GetComponent<controll>().isKiller = false;
id.GetComponent<controll>().Sword.SetActive(false);
Debug.Log("im set to false now");
}
}
[PunRPC]
void IamTheKiller(int randomInteger1)
{
Debug.Log(randomInteger1 + " randomInteger1");
Debug.Log("im in im a killer rpc");
MyGameManager.Instance.listOfViews[randomInteger1].GetComponent<controll>().PrintMyName();
MyGameManager.Instance.listOfViews[randomInteger1].GetComponent<controll>().isKiller = true;
MyGameManager.Instance.listOfViews[randomInteger1].GetComponent<controll>().Sword.SetActive(true);
//MyGameManager.Instance.listOfViews[randomInteger1].GetComponentInChildren<controll>();//.SetActive(true);
}
}
`
This in PlayerScript ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
public class controll : MonoBehaviour
{
PhotonView view;
void Start()
{
view = GetComponent<PhotonView>();
if (!MyGameManager.Instance.listOfViews.Contains(view))
{
MyGameManager.Instance.listOfViews.Add(view);
}
}
void Updater()
{
//Player Controlles just nevermind about it
}
}
and the problem is the killer is random for every player
i cant figure out what is happining it just somtimes everything is random and somtimes it works for every one exept the killer he dont see the sword with him he see it with anyone else
its super random and bad
like this the killers isnt one for all of them i dont know why
photon network issue
when i leave room i cant join back to the lobby
i tried for hours to find out why
there is no help
gameplay:
nvm i found the reason
here is the code, if you have the same problem
PhotonNetwork.LeaveRoom();
PhotonNetwork.Disconnect();
PhotonNetwork.offlineMode = true;
PhotonNetwork.LoadLevel("Main");
but no errors when re-joining room, but it says lobby is still false. photon is so annoying sometimes
oh yeah
public override void OnDisconnectedFromPhoton()
{
PhotonNetwork.offlineMode = true;
SceneManager.LoadScene("Main");
}
this will fix also
can any one help guys
I don't use photon but it looks like your game manager is running on every client so every client gets a different random number. You will need the server to make the only random number and send that to the clients as a network variable.
the gameManger script is only in one object in the map bro
That object is also on every client
yes, but it still exists for every client, and every client is calling MakeARandomPersonASus on Start
if (PhotonNetwork.LocalPlayer.IsMasterClient)
Player script this is in evry player : https://paste.ofcode.org/sNpxadmA4MhFxuMamdmZVy
GameManger script this is only in GameManager Object : https://paste.ofcode.org/VgBvgDhigysPzjCVGb4vcx
and gameManager Object has a photon view btw if its matter
so ho can i make it only one client
should i put if (PhotonNetwork.LocalPlayer.IsMasterClient)
{MakeARandomPersonASus() }
Never touched Photon, and very new to networking - I can't help I'm afraid
No problem
If the master client is the same as the host, yes. But then you have a cheating issue where the host knows the imposter
yeah in this game we are supposst to know the imposter
but he shouldnt know us between bots and npc`s
What I ended up doing is serialize the bare minimum data I needed to reconstitute the player's cards into a string and sending that via a ClientRpc call. The clients then parse that string to rebuild the data on their ends.
Dumping it into json is a bit inefficient but if it works it works. As long as it's not being sent every frame or something crazy it'll be fine
@sharp axle
i think i know the problem but dont sure
i think at the time this function ( MakeARandomPersonASus) called
there were no one in listOfViews and i thinks this is the reason becuase i got a debug.log(listOfViews.Count)
and it print 0
i thought of a solution
that i do this
IEnumerator MakeARandomPersonASusTimer()
{
yield return new WaitForSeconds(1);
if (listOfViews.Count > 1)
{
Debug.Log("dsabasdf");
MakeARandomPersonASus();
}
}
and it just doesnt work and dont really do call MakeARandomPersonASus()
Not even json - lol. Just a delimited string and it's only at startup. Really, the only reason I need to do it at all, as opposed to having each player initialize their own card data, is to make sure the shuffled deck is in the same order on all clients. I supposed I could just send a seed to use when shuffling. Theoretically all the players would end up with the same results in that case.
Once the game is setup I will use events to handle when cards are dragged from one pile to another. This way I can animate the action on each client.
this is the code https://paste.ofcode.org/3aeSQQmySeCtsiZb7s78f5C so you can be in pecture
player controller script https://paste.ofcode.org/sNpxadmA4MhFxuMamdmZVy
https://paste.ofcode.org/GSbuW3MteCGDttxYPus9ug the updated one
if it works it works - similar to how chess engines share state using FEN strings.
Hello guys, i have a simple problem
and its huge for me i spend 3 weeks trying to fix it
i want to randomlly chose imposter
and this killer should have a sword the thing is every player has a sword but its not enabled and if you are the killer its will get enabled for you
and with Photon Rpc it will be public to other players
------------------------------------------------------this is my scripts :
Game Manager Script This script is in empty object with a photon view : || https://paste.ofcode.org/GSbuW3MteCGDttxYPus9ug ||
Player controll Script this script is in every player : ||https://paste.ofcode.org/UTsCWpKSkX6UnYXV4bWUZ3||
i dont really understand the problem
itss just the killer is random for every player
i cant figure out what is happining it just somtimes everything is random, and somtimes it works for every one exept the killer he dont see the sword with him he see it with anyone else
its super random and bad
like this the killers isnt one for all of them i dont know why
-- normal players should know the imposter the sword should be enabled and everyone see it--
I doubt everyone's list of views is in the same order, so just passing the index won't work
I don't use photon but I am sure they have some kind of client id
You would need a dictionary of client ids and players instead of a list
Then you probably didn't do it right...
exactly
hey guys I am confused on how to disconect a client, rn am doing this ```cs
public void Disconnect()
{
NetworkManager.Singleton.Shutdown();
}
void Cleanup()
{
if (NetworkManager.Singleton != null)
{
Destroy(NetworkManager.Singleton.gameObject);
}
}```
but then when I try to get in again I get this
[Lobby]: LobbyConflict, (16003). Message: player is already a member of the lobby
Hey i am new to multiplayer game dev and I wanted to use Netcode for Game Objects for the first time. My question is :
Should I make my new game from scratch and implement Netcode after or should I implement the netcode networking as im making the game ?
You also need to use the Lobby API to remove yourself from the lobby. Or check if you are already joined.
That depends on if you want to make the game once or make the game twice. Adding multiplayer after the fact usually means rewriting most if not all of the code.
Got a Q about lobby service. Docs say that "When a player creates a lobby, they automatically become the host."
Is having the client host a lobby inappropriate? how should you handle this when using a DGS once the game starts? At the moment, I'm doing something like this (for a turn-based 1v1 card game):
- When a player quick plays, they will search for a suitable lobby. If none exists, they will create one.
- If they find a suitable lobby, both players will register as clients and be connected to a server, and the game will start.
With DGS you would probably be using Matchmaking instead of Lobbies. Servers would be the host of a Lobby if you wanted to have like a server browser.
yeah, that's much closer to what I was looking for - thanks again 🙂
are there any examples of NGO being used in separate client/server projects? my gut tells me its impossible - the FAQs mention NGO supporting a dedicated game server model, but suggests that the server build still needs to be the same project as the client build.
I know I've mentioned similar things before, but I'm hopeful I can keep my client and server projects completely separate. I don't want to have any server code exposed on the client build, and the other solutions like code stripping or partial classes all just feel a bit messy
Hey does anyone know about a Netcode for Game Objects TUTORIAL using a DEDICATED SERVER? Every tutorial i found on the internet were using the host-client method but i want to have the game data on a server.
it’s similar to how you would use it in a client-hosted model. you just have to make sure clients are never treated as hosts
some useful stuff:
https://docs-multiplayer.unity3d.com/netcode/current/learn/faq/index.html
The FAQ provides immediate answers for questions collected from the Community on developing games with Multiplayer, including Netcode for GameObjects (Netcode), Transport, and more.
We're finally doing it, we're hosting our own dedicated server on a cloud platform! Now anyone will be able to join, from anywhere in the world.
Digital Ocean provides us with the Linux machine, and we use SSH to connect to it!
If you're new to the whole cloud platform shenanigan, use the same provider I do for clarity, oh and guess what, if y...
There is not much you have to really change.
https://docs-multiplayer.unity3d.com/netcode/current/learn/porting-to-dgs
This is part one of the Porting from client-hosted to dedicated server-hosted series.
It's not impossible. I did it back when it was still MLAPI. But it's super messy. You have to use prefab overrides and manually copy over the prefab hashes. The class names have to be duplicates and the components have to be on the prefabs in the exact same order.
hmm, that does sound like a big pain
Here is the project. It's not gonna compile without some major updates though
https://github.com/MemphisGameDevelopers/Netcode-for-GameObjects-Workshop
I'm confused about when clients/servers should be created. I'm taking a look at the MatchPlay sample (https://docs.unity.com/matchmaker/en/manual/matchmaker-and-multiplay-sample) - and indeed clients/servers are created at launch (see: https://github.com/Unity-Technologies/com.unity.services.samples.matchplay/blob/0225d6c89a5f951350609921607457324d8f847c/Assets/Scripts/Matchplay/ApplicationController.cs#L31).
Do I want this to be the case? I had assumed, with Matchmaker, you would not do this until a game was found.
That matchplay example has a weird bootstrap setup. The server is not actually being run until it gets allocated by Multiplay. Allocation takes a minute or two, so Ideally you would always have at least one extra server running at all times to serve a match.
Hello guys i have a problem
im trying to make a random killer chose
and make this killer has a sword
but the problem is when i enable the sword for the killer its get enabled for everyone in killer view
and it dont get enable for crewMates(the players who are not the killer)
This is my game manager code there is only one game manager in scene https://paste.ofcode.org/SswfZFxnMRSbAp4P7wavCU
The player controll scripts every player has this https://paste.ofcode.org/c33j5yqFtqkwsMPfVwV9ve
right. so from a client perspective, if there is an available server, are they connected to it immediately on game launch? that's what it seems like is happening - but don't you only want to connect clients once matchmaker has found a game, and a DGS is assigned?
That's just he network manager that gets created on launch. Its the matchmaker that will actually connect the client to the server when it finds a match
Hello guys i have a problem
eyo
so i noticed that, in my game, when two players (one host, one normal) are in a game, the host overwrites one of the player's networkvariables, but just that one, its others are completely safe.
the client player, oddly, is completely incapable of modifying that variable, even though it modifies its others just fine
the ones that work are booleans that track certain inputs
the one that doesn't tracks horizontal input
new data: even when the client is the only player (by using a server with no player), it still doesn't register changes to its variable
By default, only the host/server can change network variables
im modifying them with a serverrpc
all my others work just fine that way with default settings
its just the float, not the bools
why would this be happening?
so StartClient and StartServer don't actually have anything to do with connecting a client to a server?
NetworkManager.StartClient/Server does initiate the connection. CreateClient/Server in that singelton does not
🤦♂️
feel like an idiot, ty
lol, a lot of the Unity Samples feel overengineered
is there any difference between float networkvars and bools?
thats the only thing i can identify
Not in NGO
tell me about it. going through boss room and seeing that they used facades for all of the unity services really tripped me up. Like, the service itself is pretty high-level lol
NGO?
Netcode for Game Objects
oh
i don't understand then why a client can modify bool networkvars but can't modify floats
they're the exact same
default settings
in the same serverrpc
made with the same constructor for networkvar
here:
using UnityEngine;
using Unity.Netcode;
public class WASDMovement : NetworkBehaviour
{
public NetworkVariable<bool> Example1
public NetworkVariable<float> Example2;
void Update()
{
ExampleServerRpc();
}
[ServerRpc]
void ExampleServerRpc()
{
Example1 = false; ///Works just fine
Example2++; ///Doesn't work
}
}
only difference is that the bools are modded in a switch case
¯_(ツ)_/¯
What's the error? Example2 is a string
whoops
nice catch
but the error is that example2 aint changing
i debug.log its value
and it returns 0
alright
an hour of debugging later
turns out
the reason that my other network vars work
is because they don't
seriously
i found a bug in netcode
the crap aint working like it should
it doesn't even register the variables as true
even though they 'act' like they're true
and sometimes it just doesn't work at all
so yeah
ima need to rework some stuff
You should be modifying Example.Value. Changing Example directly should be working at all
If you can replicate that in a empty scene then submit a bug report here
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/new/choose
shiet ok ty
what i had was that i had a new NetworkVariable<float>(x)
but ig that shouldn't be workin
Hello guys i maked a sword and put this code in it https://paste.ofcode.org/jjUepY2XfSGiPJcVeMPhWN
but when i hit any thing with bot tag nothing happen not even the debug i put
That should only be done on the server, yea
damn
so you can't do that in a serverrpc, right?
Those run on the server but that's not where you initialize network variables. That's only done when they are declared
Hello guys i maked a sword and put this
why is the float not proccing?
Does anyone have any idea if the Steam sdk lets you use their peer to peer network without having a steamworks account ?
if Example2.Value++ isn't working then thats a bug and should be reported
i dont imagine so
so why would that be?
if your serverRPC is not running on the server then thats a different issue
let me give you the rundown then, i may be misunderstanding
basically
the player has bools tracking its WASD movement
when you push/let go of one of the keys, the corresponding bool is toggled
this is done with a serverrpc, modifying the player's set of 4 bools + the spacebar bool
ty everyone <3
I have some events (System.Action's) that I want to trigger cross network. Currently I stick these in ClientRpcs and trigger them each locally, but I have found the need to trigger one in the midst of a serverRPC. What's the preferred way to Invoke events on clients from within a server call?
Basically, you should treat a RPC as an event firing off. If you need a return value of some kind they you send the corresponding RPC back to the source.
am I to take that as the proper way is to have something like *TriggerMyEvent_ClientRpc() => MyEvent?.Invoke() * (along with whatever args you may need) that you trigger from within some server-side block?
Thats the way I would do it
ty
Is there a way to test Matchmaker integration locally? It's tedious having to deploy new builds to Multiplay every change
There was parrellsync for older versions of unity.. Not sure about updated versions though.
there are Docker container builds that can automate things a bit but there is no way to test allocations locally
https://docs.unity.com/game-server-hosting/en/manual/concepts/container-builds
I use parrelsync, but Matchmaker docs mention specifically needing a Multiplay-hosted DGS to spin up when a match is found
Damn, was hoping there would be a way to tell Matchmaker to point to a booted up local server
Matchmaker with Relay is on the roadmap I believe
heyae
*heya
im bacc lol
was wondering why rigidbody2ds don't work on network
they just allow clipping
There are many different ways to do physics in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server authoritative physics where the physics simulation is only run on the server. To enable network physics add a NetworkRigidbody component to your object.
Hello, I'm using mirror and I'm getting an error like 4 mins in on the tutorial
Does anyone know how to fix those errors
Do you have some transport on the NetworkManager gameobject? They are usually separate components
Mirror discord server should be able to help you better
It says UnityTransport could not be found even though it is a component of the network manager object.
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(
allocation.RelayServer.IpV4,
(ushort) allocation.RelayServer.Port,
allocation.AllocationIdBytes,
allocation.Key,
allocation.ConnectionData
);
Here are the directives:
using System.Collections;
using System.Collections.Generic;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Relay;
using Unity.Services.Relay.Models;
using Unity.Netcode;
using UnityEngine;
I am really confused..
You are missing the Transport directives
https://docs.unity.com/relay/en/manual/relay-and-ngo#Import_the_requirements
what @sharp axle said. Also, just FYI for the future - any "type or namespace name" errors won't have anything to do with whether or not a component exists. That would always be a NullReferenceException
Hi!
So I decided to get multi-player going using Photon Fusion, the goal is to get a single server going.
Ny game is in super early prototype, so I don't see a massive problem going forward, I just need to re-write the code it seems.
Are there any rules as to how to proceed this?
Should networked items (players, intractable objects, etc) only contact the non-networked items, like ui/hud, static objects.
Any push in the right direction would be greatly appreciated, I just need some general rules 🙂
I got networking working, player movement and such work, but the issues comes as soon as a 2nd player joins, and the game start sending information between the player(s) and the ui/intractable objects
There are no real rules. It all depends on your game design. Are you going Server Authoritative or Client based? Are you worried about possible cheating?
Server, I was thinking of renting a small server
Photon Fusion is free up to 20 players at the same time, 16 people on a server i believe, so I was thinking of just renting a server and have it available for testing
I'm a fast learner, but don't know where to start, started looking into it yesterday, so would be awesome with a push in the right direction so I know where to look 🙂
This series is a good resource if you're looking to learn about server-authoritative architecture. It won't help with anything Unity/Photon specific, but if you're just looking to build your understanding, I would recommend.
https://www.gabrielgambetta.com/client-server-game-architecture.html
Thank you very much! That is exactly what im looking for, gain enough understanding to experiment
If you're designing anything competitive, server-authoritative is the way to go, and in general (at least to me) feels like a much smarter way to handle networking.
disclaimer: I have also only just started, so don't take my word for anything - @sharp axle is the resident expert when it comes to pretty much anything networking ^^'
I see, I'm not making anything competitive, server-authoritative just sounds better, but might not be the best for me.
I'm making a valheim/rust type multi-player, so it's not really competitive, but more chill
If that makes any sense
In that case, these are useful links for understanding the differences between DGS (dedicated server), listen servers (client-hosted), and P2P.
https://unity.com/how-to/intro-to-network-server-models
https://www.youtube.com/watch?app=desktop&v=YbIeN3CYr_M
Peer-to-peer (P2P) and dedicated game server (DGS) models are both popular choices for hosting your game server. But which one is right for you?
Disclaimer: “Peer-to-peer” can be interpreted in different ways and can reference the hosting model or the replication model. This discussion is about hosting and, in this context, it can be called “c...
Again, thank you, these are the resources I've been looking for.
I've heard those terms but never thought about it, I'll look into it later today!
this will help you out as well
https://docs-multiplayer.unity3d.com/netcode/current/reference/glossary/high-level-terminology
Learn more about essential terms and concepts.
Love it, I almost didn't ask for help, very glad I did!
Thank you!
I focus on Unity Netcode but most of the concepts are the same across most of the popular frameworks like Photon and Mirror
The reason I picket photon was because it was the main thing people picket, would you recommend Unity Netcode over photon?
It just seemed that people overall agreed that photon worked the best
Unity Netcode is still very new but its supported directly by Unity. Photon has a wider user base so more tutorials currently. Photon also has a few more features out of the box like client prediction but not anything that can't be done in NGO.
I see, so would you personally recommend it? I don't have enough experience to know if predictions is something I need for my game, I know the basics of it though
It's the one I use so I guess I'd be foolish not to recommend it
Fair point haha, I'll look into it. Is it similar with photon, in how I can essentially have a free 20 person server?
~~There are not hard caps in NGO Relay or Lobby. ~~ There is a limit of 100 players per relay/lobby. The free tier is avg of 50 CCU per month. If you are just connecting locally there is no fees at all
Unity Netcode it is!
Hi all,
So, I'm playing around with Netcode, and hitting something of a snag with Network Variables. I'm making a very simple tank vs tank game to try everything out and us as a learning experience.
At the moment I'm trying to get a scoring manager to work.
Here is the code I'm using, I'm sure I'm doing something really simple and silly wrong, but I can't see it.
`using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
public class ScoringManager : NetworkBehaviour
{
private NetworkVariable<int> playerOneScore = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<int> playerTwoScore = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public Text txtPlayerOneScore;
public Text txtPlayerTwoScore;
public override void OnNetworkSpawn()
{
txtPlayerOneScore.text = playerOneScore.Value.ToString();
txtPlayerTwoScore.text = playerTwoScore.Value.ToString();
playerOneScore.OnValueChanged += (int previousValue1, int newValue1) =>
{
txtPlayerOneScore.text = playerOneScore.Value.ToString();
};
playerTwoScore.OnValueChanged += (int previousValue2, int newValue2) =>
{
txtPlayerTwoScore.text = playerTwoScore.Value.ToString();
};
}
// Update is called once per frame
void Update()
{
if (!IsOwner) return;
if (Input.GetKeyDown(KeyCode.E))
{
playerOneScore.Value++;
}
if (Input.GetKeyDown(KeyCode.R))
{
playerTwoScore.Value++;
}
}
}`
At the moment I'm 'manually' increasing the scores with keypresses. The score sync over the networking just fine and update the score counters.
The problem is, I can only increase the scores on the 'Host' version of the game.....(cont)
.......And not the client. It behaves as though the keypresses aren't recognised on the client game.
Anyone have any ideas? 😕
NetworkVariables can only be written to by the owner. I believe this is default behaviour, but you’ve also explicitly added it (NetworkVariableWritePermission.Owner). If you threw a debug log in your key presses, you’ll see it come through - the issue isn’t that the key presses aren’t recognised by the client, it’s that the client isn’t allowed to write to the variable
Aaah okay, I think I understand that part. I think I've been misunderstanding the 'owner' part (thinking it was a local thing, whereas if I understand correctly now, the host will always be the owner as it's the first game to start and declare the variable?) Think it's my own fault for skipping ahead in the vid I'm following. lol. I'm guessing an RPC will be needed to write to it (that's a bit later in the video. lol.)
Yep the server/host will own everything not explicitly assigned to the client. A serverRPC would be needed to update the score in that case. But that should really be done on the server
Gotcha, thanks fellas 🙂
@sharp axle could you walk me through something on the Matchplay sample project? (https://github.com/Unity-Technologies/com.unity.services.samples.matchplay/blob/master/Assets/Scripts/Matchplay/Server/ServerGameManager.cs)
StartGameServerAsync (line 45) is hit from the bootStrap scene on app start. There is a comment that addresses a problem I mentioned yesterday - testing matchmaker locally/not through a Multiplay hosted server. I don't really understand how it's doing that - it seems to just skip initialising Matchmaker, but the rest of the application is still dependant on it?
walk me through something on the Matchplay sample project?
Hi guys, I receive this error in the client (and not in the host for some weird reasons) when the client connects to the host.. but I literally have 0 prefabs spawned in the scene when the client is connected to the host
Sounds like you might have an in scene network object that's causing that error
I have only a network object in the scene which is the Relay (that I use to connect the client to the host with a join code so that they can play together) and I don't understand how it could cause an error
The Relay script loads the "Game" scene for both the host and the client when a client inserts the join code (it's a 1v1 game)
And does that calling a ClientRpc to unload the current scene and load that
Ok I've put a DontDestroyOnLoad on the Relay script, and now it gives me an error like that but with another hash
And for some weird reasons the relay is destroyed on the client (which is the one that gives me the error)
The Relay has a reference to other objects.. do those objects also need to be NetworkObjects? (they're just a button and the text field where the user inserts the join code)
The hash code that's in the error is the same as the Relay's one..
I mean the relay is not a prefab.. wtf
Ok I had to also put the Relay inside the network prefab list of the network manager (even though it is not a prefab)
But now the relay is destroyed when I change the scene even though I put a DontDestroyOnLoad on it
Is there any way to spawn a network prefab from a ScriptableObject?
Nah, Scriptable Objects are just data containers. They can only be referenced in scripts.
Well I am using them to avoid using singletons
I am getting this warning when I run this function, idk what the warning means.
public async void CreateRelay()
{
try
{
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(49);
string JoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
Debug.Log(JoinCode);
HostID.GetComponent<Text>().text = "ALPHA V0.1 - HC: " + JoinCode;
NetworkManager.Singleton.GetComponent<UnityTransport>().SetHostRelayData(
allocation.RelayServer.IpV4,
(ushort) allocation.RelayServer.Port,
allocation.AllocationIdBytes,
allocation.Key,
allocation.ConnectionData
);
NetworkManager.Singleton.StartHost();
}
catch (RelayServiceException Error)
{
Debug.Log(Error);
}
}
Sounds like you need to activate the Relay service in the Unity Dashboard
Thanks, it was off, I remember very clearly turning it on but I guess it didn't save.
I'm using a cinemachine camera in my 3rd person throwing type game, except when I have 2 players, they both only look through that one camera. How would I go about fixing this?
You need to make sure the camera is disabled on the remote player objects. Here is how they did it in the Unity Sample
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/d37c360bc8cdbbbf680e2afc5963571e20f28ffd/Basic/ClientDriven/Assets/Scripts/ClientPlayerMove.cs
Hello, I'm not really good at english so sorry first,
I'm using Photon and I can't give a nickname to player.
This code gives NullReferenceExpection error. I'm sure the object which has this code has Photon View component. What can be reason?
GetComponent<PhotonView>().Owner.NickName = "player1";
User connects to master, lobby and room before this.
Mornin!
I'm working on Netcoding, and got a question about cameras, each player should have a camera, but how do i correctly assign a camera to a single player?
Should each player object have a camera? Should there be one MainCamera in the scene?
I prefer to have only one camera that the local player gets injected, others put a cam on every player and disable them for all but the local one. It’s your choice.
So the logic would be, if owner, grab the main camera, if not owner, create your own camera?
Yes, either create or activate
Got it, my camera got a few scripts etc attached, so could I also in theory attach a camera to each player and deactivate it, when the player spawns, grab your own camera and activate it?
That works too, it’s just more wasteful in terms of having copies of unused stuff
Fair
Thank you for your answer! I'll give it a look 😄
Or, what if I create a camera prefab with all my things on it, and then instantiate that camera when the player spawns? Would that be the same as having the camera on every player?
That would be similar to grabbing the main camera. Architecturally it’s best to have the player spawning system inject the camera into the player system or to inject the player into the camera system, keeping this entire logic outside of either one
I see, ok thanks!
I've tried to google a bit but got no real answer, could you be a bit more specific on what this entails? or link me in the right direction?
Check out the link I posted yesterday. This is how a Unity sample uses the 3rd person controller and cinemachine. When players spawn in they disable the controller and do not assign the camera follow script
Will do, thanks!
I got that working, and all characters move with their own camera and such as I want, perfect!
Let me just make sure I got the right idea as to what is going on.
When the player spawns, it disabled both the controls and collider.
Then in OnNetworkSpawn it activates my controls if that player is the client (the one controller the player that spawned), then if the player is NOT the owner, it will disable the controls (??), the character controller, but activate the collider.
If however, the player is the owner of the player spawned, it will enable the controls, set the cinemachine follow to the right target (which in my case is an empty on the player character).
The whole SetSpawnClientRPC thing I don't really get
Yea that's correct. Don't worry about the clientRPC, it's just for resetting the player position by the server. You can ignore that.
Got it, thank you a lot!
I hope you (and others) don't mind if a ask a bit of questions as I encounter them, I always try to solve and figure it out before asking 🙂
.
I don't use photon but error usually means that get component returned null
Actually the Owner returned null
I would look at the Photon docs, specifically for PhotonView, and see if it says where the owner is populated/why it might be null
I got character customization in my game, what is a good way to synchronize what the player is wearing?
The players has modular components where only 1 is active at a time
Changing on one client will change the other player aswell
I got a list over the active items, so if there's a way for me to send that list to the server, that would be great
But from what I've read about NetworkVariable, i cant really do that
NetworkList?
Yea. you wont be able to use a list of gameobjects. I would use a list of indexes of the active objects
I see, so a list of indexes that gets syncronized, that list will be read by each player in the session and activate/deactive the item accordingly?
right
And just to make sure.
Let's say I got 3 players, player 1, 2 and 3.
Player 2 changes hair from index 1 to index 2.
When player 2 saves changes, a call or whatever will tell player 1, 2 and 3 on the server that something changed, and that something should be updated.
Player 2 might send their ID to tell the others that they did a chance?
Then player 1 and 3 will then run a method on Player 2 gameobject that will activate/deactive the changes?
Or am i completely off?
If you use a networklist then you can subscribe to that players networklist.onchangeevent(). Probably some kind of manager class is needed if player can change themselves on the fly
I see, I'll take a look at it later on, gotta make some dinner and stuff!
Thank you for your answers 🙂
Hello brothers
can i stream and receive Renderer.material of objects in OnPhotonSerializeView?
and if i can how, what is the code i should put
for example any game object state
can be streamed with ---> stream.SendNext(GameObject.activeSelf);
And readed by --> GameObject.SetActive((bool)stream.ReceiveNext());
I Mean Materials like colors
why am i even explaining that
I don't know about Photon specifically. But Materials are not serialized. You should be able to send just a Color then apply it locally
I want to change the t shirt color by pressing button
And i want to send the new color to other clients
Will it change for all because i didnt test it yet
.
You would need to send the new color to every client
how
rpc?
rpc as what i know will make all the clients have that color not only send it
So, I figured how the Client (people joining server) can change their look and it will update for everyone. the server/host only
But how can I do the same change when the host does the change?
_allChildObjects is a 800 long list with every possible modular piece of my character (Should probably turn this into a Scriptable Object), ActivateItem(GameObject) will take that GameObject, figure out where it fits in and deactivated the old one, and activates the new
From my understanding, ClientRpc is a call/message or whatever, sent from the client (player who joined) to the server (player who first joined/The host of the server).
ServerRpc should sent a class/message FROM the server (first player/the host) to every client, but this does not work, and I'm not sure why
the serverRPC needs to call the clientRPC to broadcast out to the clients
You could also make the int[] into a NetworkList and give the client authority over it
That would save on bandwidth as only list changes would be sent
So in the picture above, ServerRpc should call the CleintRpc?
So when I do a change, on any or the clients, a ClientRpc should call ServerRpc, which will then call every ClientRpc?
It's getting late, and I'm running out of steam for today, so my brain ain't working right, so sorry if it's super obvious x)
the first part is right.
Yea I'm gonna continue tomorrow, my brain is fried lmao
Thank you so far, got a lot done today!
Oh, that reminds me, is it possible to spawn your own character prefab?
As in, what if I have a scene that allows the player to modify their player prefab, then when they join a server, what the player created in the menu will be used?
I imagine I can just customize a character how I like and spawn it like it is
Players won't be able to customize in game, but that's fine
nope. only the server can Spawn objects
Oh well...
I guess I can just force the player into a one-time character creation when they join a server
I'll just re-write how my customization work to be more multiplayer friendly overall
I got the most important part working like I imagined, the player customization ain't the most important thing now
hey guys after starting the network manager host can I change it to another player if the original host disconnects?
No, when the host disconnects it the entire session ends with it. If you were using the Lobby service a new lobby host is assigned and they could start a new game.
ah ok so the aproach is: go back to the lobby and the new apointed lobby master can start hosting
is this correct?
right
btw I am trying to see how can I kick a player from the game from the lobby, the player id has a diferent Id from the network manager id, is the best aproach the host send a RPC message to the client with the same lobby id to disconect?
I am pretty sure if the integration is setup correctly, if the player leaves the Lobby they will also leave the Relay. I know it works the other way around. The integration is supposed to sync the Relay and Lobby connections
ok thanks for the input
Proper noob Q - the NetworkManager forces clients to load the scene the server is in on connect. Is it desirable to turn this off? I've been debating it, since for most of the user's journey up until they get into a game, I've currently kept my server in an Init scene rather than matching the client's scene.
Really depends on how much you want to babysit Scene Management. There no wrong answers here
It won't let me post Discord links but there is also a Server dedicate to Netcode for GameObjects.
I think I prefer just making the method calls when I need to change scene. Please DM me the server dedicated to NGO, would love to join 🙂
Full Disclosure: I'm a mod there
why would that need to be disclosed? 👀
I dunno. It kinda feels like self promotion. or something
does firebase firestore follow the first set of rules (realtime database) or the second (storage) , I think its the second
https://www.youtube.com/watch?v=PUBnlbjZFAI
All data stored in Firebase is by default readable and writable by any authenticated user. While this is great for getting started, productions apps require stronger security. Thankfully, Firebase has your back with Security Rules. They provide a declarative way to specify who can access certain data and what schema that data should have. Take a...