#archived-networking
1 messages · Page 34 of 1
this is only in the scene, the game looks normal
is there any way to deactivate this?
How much work is it to convert SP game into MP with NGO? Should I start with MP right away?
Yes
This is part of the Multiplayer Tools. You an find it under Windows -> Multiplayer -> Multiplayer Tools
Hello all. Using NGO, What's the proper way of handling the GameObject with the Network Manager Component on it?
It lives on the start menu and I guess internally it is already set for DDOL. But every time moving back to Start menu, it spawns a duplicate.
I usually destroy the NetworkManager when disconnected from it and when done using it. Allowing the new one in the Start Menu to be used when loading back to that scene.
Cool, ill destroy in my activity manager class when calling GoToStartMenu. I was just not sure if there would be any issues by not using the original one spawned from any kind of initializations internally to the script. But good to know it doesn't matter.
All the initializations will be ran again by the new one
The other alternative is having an empty bootstrap scene with the network manager automatically switching to the main menu. Then you can always switch back to the main menu without duplicating or destroying things
I ended up just creating the network manager on a prefab and a script on my start menu just checks to see if the singleton is not null and spawns if it is. I tried the startup scene(that only has the network manager GO on it) route that goes directly to start menu at launch , but i hate that work flow.
Does Firebase Analytics events show up immediately after being called or they take time?
Like this one
EventCall("ABC Game " + Levels.ToString());
void EventCall(string eventToCall)
{
try
{
FirebaseAnalytics.LogEvent(eventToCall);
}
catch (Exception e)
{
print(e.ToString());
}
}
The docs say
You can view aggregated statistics about your events in the Firebase console dashboards. These dashboards update periodically throughout the day.
https://firebase.google.com/docs/analytics/events?platform=ios#view_events_in_the_dashboard
easiest way is to have a scene just for game launch. When the game starts it opens this scene before anything else. That's where I find out if the user is a client or server, then it loads the main menu
Another question about distributed auth and NGO with WebGL.
I have this function that runs fine on the MacOS or PC. But when I build for WebGL it does not.
Basically the Debug.Log($"ServicesHelper: Before CreateOrJoin"); Gets printed but the Debug.Log($"ServicesHelper: After CreateOrJoin - Success"); Never does. and also none of the catch messages. And the code never gets to Debug.Log($"ServicesHelper: Session created/joined successfully. Players: {m_CurrentSession.Players.Count}");.
async Task ConnectThroughLiveService(string sessionName)
{
Debug.Log("ServicesHelper: ConnectThroughLiveService - Starting");
try
{
var options = new SessionOptions()
{
Name = sessionName,
MaxPlayers = 4,
IsPrivate = false,
}.WithDistributedAuthorityNetwork();
Debug.Log($"ServicesHelper: Before CreateOrJoin");
// Specific try-catch for the CreateOrJoin operation
try
{
m_CurrentSession = await MultiplayerService.Instance.CreateOrJoinSessionAsync(sessionName, options);
Debug.Log($"ServicesHelper: After CreateOrJoin - Success");
}
catch (Exception createJoinEx)
{
Debug.LogError($"ServicesHelper: CreateOrJoin specific error: {createJoinEx.Message}");
Debug.LogError($"ServicesHelper: CreateOrJoin stack trace: {createJoinEx.StackTrace}");
// Also log the status of MultiplayerService
Debug.LogError("ServicesHelper: MultiplayerService connection failed");
Debug.LogError($"ServicesHelper: Is Authentication signed in: {AuthenticationService.Instance?.IsSignedIn}");
throw;
}
Debug.Log($"ServicesHelper: Session created/joined successfully. Players: {m_CurrentSession.Players.Count}");
m_CurrentSession.RemovedFromSession += RemovedFromSession;
m_CurrentSession.StateChanged += CurrentSessionOnStateChanged;
}
catch (Exception e)
{
Debug.LogError($"ServicesHelper: Failed to connect: {e.Message}");
Debug.LogError($"ServicesHelper: Stack trace: {e.StackTrace}");
throw;
}
}
Does anyone know a good system and tutorial for p2p networking
(Im using p2p because I can't afford to host a server for connection)
NetCode for GameObjects is Unity's official networking solution but it's server-authoritative (meaning one client acts as a "server" for people to talk to). The only downside is that if the host or the "server" disconnects then everybody will leave and so host migration isn't exactly a thing
But Unity has another service called Lobby you could pair with NetCode for GameObjects which would let players host lobbies (duh) and you can tell the lobby to swap hosts and then you could manage connecting to the new host yourself (lobby is INCREDIBLY cheap and it would take tens of thousands of players constantly joining and leaving lobbies to even cost you less than $1)
That could work yes. I could have a warning before the host leaves to tell them if they disconnect it will end everyones game, and have a system for if a host consistantly leaves when hosting then they are banned from hosting the games
Awesome then yeah I would recommend NetCode for GameObjects!! Code Monkey goes over it pretty well as he does with everything else. Incredibly useful channel
Yeah ive seen that channel. Thanks for the help
No worries good luck!
Cheers
The easy way is to use that objects OnNetworkSpawn() that will get called on all the clients
You could also send the NetworkObjectReference in an RPC if you want
Brief explanation on using NetworkObject and NetworkBehaviour in Network for GameObjects
Thanks! but i stuck to find out OnNetworkSpawn() in getting value of OwnerClientId. it just 0
how to use that function
that Debug.Log just print on server side
result is here
Any in-scene NetworkObjects are owned by the server by default - meaning an OwnerClientId of 0
If you want the OwnerClientId of the PlayerObject through OnNetworkSpawn, you would use OnNetworkSpawn on a script on the player object itself - not in PlayerSpawn which I assume is an in-scene NetworkObject
You want to use NetworkManager.Singleton.LocalClientId instead of OwnerClientId
Anyone using Photon Fusion 2 can tell me if Mono Celi is still required? i get conflicting information on the web but the doc no longer reference it
Oh thank you ill try
Hello, I have a question about Unity6's Multiplayer play mode. If you do something that requires scene loading in a newly opened virtual scene, Build Profile will tell you to set the scene or many game objects will be missing. Is it a bug? Is there a way to fix it yet?
Based on 1.4.0-pre.1, the latest version of multiplayer mode, clicking the original Unity Editor during SceneLoad of the virtual scene causes the Build Profile to specify a scene.
This is happening during scene reload?
That's right. When I'm loading a scene in MPPM's Game View, and I click on the Unity Editor when the scene load is not complete, I get a warning that Scene Setting in Build Profile is required.
can i get photon help here..?
Maybe? Photon has their own Discord server though
Im not sure what IP to do here if I want it to work anywhere
for example someone from USA and UK connecting to host in Germany
You would a Relay service for this. or you can set up port forwarding for the host (not recommended)
hang on so the address is for the relay server?
ah
Im still a bit confused
what do I change for this?
im using netcode
@weak plinth these are your options here. You won't be able to change anything in there on its own to enable online play.
Unity's Relay service can be read about here: https://docs.unity.com/ugs/manual/relay/manual/introduction
ok, but Im still not sure what to do with it. since I set that thing up but do I change the protocol type or what?
im new so please be patient
The manual has samples and start up guides:
https://docs.unity.com/ugs/en-us/manual/relay/manual/get-started
https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo
Hello, I'm trying to use WebRTC in Unity I'm not sure whats happening but I can only receive one frame and then I don't receive anything else
I was wondering if anyone had a similar issue?
If I receive the video stream on my browser I'm able to see the entire video stream
Are you using the webRtc package?
https://docs.unity3d.com/Packages/com.unity.webrtc@3.0/manual/videostreaming.html
Hi ! I am using the Unity Relay Service and I am trying to also implement a LAN solution for my game, but for that I need to change the Protocol Type in the Unity Transport component of the NetworkMaganer from "Unity Transport" to "Relay Unity Transport", and vice-versa. I know you can change dynamicly to "Unity Transport" by changing the SetConnectionData (like stated in this post : https://discussions.unity.com/t/how-to-set-protocol-type/924171/2), but is it possible to do the opposite and change to "Relay Unity Transport" ?
Hey guys I’m trying to figure out how to setup my first person shooting mechanics in a multiplayer setting. I’m wondering how to make the pov from a second player accurate to what the first player sees on their first person rendered pov. (Making the player model and first person model accurate to eachother). And how I can hide a players own model from their own pov, while also being able to see other player’s player models. I’ve run into a problem where the player models are all on one layer that the first person camera blocks through culling mask.
I’m also curious of how to create a first person pov haha, making the full player model took me a lot of time on its own, and trying to replicate the arms, and then any equipment on the arms during runtime might be kindof difficult
The easy way is with the Multiplayer Services SDK
https://docs.unity.com/ugs/en-us/manual/mps-sdk/manual/create-session#Type_of_network_connection
You can change the layer of just the local player model so only it gets culled
How do you make the layer only local?
I think the standard is to have a separate fps model that is loaded for the local player while the remote players use regular model
I see, that’s what I imagined, it’s going to take me a lot of time to figure out how to get all the weapons and equipment to stick to the player model and first person model correctly 😂
I will have to Create two seperate animations for every single weapon AHHH
And I’ll have to learn how to actually make a first person pov with the arms and legs lol
In OnNetworkSpawn(), check for isLocalPlayer then set it's gameObject.layer
Thankyou sir
This is great ! but I'm also trying to change the protocol type so I don't have to connect the Relay every time I'm doing testing using my own computer with the Multiplayer Play Mode. So is it possible to change from one another protocol type by script ?
You can kinda see how Opsive does it here
https://opsive.com/support/documentation/ultimate-character-controller/camera/view-types/included-view-types/first-person/
You can just change the session options before you connect
Dude Thankyou
Typically in games the first person pov is just the arms of the model, its a much easier solution unless you really want the player to be able to see their feet
The game must have feet.
Some first person shooters like Apex Legends don’t have body parts other than arms and hands. They have no torso, legs, or feet or head. You could have a completely invisible body that casts a shadow on the ground and then add arms and hands in front of a second camera that is rendered over the main camera view. Halo does it, it looks strange when you get up against a wall, but the hands never clip into the wall- you always see them.
Halo has feet but it’s a real effort to position the camera to look down, see the feet, but not have the torso in the way.
Halo’s camera is not at the eyes. And you don’t want them attached to the body. You want the camera attached to the capsule.
I will probably take this approach for now because it seems to be the easiest, but ideally I would want the playuer to be able to see what action their feet are in, for the sake of scaling objects and stuff. What comes to mind for me when I think about a good example for first person view that I would like is, Dark and Darker
private void OnNetworkInstantiate(){
if (IsClient){
GameObject playerModelObject = gameObject.transform.Find("PlayerModel").gameObject;
searchTree(playerModelObject);
}
}
// Recursive method used to search through child objects.
private void searchTree(GameObject node){
int i = 0;
while (node != null){
node.layer = 6;
node = node.transform.GetChild(i).gameObject;
searchTree(node);
i++;
}
}``` My attempt at what you said, not working for osm reason, maybe because im starting the game as a host?
What about that is not working?
OnNetworkInstantiate() is not being called, or for some reason IsClient is false
Im using netcode for gameobjects, and joining by selecting start host
does OnNetworkInstantiate() go after start or update or something? Im not sure if that would affect it being executed or not?
It's OnNetworkSpawn()
public override void OnNetworkSpawn() { }
int i = 0;
while (node != null){
Debug.Log(node.name);
node.layer = 6;
node = node.transform.GetChild(i).gameObject;
i++;
searchTree(node);
}
} ``` apparently an empty GetChild() doesnt return a null?
There's no such thing as an empty child in that context of GetChild(). Either there's a child GameObject at that index, or there isn't or you'll get an index out of bounds error.
ah I see, its an array not a list
thankyou, and that override keyword made that function work, I appreciate it man!
np
Wouldn't make a difference
well if it was a list, the next spot reserved for another object would be null, if it was empty
wheres in an array its out of bounds error
in the context of GetChild() there will never be an empty. There are only as many elements as there are children GameObjects.
kk
Hi friends, I am trying to make a multiplayer game but there are always two players controlling each player I want to make something different like there is only one reward wheel I want it to be controlled by both players turn by turn. For example, first player A turns the wheel, and player B just sees and then player B spins the wheel, and player A sees.
You'll need to make some kind of turn manager that will disable the input when it not the player's turn
@sharp axle how can i do this phone pun2
It's not a networking thing. Just a variable for turn number. When it's not the player's turn you can make all the button.interactable = false
oh no i want it to make multiplayer this same screen shows on both players deveice but at a time only one player can spin the wheen
Any suggestions on best tutorial video on websockets.
You'll probably have to narrow it down. Do you want to use netcode for gameonjects with websockets?
Ngo concept and anything. I am new to websockets now and one company told me to learn websockets within 2 days.
I feel like am missing something obvious, but I'm going through the Boss Room sample project learning about relay/lobby, but I keep running into issues in my own project with errors about classes and methods existing in two packages like The type 'Allocation' exists in both 'Unity.Services.Multiplayer, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Unity.Services.Relay, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' but I see both of these packages in the Boss Room project as well without any issue. Does anyone have any idea what the difference could be I could look into?
I've also tried just removing the Relay package to see if that fixes it, but then other errors show up that need that package, so I am currently stuck.
Same thing happens with Multiplayer and the Lobby packages, even though that one is also used in the sample project.
I managed to use the upgrade guide to get these issues fixed, but I am still curious why this isn't necessary in the sample if anyone knows.
Boss Room was make way before the Multiplayer Services SDK existed and hasn't been updated for it yet. I don't think Boss Room is a very good learning project in any case.
Hi guys i been creating a unit combat system like this. When trigger the attack behaviour will start by create a collider to check all the unit in side, and then search for valid target, it will then call a function from the target health behaviour script to reduce the amount of attack token, if the attack token is > 0 then it will sync the target to client and network, subscribe it change target function to target death event, then move to target, then after reached the destination, it will start attacking it's target. And if the target died, it will trigger the event to change the target. The problem is when changing the target, sometime it got a very weird interaction that will prevent the attacker to regain attack token if it's being targeted by another unit. I know it's a very complicated thing to describe, but i hope to get some help from u guys. TY ! 
I've been trying to fix it for week, but sadly still cant understand what's causing the problem
sounds like this is NPC behavior and probably shouldn't be networked at all. But I would have Health and the Attack Token be network Variables if they are needed for client side UI.
thank u man, i will double check.
What makes you say its not a good learning project, and what would you recommend in its place?
Its way too complicated. I would argue overengineered. The Multiplayer Services SDK and Widgets makes all of that kinda trivial.
Widgets do currently lack customization but I hear that is coming
Is there a sample project that has these showcased? I can see the documentation, but I can get a better understanding having a visual project I can run side by side.
If you are on Unity 6, the Multiplayer Center has a Quickstart section with some built in samples
I feel it was too easy to be led down an old deprecated path, especially with the multiplayer sdk essentially swallowing relay and lobby. I agree that the Boss Room prroject was surprisingly high grade for a sample and certainly didn't expect to see dependency injection lol, but I was able to tear through it to understand it and at least had something to work against. Maybe that will serve me well as I change approaches yet again lol
Hi! So I am still pretty new to networking and ran into some issues regarding certain networking methods in Fishnet running twice on the host player as the server and client side is being handled by the same game instance.
I was recommended to separate out the server and client. I had some questions about this.
What are your thoughts on this method?
This would still be peer-to-peer right as the server is still on one of the client's computers (I wouldn't need a dedicated server when eventually shipping the game)?
Additionally, when testing this I would need to create an additional game instance to act as the server, how would this work in a shipped game where you would only be able to run one instance of the game?
I don't use fishnet, but usually you will run a check on the host to make sure things like movement is not happening twice for the host client. There is no need have a separate server instance running if you are having clients host.
Oh ya it's nothing like that pretty much there are methods such as OnLoadEnd or OnActiveSceneSet that runs on the server and all clients for syncing purposes and as a result triggers twice on the host and I've been having a little trouble regarding the checks.
For something like that I would have the first line of those be along the lines of if(IsServer) return;
Ya I tried that. The issue is that OnLoadEnd runs when a scene has finished loading and I am using in on the local object pooling system to instantiate certain pools depending on the scene. When I add the server check on both runs outs, it would both technically be the server on the host side.
Hi I've noticed some peculiar behaviour with my remote Linux NGO game server instances (using secure websockets). I generally start up 3-4 game servers with NetworkManager.StartServer() so that clients have something they can quickly connect to.
If these server instances have been running for an extended period (a couple hours or so) without any client connections, they seem to go "stale" and a connecting client will be disconnected immediately after connecting with the following TLS error on the server.
\Failed to decrypt packet (error: 1048580). Likely internal TLS failure. Closing connection.```
Does anyone know what might be the cause of this? The work around I have is to automatically restart inactive servers every 10min or so but I'd like to know more about what is causing the failure if anyone has experienced something similar?
I'm trying to follow the tutorial for multiplay, and when i get to the deployment step, it fails on fleet, and I can't seem to get past it. Don't see any kind of useful error, just "failed to deploy: HTTP/1.1 400 Bad Request"
I'm using the "Small Scale Competitive Multiplayer" sample project's tutorial
I'm not sure why that always fails but you can make the fleet manually on the Cloud Dashboard
Sure but I can’t proceed with the tutorial
What is the difference between Anticipation and Prediction?
Specifically https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.9/api/Unity.Netcode.Components.AnticipatedNetworkTransform.html
Versus client-side prediction
It doesn't mention anywhere as far as I'm aware what the difference is
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/client-anticipation/
Netcode for GameObjects doesn't support full client-side prediction and reconciliation, but it does support client anticipation: a simplified model that lacks the full rollback-and-replay prediction loop, but still provides a mechanism for anticipating the server result of an action and then correcting if you anticipated incorrectly.
Client anticipation is only relevant for games using a client-server topology.
A bit better explained here
Ah, thank you! 
hello peeps, I was wondering what the buildid and map variables are for in startserverqueryhandler. docs aren't really giving me an idea on what they're for.
my initial assumptions is that buildID is handled by us for our own use and that map is just an extra variable to be used like what map a level loads with
Yea. The build Id is like the version number of the build. And the multiplayer map are both used for matchmaking queries
thank you!
@sharp axle @ornate zinc @opal dust @noble spindle @tame slate I'm looking into using WebRTC in Unity and saw that you posted or answered around messages for WebRTC recently. Did you get those solutions running or continue those messages threads anywhere?
I'm aiming to use WebRTC with a Quest 3 build and the OpenAI Realtime API so that I can mock talking to an AI assistant in realtime in VR.
WebRTC, Unity, Quest 3 VR: I haven't worked with WebRTC before, so I'm trying to understand the standard, available tools, and what I'll have to implement. If there's some response on this, I can also share openly here in case that helps anyone looking in the future.
No need to mass ping people. I've just been point folks to the WebRTC package
Ah apologies if that was a nuisance. I gave it a shot since it seemed like a lot of unclosed threads.
And thanks for the response. Have you used that WebRTC package with success? Do you happen to know of any Android limitations? I ask because some quick research shows that people seem to say it's hard to work with.
Of course that might just be development errors too and not the package itself.
I haven't worked with WebRTC before, so
Apologies for extra channel spam. I just created a thread I'll add to for anyone that's looking in the future. Accidentally threaded the wrong message at first though - sorry all if that pinged you a ton!
Hello everyone! I'm currently trying out the unity vr multiplayer template but encountered an issue. In their setup, one player acts as a host and the other players that join act as clients. All physics interactables are setup to have a Client Network Transform Component. However, the host can't move the objects, they just stay in place (The client can, though, and it also gets synchronized).
There was also a question about this on the forum here https://discussions.unity.com/t/host-cant-move-objects-in-base-vr-multiplayer-template/1571622 but no one answered it.
From my understanding, shouldn't the host also act as a client and therefore be able to interact with the Client Network Transform Objects?
Also, the host seems to own the objects as well, still can't move them however
If I remember right the objects in the VR Template are owner based. When a client grabs one it requests ownership and should be able to move them
hmm I see, but from what I understand, the clients are not really the problem right now. They can move the objects around just fine (as long as they have a Client Network Transform Component). But the host can't move these objects for some reason.
You'll need to check that the ownership is actually changing to the host. No clue why that wouldn't work
Thanks for your quick help! I experimented some more and it seems that it works differently for objects that I create add myself. Here, the host can move it but when the client tries to move it the object snaps back to its originial position after letting go. This would add to what you said that I need to ask the host for ownership, do you know of good resources where that is described?
No idea why this doesn't work for their objects though, from what I can see they're using the exact same configuration🤷♂️
Its not much of a guide but the quick start guide
Also no need to add people randomly…
Hello! I've started using the networking packages on the 6000.0.30f1. Up until now, all the information I've seen including official documentation is saying to use the MultiplayPackage. Notably for hosting dedicated servers, the MultiplayService.Instance is need to access stuff like the ServerConfig and setup correctly the NetworkManager and the likes.
However, the package is marked as deprecated and although I've seen disccusions mentioning that it can be swapped, as indicated in the package manager, with the new unified Multiplayer.Services package. I fail to see how I would go about getting an equivalent to the MultiplayService.Instance.ServerConfig
EDIT: My mistake, I'm using assembly references and missed the Unity.Services.Multiplayer.Multiplay
[MIRROR] Hello, I am trying to host an online webgl game on itch.io but the problem is that i cant make a websocket server i say the docs and there is nothing really usefull for me.The game as a pc game works with online. how could i make a dedicated websocket server or maybe even use AWS for websocket connection
Do you mean you? I added you because you had WebRTC questions that seemed to go unanswered. But again, apologies if the ping felt more bothersome than helpful.
i'm making a chunking system for streaming world chunks, if a player edits a chunk(like adding a GameObject to it) that a client dosent have loaded how would i pass that change to new clients that load that chunk?
i assume the server will have to have all chunks loaded but will that be performant enough? i'm not really sure how the headless unity server build works
**[Multiplay] ** hello peeps, what do you guys generally exclude when creating a headless server build? Currently when running mine on Multiplay, I get about 50%+ usage with nothing but a ground plane and a skybox. When I get 2 clients to join, it goes up to 56%. I have limited the FPS to 60 because I read online about uncapped framerates running as fast as possible due to no rendering but that only took it down a notch. Any other stuff you guys exclude to bring the usage down?
Browser cannot open connection for security purpose, your choice is to use Relay, or a dedicated server
And to not leave your question unanswered. I stepped away from webrtc and am working with native platform features now, so I would have been out of this conversation anyways.
This is part four of the Porting from client-hosted to dedicated server-hosted series.
and how can i make that dedicated server it gives me this error
One thing that isn’t evident in the simple client-serve example is that the NetworkDriver instantiates a NetworkInterface object internally. However, you might still need to request a particular NetworkInterface object.
Is it normal to have such high CPU usage in a dedicated windows build?
It goes up to 85% if not more
Processor is 24 / 32
Unity: 6000.0.33f1
Unsure whether this is part of networking or if it's part of something else, please redirect me if I'm in the wrong category.
Edit: Ah I forgot to limit the target frame rate for the server, my apologies!
so does this work with mirror and do i need UTP or Unity transport?
Mirror has its own Transport that would have its own way to connect to websockets.
UTP is the Unity Transport Package
k thx
Hi guys, does anyone know how to run animations and sync between all clients using Netcode for Entities? I'm struggling with this and haven't found anything useful yet. All the Unity examples (megacity, ecs samples, multiplayer FPS) only use objects that don't need animations (cubes, capsules and cars that only move on the x, y and z axes), I haven't seen an example showing any real animations such as running, jumping, shooting, dying, etc.
why would you need to sync those directly? you could just run those on the clients as cosmetic effects.
regardless, you can use https://docs-multiplayer.unity3d.com/netcode/current/components/networkanimator/
The NetworkAnimator component provides a fundamental example of how to synchronize animations during a network session. You can also use RPCs, NetworkVariables, and custom messages to create a custom animation synchronization system, if it suits the needs of your project better.
but as that example states, its kinda pointless to sync animations directly, cause they are typically irrelevant for gameplay logic
note that entities (if you are using that) does not (natively) support animations yet and this limitation extends to netcode projects made with entities.
Okay, won't tag you on future ones. I think it's a loss to the community when open threads don't get closed, so that's part of why I tried to bring together recent contributors. And of course yes: I asked because I want answers too. Noted you don't want in on WebRTC though. Good luck on future work.
Yea. currently DOTS does not have an animation system. Your best bet is to use one of the 3rd party assets like Rukhanka Animation
Hello, I am trying to run the following code for RelayManager
public async Task<string> StartHostWithRelay(int maxConnections = 3)
{
Allocation allocation;
try
{
allocation = await RelayService.Instance.CreateAllocationAsync(maxConnections);
}
catch
{
Debug.LogError("Creating allocation failed");
throw;
}
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(new RelayServerData(allocation, "dtls"));
string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
return NetworkManager.Singleton.StartHost() ? joinCode : null;
}
Though, StartHost() always returns a NullReferenceException. I'm new to Unity so I'm not exactly sure how to fix it.
https://pastebin.com/EkdUgYte (Error)
And I'm using these tutorials if it matters:
https://www.youtube.com/watch?v=DXsmhMMH9h4
https://www.youtube.com/watch?v=BEm-LWPlMz8&t
I would switch to the Multiplayer Services SDK
my bad i forgot i changed yesterday
i was on unity 2022
and updated to unity 6
same project im working on now
i forgot they changed the name
but yeah im using multiplayer services rn
(I think)
i downloaded the multiplayer services package, but I didn't change this stuff. am i supposed to import different stuff here now in unity 6
ty
I'm trying to update my namespace imports from
using Unity.Services.Lobbies;
using Unity.Services.Lobbies.Models;
but I cannot figure out what to update them to that keeps the same functionalities. Do you know what namespace im suppsoed to use?
Unity.Services.Multiplayer
i've tried that, but it doesn't work
and i have it installed
nvm reopening vscode fixed that part
butttttt
this issue where things such as this, which previously worked fine with lobbies, is happening
i now added Unity.Services.Multiplayer
but for some reason its dulled out
and nothing is using it
such as this, it isn't recognizing unity.services.multiplayer, so idk if I'm doing smth wrong
Hello guys, currently trying to figure out how to get one of my servers to go from available to allocated. Currently everything works with the test allocation so tryna get this done through code but I've been hit with a wall.
An allocation is only returned in the api response json if a server is already allocated,
and to queue an allocation requires it's id in the api request body
so how does one acquire the allocationid in the first place
I hadn't really thought about it like that, it makes sense, but I still need to ask the clients to run the animation, it's still going to involve some kind of animation mechanism on the network, right?
yep, that's the point, so sad... I'm using entities 😕
Thanks anyways for your support and time mate 🙂
I've seen that package and it seems to be amazing, however I cannot afford it at this moment. I'm researching and playing around with Netcode for Entities and doesn't make sense to buy a package just for that. I mean, the package is awesome, but it is not worth it for me atm.
I'd like to hear your opinion guys, I'd like to create a game samurai warriors like (I can leave a link below for those who don't know the game) but multiplayer, about 4 - 6 players in a room, hundreds of enemies and a couple of bosses. I'm trying to use Netcode for Entities and Unity ECS for it, but I'm struggling with the animations. Do you have any other suggestions for a better Unity Network for a game like this? Maybe Mirror, Photon... I'm not using Netcode for GameObjects because Unity said it's not a good solution for competitive games and to handle several network objects.
Samurai warriors link: https://store.steampowered.com/app/1591530/SAMURAI_WARRIORS_5/
Need a bit of a sanity check on Networking for Gameobjects order of RPC calls--
I know that RPC order is not guaranteed between different network objects, but is the execution order guaranteed between different networkbehaviours on the same network object? Or is it determined by the script execution order?
You should be using the matchmaker to allocate a server.
Honestly, I would stick with netcode for gameobjects. You'll end up losing most of the benefits of dots having to deal with gameobject animations. Unless you really really need client prediction and roll back netcode. You'll need to get a bit creative with your enemy management but it's doable.
As far as I know, RPCs on the same object will get executed in the order they were received.
Thank you, I'll go on that for now then. I had the same impression but I haven't seen it stated anywhere explicitly.
Thanks for your answer and indeed, I'm thinking the same, I'll try another approach here before abandoning DOTS. Maybe in the near future Unity will release better features for DOTS.
DOTS animation is a ways off. Unity 7 timeframe
luckily very few games use animations, so it doesn't cause many problems 
😂 that's exactly what I thought. Animations is one of the most important and used part of a game and they don't have an out of the box solution 🫠
No that's something seperate
Anyone know what's happening?
If you're wanting to use Lobby directly, I'm pretty sure it is still accessed through
using Unity.Services.Lobbies;
even when using the Multiplayer Services package
If you're wanting to use the new Sessions (which encapsulates Lobby/Relay/NGO) that is under Unity.Services.Multiplayer
Actually that might be inaccurate - I think if you're wanting to use Lobby directly, you have to stick with the standalone Lobby Package and not have Multiplayer Services installed. If you're wanting to use Multiplayer Services, I believe your Lobby code has to be migrated to use the new Sessions.
You should still be able to use Lobbies directly.
Oh i thought I wasnt supposed to do that
Then what's Using Unity.Services.Multiplayer for?
Lobbies are still part of Unity.Services.Multiplayer
Hey guys i have a quick question.
Is Cloud Code necessary with Cloud Save if i want to make sure the players don't manipulate there data on Cloud Save?
Do you mean Cloud Code?
Hey, its probably me that messed somethig up, but for some reasons it seems like the InputField.onValueChanged.RemoveListener doesn't seem to remove the function and still gets called after the NetworkSpawn. Wich is weird because the SetPlayerColor does indeed get removed (they are added in Awake). Could someone help ? I've looked everywhere and this literally the only time SetPlayerName is used so I did not add it later by mistake
Really sorry if I bothered anyone, found my mistake. I added the function to the event by the editor and forgot to remove it 😅.
yes sorry i meant cloud code
It's useful for anti cheat but not necessary. You can do the same through a dedicated server if you want
I am trying to use unitywebrequest.post with the following json data:
"{'{ \"model\": Scarlet,\"messages\": [{\"role\": user, \"content\": who is godzilla? } ] }'}"
the url works, but combined with the json it returns status code 400
I am using local host
UnityWebRequest www = UnityWebRequest.Post(url, form);
yield return www.SendWebRequest();
Debug.Log("Status Code: " + www.responseCode);
if (www.isNetworkError)
{
Debug.LogError(string.Format("{0}: {1}", www.url, www.error));
}
else
{
Debug.Log(string.Format("Response: {0}", www.downloadHandler.text));
}
}
currently i am using NGO, Lobby, Relay & Cloud Save
but the Server/Host is not running when in the main menu. that's where in the script i give player gems and save it on the cloud using Cloud Save.
my question is should i be concerned having that in a script which is running locally and not on the server or is that not a big deal as its not easy to manipulate a script?
If the client is writing to Cloud Save locally, it is entirely possible for them to manipulate things.
Yes but using the import statement unity.services.multiplayer doesn't recognize the lobby terminology
I'm pretty sure this is the case.
Whether or not you can access Lobby directly through the Multiplayer Services package - I don't know for sure.
But either way Lobby related code is accessed through Unity.Services.Lobbies.
Hi Guys with NGO ive sucessfully got my Client Authed Player to smoothly follow a SeverAuthed SteeringWheel Object with transform movement Using lateUpdate(I Believe this is because lateupdate contains the Interpolated transform values) Im trying make my players velocity match the velocity of the server authed object now, Im doing this by saving the Velocity on server to a networkVar and getting clients to match it, this works great for local(Singleplayer) But doesnt work very well as a client on a dedicated server, Does anyone know why? im confused as to how im able to accurately match the position of a server authed object but not the velocity.
This below is an visual example of the issue, Player is slowly sliding off when not using steering wheel and using velocity matching (As a client on a dedicated Server)
And this shows it working correctly where the player is not sliding off (On local/SinglePlayer)
You can the Lobbies namespace is wrapped in the Multiplayer Services package
You would Cloud Code for validation of the save data
understood, now my final concern is using all the services a good idea for an indie dev knowing that the android game might not earn enough to help with the costs along with cloud code since in this case it is necessary and of high importance...
You are very unlikely to go beyond the free tiers of UGS. If you do then the game should be paying for itself at that point
https://unity.com/products/gaming-services/pricing
But that is a value call that only you can make
yeah i did go through the pricing, maybe i am not understanding it right but i am hesitant.
Like what does Invocations Compute hours & Egress mean
I'm going to research more so i understand these in depth.
Ok well I'm implementing Cloud Code 😄
Invocations are individual calls from the clients for a cloud code function
Compute hours are the amount of time those functions take to actually run
Egress is the amount of data sent from the cloud function back to the clients
i have this simple serverrpc to sync player movement with the server and a networktransform on the player, but with this setup the client cannot move
im new to networking so i thought this would sync because the serverrpc sends the movement to the server and the networktransform distributes this data among all clients
here is my network transform attached to the player prefab
Might need to add RequireOwnership = false to the RPC attribute.
[ServerRpc(RequireOwnership = false)]
i tried it, it didn't work
i was thinking maybe its because the networktransform is also syncing to the original client
so the serverrpc keeps sending its original position which is sent back
is the server receiving the RPC? Does the server move the object?
the serverrpc is inside Update, the player movement script is a basic one
im taking the position and sending it to the server
it was working before when i used a clientRpc to update the position across clients
i have this simple serverrpc to sync
Anyone got any experience with velocity matching a player to an object, In a multiplayer setting where player is controlled by client & Object is controlled by server?
Is this for a moving platform?
Yeah for moving platform
check out this sample. it uses parenting
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/tree/develop-2.0.0/Examples/CharacterControllerMovingBodies
hello yall ive ran into a problem with my first ever multiplayer game! i am working on the health and shooting system using photon PUN and everything is working great except that when i shoot another player his health updates but the text before stays there and my health also updates like on the picture but when i kill him my health goes back to 100 health script: ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using TMPro;
public class HealthManager : MonoBehaviour
{
public int health;
[Header("UI")]
public TextMeshProUGUI healthText;
[PunRPC]
public void TakeDamage(int _damage)
{
health -= _damage;
healthText.text = health.ToString();
if (health <= 0)
{
Destroy(gameObject);
}
}
}´´´
Thanks i will take a look however im not sure parenting is viable in our usecase and im also using rb movement, Im just wondering is it possible to get an accurate velocity which my player can follow which matches the interpolated positions of my platforms, it seems that saving the velocity to a network var & setting clients velocity to this doesnt work very well.
You'll run into lag issues trying to match the velocity. The other option is to attach the player to the platform with a physics joint
But then this disables movement right? i want my player to move freely on this object with its own rb movement + the rb movement of the object below it
you can move the physics joint like it was the player
Im unsure what you mean by move the Joint, How can i move the joint?
by attaching a joint to an empty gameobject. that object can be a child of the platform. moving it in local space will drag the player along
Okay this in an interesting concept, I will have to make the empty child Game-object IsKinimatic to avoid it falling away from the platform. This means that i wont be able to move my player as its fixed to a Rb which is Kinimatic, Unless i move the Child object with transform movement?
Right, you would move the child object instead of the player.
But the child is now IsKinimatic so must be moved using Transform based movement?
You can do rigid body.MovePosition(), but you won't be able to Add force()
This could potentially work, however it would probably allow for some strange circumstances with collisions, as the child object would be able to move around however, yet my player would collide with objects, Which leads me to think that i might as well just use transform movement in that case anyway.
I was also just reminded of this way of using fixed joints build into NetworkRigidbody with this you can change the fixed joint anchor point instead of using a child object
Put a Debug.log in Start to make sure Start is even running
After that - make sure you understand this: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/messaging-system/
Netcode for GameObjects has two parts to its messaging system: remote procedure calls (RPCs) and custom messages. Both types have sub-types that change their behavior, functionality, and performance. RPCs as implemented in Netcode for GameObjects are session-mode agnostic, and work in both client-server and distributed authority contexts.
Note that the Server RPC is only going to run on the server
Which means:
- there needs to be a server
- There needs to be an active network connection
etc
start debug works and Im just starting out on spawning it on the server, not running another instance atm, but its not even spawning in the main project
the script is inhereting the networkingbehaviour
got it, I moved it to update and they spawn now. The tut runs the instance first then chooses to start client/host/server. So because start() is immediate, it didnt spawn. Guess I can make an event ?
also wdym network topology
Network topology defines how a network is arranged. In the context of multiplayer games, this primarily relates to how clients, hosts, and servers are connected and communicate. Different network topologies have different benefits and drawbacks, depending on the type of game you want to make.
yeah so it was running before you actually had a network session going
ah , its hosted by the client
in this case, if I do "start as host", that instance will be a hybrid of client/server right? So the rpc should still work ? Just trying to understand the difference between start as host and start as server
Yes it will be both the server and a client
Server RPCs just run locally on the server when called from the server
like a normal function
The page about RPCs I linked you above explains this all
ty
Right, Start() runs before the network is connected. RPCs should be called in OnNetworkSpawn() or after.
for persistent RPC targets, it says I need to call Dispose() on them, but doesn't have an example. Is this what it means? myRpcParams.Send.Target.Dispose(); There isn't any dispose method for the params object.
You would dispose of the native collection you are using for the target group.
Ah, so it would be the same collection I pass into RpcTarget.Group(<this needs disposing>, Persistent)?
Exactly
Appreciate it as always 
Sure but how would collisions work, if I am moving the fixed joint object/anchor point this could drag the player (NotKinimatic) into colliders.
Yea. collisions would still happen. joints have a break force so the player would unattach from the platform if pushed too hard
Hmm yeah but the player would still be on the platform, so the connection would still be needed for future movement and breaking is not desirable.
Yea. I would use OnCollisionEnter() with the platform to reset the joint
I made an online game with NGO and it shows me a lot of null reference errors. And this error only happens in Android and is not a problem in Unity!
With Android Logcat, I found out that the error is in the Unity NetworkManager script and from this part. Can anyone help me, what is the cause of this error? Thank you.
I'm instantiating objects in a card game one each client and right now they do not have network object attached. When they play the card I want to instantiate/spawn the card for the opposing player. Should I be using network object to declare spawn or is there a way to do it without having a network object attached?
Send which card is being played via a NetworkVariable or RPC. Have the receiving client look up which GameObject to spawn based on which card was sent.
You could use an ID for the card like an integer or an Enum.
I have a follow up question to that, how sould I go about instantiating the gameobject once the information is passed? I'm just not sure which rpc to use to get just the opposing client to receive code.
You're just sending an RPC/setting a NetworkVariable with the card ID or card type. Once the opposing client has received that ID/Type, they can use it to find a match in a list/array of card prefabs. From there you can just instantiate it normally.
Custom RPC targets can be read about here if none of the basic targets work for you: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/#custom-targets
Any process can communicate with any other process by sending a remote procedure call (RPC). As of Netcode for GameObjects version 1.8.0, the Rpc attribute encompasses server to client RPCs, client to server RPCs, and client to client RPCs. The Rpc attribute is session-mode agnostic and can be used in both client-server and distributed authority...
thank you 
So i am making a unity 3d fps multiplayer game with photon fusion and i have stumbled upon a problem where the other players can not hear your footsteps, i have tried using photon [Rpc(RpcSources.All, RpcTargets.All)] but this did not work. Anyone that can help?
Footsteps don't really need to be networked usually. If other player's movement and animations are already syncing properly, just play the audio based off of that.
Yea, animation events will fire locally
hi how come im getting the error:
SocketException: No connection could be made because the target machine actively refused it.
when trying to connect to a server on the same pc, 127.0.0.1, and debug logging the attempted server to connect to, and the server itselves ip and port, it shows the same numbers (127.0.0.1, and port 7777)
im trying to just check if a server exists. everything i see online uses onfailedconnect which is called, but i wanna call a function and return a value based on if it connected or not
Active refusal is usually a firewall thing. But connecting to localhost shouldn't trigger that. You can't really check if a server exists, all you can do is wait for the connection attempt to timeout. So use OnFailedConnect to call your function
so how would i test a connection attempt to check if it exits? i wanna have a start host button in my game but not let it work if the ip and port are already in use
You can't know if it's already in use until you try it. I suppose you could Ping it. But StartHost will return false if it fail to start.
will it just fail to start if it's already in use?
You should get a Failed to Bind exception on the host. StartClient would still return true but will timeout.
if (NetworkManager.Singleton.StartClient())```
returns true even if there's no server?
ah nvm you said that
how do i know if it's timed out then or wait for a timeout
or only continue the code when / if it succeeds to connect?
There is a Network Transport OnTransportEvent that will return either a disconnect or TransportFailure event when it times out
Hey, I am invoking an event whenever the player right clicks and wants to move a unit. I subscribe to this event on my visuals controller so that a visual effect is being spawned at the clicked location. However, subscribing to this event never actually triggers and therefore does not happen. What am I missing? I noticed, that it works sometimes in rare cases and very randomly. I assume it has something to do with the order things happen or maybe with OnNetworkSpawn?
the visual controller (attached to every unit object in the scene):
using UnityEngine;
public class UnitSelectionVisualController : NetworkBehaviour {
[SerializeField] private GameObject moveParticleEffectPrefab;
private UnitController unitController;
private void Start() {
unitController = GetComponent<UnitController>();
if (unitController == null) {
Debug.LogError("UnitController not found on " + gameObject.name);
}
}
public override void OnNetworkSpawn() {
if (unitController != null) {
unitController.OnWaypointSet += UnitController_OnWaypointSet;
Debug.Log("subscribed to OnWaypointSet!");
}
}
private void UnitController_OnWaypointSet(object sender, UnitController.OnWaypointSetEventArgs e) {
PlayMoveEffect(e.destination);
}
private void PlayMoveEffect(Vector3 position) {
if (moveParticleEffectPrefab != null) {
GameObject effect = Instantiate(moveParticleEffectPrefab, position, Quaternion.identity);
}
}
}```
the event invoke logic:
public event EventHandler<OnWaypointSetEventArgs> OnWaypointSet;
public class OnWaypointSetEventArgs : EventArgs {
public Vector3 destination;
}
private void SetDestination(Vector3 destination) {
if (playerNavMeshAgent.isOnNavMesh) {
playerNavMeshAgent.SetDestination(destination);
OnWaypointSet?.Invoke(this, new OnWaypointSetEventArgs { destination = destination });
Debug.Log("Invoked OnWaypointSet event!");
}
}```
None of this code is networked but it should work locally. As long as SetDestination() is actually getting called somewhere.
Hi,
I'm struggling to set up a working NetworkObject with a NetworkRigidbody properly.
When the client tries to move the object, it completely glitches out, starts shaking and refuses to move. The cube is being moved by setting its linear velocity, so I can not make it kinematic and just sync its position.
Is there something I don't understand what don't I understand with the way Netcode works ?
Are you using Network Transform with Owner Authority set?
Yes
Are you making sure that only the object owner is setting the velocity?
I think it's the case, but how could I check that?
Check for if(IsOwner) in the network behavior that is setting the object's velocity
That was the issue, SetDestination was never actually called because I had gated it with a „if (!isOwner){ return } „
Thanks!
i am developing an multiplayer for my game right now, using Unity Netcode for Game Objects and it uses "Lobbies" for it as far as i went, and i like how it works but i feel like i missing something, because i want to create permanent servers as those in battlefield and Netcode uses a lil too specific naming, lobby as i imagine it, is a temporary server for couple of friends. So is it ok to use it for hosting a game similar to battlebit for example? Sorry if stupid question, i am begginer
Actually, Lobbies are not servers at all. You can use them to group up players before connecting to the game server. It sounds like you want dedicated servers. That can be done through the Multiplay Service or by hosting on cloud service like Amazon's
For more clarity i am following a multiplayer course by code monkey now, and there is an free option for relay and everything in Unity Gaming Services so i thong that i could set one machine as host, without graphics, just bare logic calculator, on my own for now. Isn't it server enough? Thank you anyway
You will hit a limit with Relay at some point. Where that limit falls is entirely based on your game and how it is coded to be networked. To use your example of Battle Bit, they use dedicated servers that support up to 254 players. Unity Relay has a hard limit of 100 players and you may run in to performance issues well before that number depending on how your game is built.
Oh okay, than can i use some external hosting while still using Netcode for Game Objects as multiplayer utility?
@tame star Yes. Common server hosting options were listed here. Multiplay is Unity's solution.
Thank you very much
If your game is turned based the you could also do a serverless architecture with Unity Cloud Code, Amazon lambda, or Azure Cloud Functions
it is shooter actually and i am aiming for at least 16vs16, so it is not an option
can i use unity relay for testing and developing now and transfer later to more powerful host without much issues, in that matter?
There is a whole guide on it
https://docs-multiplayer.unity3d.com/tools/current/porting-to-dgs/
This is part one of the Porting from client-hosted to dedicated server-hosted series.
Omg thanks
hi i've got this code
void Awake()
{
if (Instance != null && Instance != this)
{
Debug.LogError("More than one player spawner exists!");
Destroy(this);
}
else
{
Instance = this;
DontDestroyOnLoad(this);
}
}```
for a singleton, yet when i start a client it destroys the objects? but it doesn't when i start a host? and the debug.logerror never fires either which is the only place i have destroy
i start a client then load a new scene too, if that changes anything
This is for a NetworkObject?
yes
I try to avoid Singletons. But I would move this to OnNetworkSpawn instead of Awake.
how come i can't get that function ?
how do i run code on onnetworkspawn?
It's an override. Make sure this is in a network behavior
ok so that broke everything.. it doesn't even seem to be running this code
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (Instance != null && Instance != this)
{
Debug.LogError("More than one player spawner exists!");
Destroy(this);
}
else
{
Instance = this;
DontDestroyOnLoad(this);
Debug.Log("Singleton for " + this.name + " set");
}
}```
none of the debug logs are running in the client
i just get this a bunch
Debug.Log("Loading scene");
NetworkManager.Singleton.Shutdown();
unityTransport.ConnectionData.Address = ipAddress.text;
unityTransport.ConnectionData.Port = ushort.Parse(port.text);
NetworkManager.Singleton.StartClient();```
this is the code that starts the client on a button press
If this a NetworkObject, you can't do Singleton logic like this on it anyway. Clients can't destroy NetworkObjects.
ok so if i remove the destroy then, but what about the rest of it? it shouldn't be destroying anything anyway as i only have one in the scene
nor does the error that more than one exists ever show
does the network object get spawned before it connects to a server successfully?
or after it connects to a server
aka does onnetworkspawn fire when the object is spawned / on game load in this case, or when a server is connected to
Yes. this is why I avoid singletons. scene objects get respawned when the scene loads
ok so.. how can i get data from the server about a different scene
You can use Dont destroy on load. just do't make it a static instance
You can also use scriptable objects to persist data across scenes
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/Transports/com.community.netcode.transport.steamnetworkingsockets
using steamworks.net and this layer for netcode, when starting a client once joining a lobby my game freezes and no errors are displayed. How do I fix?
[System.Serializable]
public class Character
{
public string characterName;
public Sprite characterSprite;
public GameObject ballCharacterPrefab;
public GameObject characterPrefab;
public GameObject podiumPrefab;
}
hello how can I make this serializable? right now I get Unity.Netcode.Editor.CodeGen.NetworkBehaviourILPP: (0,0): error - Character: Managed type in NetworkVariable must implement IEquatable<Character> issue
You should use an ID for the sprites and prefabs like an integer or an Enum. Clients can use that ID to look up sprites, prefabs, etc.
public class GamePlayer : NetworkBehaviour
{
//private Character playerCharacter;
private NetworkVariable<Character> playerCharacter = new NetworkVariable<Character>();
private NetworkVariable<Character> hoveredCharacter = new NetworkVariable<Character>();
private int playerNumber;
private int playerHealth;
private bool isCPU = true;
private int userNumber;
private int roundWins;
private bool isReady;
private MainManager.Difficulty playerDifficulty;
public void ReplacePodium(int podiumId, int characterIndex)
{
foreach (GameObject podium in podiums)
{
if (podium.GetComponent<Podium>().PodiumID == podiumId)
{
GameObject replacedPodium = Instantiate(MainManager.Instance.characterDB.GetCharacter(characterIndex).podiumPrefab, podiumPos[podiumId], emptyPodium.transform.rotation);
GamePlayer player = MainManager.Instance.GetPlayer((int)NetworkManager.LocalClientId);
player.HoveredCharacter = MainManager.Instance.characterDB.GetCharacter(characterIndex);
replacedPodium.GetComponent<Podium>().PodiumID = podiumId;
podiums.Add(replacedPodium);
replacedPodium.GetComponent<NetworkObject>().Spawn();
podiums.Remove(podium);
Destroy(podium);
}
}
}
that was my script
it was working well until I struggled with network variables
I have a character database, I get chars from there
with index
Also if each client knows this information beforehand, there's not much reason to network it.
Which is usually the case with Sprites/Prefabs
okay so I Initialize 4 player classes at the start
these player classes have character variable
I just want to make players change their player classes itself
like player.PlayerCharacter = chosenCharacter
so instead of that do I need to make it like player.PlayerCharacterIndex?
Yes, that would probably be the way to go about it.
Network the chosen character as an ID or index and then let each client update visuals and whatever else on their own based on that ID/index.
okay but how can I update player classes on all clients?
like I want player2 updated when second player picks
on all clietns
Use a NetworkVariable for the ID/Index and then use OnValueChanged to update whatever you need.
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
private void InitializePlayers()
{
players = new GamePlayer[4];
for (int i = 0; i < players.Length; i++)
{
players[i] = new GamePlayer(i); // Assuming Player constructor takes a player number
}
}
okay ty
why does
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnect; (in start)
private void OnClientConnect(ulong clientID)
{
Debug.Log(IsClient);
}
return false?
doesonclientconnectedcallback not call when a client has connected to a server?
what does?
It calls on the server when any client connects and it calls on clients when the local client connects to a server. So if you're running a server-only (not a host) instance and a client connects, that will return false.
If it's always returning false, it's probably just too early in the network cycle to accurately return the proper value. If you check it at any later point, it should be correct.
I've seen a handful of bugs with OnClientConnectedCallback as well. It is recommended to use OnConnectionEvent as OnClientConnectCallback and OnClientDisconnectCallback will be deprecated at some point.
how do i compare the connectioneventdata passed into onconnectionevent to a connectionevent? i.e how do do i check if the value passed == clientconnected? which i assume would mean the client has connected to a server / host
private void OnClientConnect(NetworkManager manager, ConnectionEventData data)
{
if (data.EventType == ConnectionEvent.ClientConnected)
{
Debug.Log(IsClient);
}
}```
now this is still showing false.. using onconnectionevent
Then something else is up. What script is this running in?
it's running in a dontdestroyonload networkbehaviour object, and in the code a new scene is loaded. a client and host are started in the game itself at runtime, and i want the new scene to load when it detects the client as being connected to a server
unity 6 if that helps, netcode
The NetworkManager's SceneManager auto syncs scenes on join IIRC, if that works for what you're trying to do.
yeah, i disabled that though as i wanna manually join the scene and make sure everything loads in order n stuff
ok, i enabled it for testing, and it doesn't load the same scene when i run startclient
Right. Well again, I’m not really sure why IsClient isn’t coming up as true. You could just check for if you’re not in the scene you’re wanting to load, since the server/host is already in that scene.
also, this debug.log i put runs now
private void OnTransportevent(Unity.Netcode.NetworkEvent eventType, ulong clientId, ArraySegment<byte> payload, float receiveTime)
{
if(eventType == NetworkEvent.Disconnect || eventType == NetworkEvent.TransportFailure)
{
NetworkManager.Singleton.Shutdown();
Debug.Log("Client disconnected (is there a server on the ip and port?)");
}
}```
im right in saying 127.0.0.1 is the local ip right?
ok yeah debuglogging the ip and port on the client and the host have the same numbers
yeah, startclient in the code just isn't running
NetworkManager.Singleton.StartClient();
it's not connecting to the server
i think i fixed it, but now running my rpc gives a "the given key was not present in the dictionary" error
i have an rpc running set to sendto server onsceneload, yet on the server it runs 8112 times, and the client gives a given key not present error
why does onsceneload fire 8112 times???
anyone have problem with network objects? when i click on one in the hierarchy it seems to do loads of stuff over and over and its difficult to even click off it
using netcode..
also does networking disable the "step to next frame" button? not been able to use that in ages
Hello, does anyone know a good method to archieve multiplayer damage by teams?
Been looking for tutorials on YT but all I seem to find is basic offline damageable behaviours
Sounds like it's getting called in update.
Never heard that one before. Netcode doesn't effect the editor at all. Unless you have some odd custom inspectors
Easiest way would be to a Team network variable that you can check before applying damage
i think its something to do with that setting where it can auto add network obj script
That shouldn't be doing anything if it already has a network object component
yeh!
this may be a dumb question but, i want to have a few default items in the inventory (items are int/id's in an int network list), but it's not possible to do that with a network list directly, right? (to set the network list default content in the inspector) i have to first instantiate the list and add in the content in start from another list manually?
Correct
You could use a regular List for the inspector the initialize the NetworkVariable<List<int>> with that first list
Hey guys, I'm currently setting up UGS Multiplay, I've set the minimum available servers (in fleet->scaling settings) to 0, but I'm not quite sure how the machine's supposed to start up (because it isn't, even though there's an active matchmaker ticket)
(Everything works fine when I set the min available servers to 1 or more though)
Nevermind
Looks like the machine just took ages to load up
why is my rpc not loading at all? it shows KeyNotFoundException.. the rpc is in the same file that the rpc is being ran from,
rpc:
[Rpc(SendTo.Server)]
public void RequestServerMapRpc()
{
//Debug.Log("sdfljhkbndrsfgsgfdsdgtf ");
Debug.Log(IsServer + "sdrfg");
if (IsServer)
{
SendMapToClientRpc(map);
}
}```
running requestservermaprpc causes the keynotfoundexception. even if i comment the code and have it only be a debug log it still gives an error?
how can it not find the rpc but it's able to run the code that runs the rpc, which is on the same script
running the rpc on a host works fine, the client fails though
Are you destroying or disabling the component on the client?
i can see the component the entire time in the inspector that runs the script
and there is nothing setting it to active or destroyed ever in my code at all
it's set to a dontdestroyonload
You need to make sure that its getting spawned on the client. Make sure that its not moving to DDOL in Start() or Awake(). It should be in OnNetworkSapwn()
onnetworkspawn never runs and it ends up deleted when the scene changes ?
but, it does on the host?
I’m having a hard time with the concept of multiplayer rpcs. The game I’m working on is a two player card game. Right now I have client authoritative deck creation and dealing. When I was moving it to server authoritative I got stuck on the step of instantiating the decks with instantiate then spawn. now I needed to pass all the information to the client within an rpc(I think) or find a way to get card info stored on a separate matchmaking scene. My biggest issue is that I still don’t understand how get both players to function with separate decks. Or am I supposed to just 180 the board at scene start? Please let me know how you would do it.
but now, on a different script a network object on the host shows "spawn" and on the client it doesn't ?
this is one that's loaded by loading into a scene
Are you using Network Manager Scene Manager to switch scenes?
If your decks are a list of card ids, then you can use a NetworkList
"enable scene management" yes, that is the only thing on the client i have to load scenes, other than an rpc that is sent to the server to tell it to load the scene (which loads fine)
Are you calling NetworkManager.SceneManager.LoadScene() from the host?
Unfortunately I’m using a struct that serializes scriptable objects. The ambition of this game is to use player made cards so I need to keep the list of cards dynamic (I think anyways)
You shouldn't use SOs for dynamic data, but as long as its serialized then it can still use NetworkList or NetworkVariable<List<>>
rpc not properly working
Hey guys, I have a chair<network object> inside of a vehicle<network object> that is supposed to allow passengers to ride with each other. Everything works great until the vehicle despawns. The chairs do not despawn with the vehicle. They simply stay active. Is there a solution to this behavior?
You might need to use OnNetworkObjectParentChanged or in the OnNetworkDespawn() of the vehicle, loop through all the children to despawn them as well.
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
@sharp axle I will give that a shot after you get off work
@sharp axleNot quite what I'm looking for. I just want the child network objects to deactivate with the parent.
in the OnNetworkDespawn() of the vehicle, loop through all the children to despawn them as well.
this doesn't work for you?
@tame slate Haven't tried that yet, currently building a cleaner work around. The chair is messy lol
hello I have a problem
I have a mainmanager and I initialize several player classes inside at the start.
private NetworkVariable<int> hoveredCharacterIndex = new NetworkVariable<int>();
private NetworkVariable<int> playerCharacterIndex = new NetworkVariable<int>();
these players have that values. How can I sync them with other clients?
private void InitializePlayers()
{
// Create 4 players without using prefabs
for (int i = 0; i < 4; i++)
{
GamePlayer player = new GamePlayer(i);
players.Add(player);
}
}
I initialize here
public class MainManager : MonoBehaviour
{
private List<GamePlayer> players = new List<GamePlayer>();
do I need make mainmanager also network object?
Network Variables are already synced to all clients. If gamePlayer implemented iNetworkSerialiable, then you can make Players a NetworkList. MainManage would need to be a network behavior in that case
Hello everyone, I would like some help in trying to make a VR multiplayer game using Netcode but i am stuck since the materials that i am using from unity are working well for third person player and now i am trying to implement it in VR.
Check out the VR Multiplayer Template to see how they did it
what do you mean by that? (rn i add all content from a second list into the network list in Start() if you mean that)
Yea, that's what I meant
ah yeah that's what i was trying to avoid but nevermind
Are the default items consumable or removeable?
Or do they stay in the inventory the whole time from the moment they're added
i mean it's an inventory so obv you can remove and add stuff (so no)
Some items in an inventory can be persistent. That's why I asked.
How can I make a network leaderboard for my game? The game will be for IOS. Unity6.
Leaderboard is a package that's a part of UGS.
Thanks a lot
public void InitializePlayers()
{
if (IsServer)
{
for (int i = 0; i < 4; i++)
{
Debug.Log("Instantiating player " + i);
// Instantiate the player prefab
GameObject playerObject = Instantiate(playerPrefab);
playerObject.name = "Player " + i;
NetworkObject networkObject = playerObject.GetComponent<NetworkObject>();
players[i] = playerObject.GetComponent<GamePlayer>();
players[i].PlayerNumber = i;
networkObject.Spawn();
}
}
}
it doesnt spawn prefab for other clients anyone know why? Yes my prefab has network object component
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
// Initialize players
InitializePlayers();
DontDestroyOnLoad(gameObject);
for (int i = 0; i < characterDB.CharacterCount; i++)
{
Debug.Log("works");
availableCharacters.Add(characterDB.GetCharacter(i));
}
}
If this is on a scene object, then it will only run once on the server. only the host like going to be connected then
its on mainmanager
singleton instance
it has networkbehaviour too
what I need to do then
:/
wait for all clients to connect then call InitializePlayers()
but this is on character selection screen
Ive made setup with relay and unity lobbies already
later all players go to the character selection screen
cant I syncronize when other players join or something?
these player classes are basically to store information. I was doing it without gameobjects before but I reallized its hard when its networked
Sure, there are Lobby events for when players join
no no these happen after lobby
I dont allow people to pick characters on lobby because my character selection screen is pretty animated
You can store the character selection however you want really. He's just making the point that you can't spawn players at a point in time at which they are not connected to the server.
I would store your character selection locally on the client, and then when they connect to the server they can send an RPC to the server to request the player object to be spawned.
how can I make that they get these player objects too?
when they enter to game example
I just explained that above
You can use the OnNetworkSpawn of the main manager to send an rpc to the server
okay thanks
Hello guys. I am making an Android app that uses Google Drive. I am using this package to access Google Drive
https://github.com/elringus/unity-google-drive
It works really well in Editor, but when I try to Upload a text file to Google Drive in my Android Phone, it crashes. What should I do?
Unity 2020.3.30f1
This probably needs to be in #📱┃mobile but you'll need to check the logs to find the error
I dont know how to look to logs error on mobile.
Thank you
How do you name an instantiated prefab on clients? I can't get the GameObject instance as a ref so I'm struggling with this concept. Right now I have the name I want being passed into the rpc for clients, but since I'm spawning so many I can't get them to work.
If they are being spawned then you can use NetworkObjectReference
Brief explanation on using NetworkObject and NetworkBehaviour in Network for GameObjects
doesn't that use alot of bandwidth?
Still it is looking like the only option
Thank you for the pointer
its just a wrapper for a ulong network Id
oooooo, that is good to know, I thought it was doing some type of gameobject serialization
I am having trouble trying to swap the avatar in the template for a full body avatar and its not working when i test. What could i be doing wrong?
Hello again, been a while since I posted here.
I'm looking to learn how to set up my own game server, preferably C# / ASP.NET so I don't need to study a 2nd programming language.
I've build a tiny real-time game before in node.js with socket.io. I'm a mid-level developer but I don't have much experience with servers.
I think I'd prefer a mid/high level solution so I'm not re-inventing the wheel, if proper solutions exist I'd like to use those. But I do want to be able to control how the game logic works. I'd rather not have to worry about the networking too much.
Not entirely sure what kind of game I wanna make yet. Probably something for 2 players, max 10 players. Like 2 player co-op or 5v5 PvP.
Specifically I'm looking for a library that handles everything or most of the things I'll need for a small multiplayer game, with a lot of freedom to change game logic (not networking logic) and I'd prefer it to be fast, like say max 50ms latency. I would need matchmaking and lobbies, but can write those myself is necessary, again if a proper library exists for them I'd prefer using that. It also needs to be free, not looking for a service that requires me to pay per user or something.
I've been doing my own research and found some libraries that look interesting, but from experience it's always better to ask people actually working with them than just reading some articles on the internet.
what are those libraries?
I intentionally left them out because I'm not sure they're suitable for what I need and it will bias replies.
no, its okay
SignalR, but seems too slow.
LiteNetLib, but seems very abstract to me
Ideally I'd use a Unity service, but the cost per user just grows out of control too fast
What PvP style is this?
what most matter here is:
- where it will be deployed
- what is gameplay looks like
What I've read the latency for SignalR would be around 100ms at a minimum, I want my game to feel smoother than that
I'm thinking a real time co-op tower defense for now, but it might change to PvP and I'd prefer to learn something I can use for more fast paced games in the future as well
Not sure where/how to deploy it, but probably a managed dedicated server somewhere?
Gameplay no idea yet, but fairly simple. Why is this important? Might be able to give a better answer if I understand.
is it mobile, pc, console?
PC, might go mobile but not the main goal
Mobile -> weaker connection, weaker processing power. Require the most performant library
PC -> Safe, more exposeable to cheats, require more secure library
highly competitive?
co-op tower defense, then its not too fast paced? but then changing direction to PvP?
yeah I'm not sure what game to make yet 🙂 just a general direction I wanna go in
anti-cheat is very important to me, definitely want a competitive game
is it fast paced?
tower defense PvP?
Im still dont getting the idea of the gameplay
not extremely fast paced, but I want the game to feel very smooth regardless, like 20-50ms preferably
it really depends on what idea I got with, if it's co-op tower defense the pace will be much slower
if it's pvp tower defense one player might be dropping units, which need to appear for the other player as fast as possible
sorta real-time strategy
but I might go with something else entirely, not sure how to explain it better
you can try to take a look for quantum
its suitable for cross-platform, lot of entities
Hi all - using Unity.Networking.Transport and jobs... the tutorial uses Driver.Accept() in a job. I was under the impression it is not thread safe or has this changed?
But it's paid per CCU? Isn't that very cost inefficient if I would ever scale up?
I did a business plan based on UGS and the cost efficiency was terrible
Looks really good though
yeas they are
100CCU seems small right?
not really, just worried about the cost
oh okay, then you can upgrade your plan
quantum is cost efficient because we dont pay for servers
while in in traditional client-server, we still have to pay for dedicated servers for secure gameplay
what are it's major downsides? what games shouldn't I use it for?
games where you want to hide some information from other players:
- card games, wallhack, fog of war
oh wauw, that's good to know
Your latency is based almost entirely on your network connection not the library used. I'm a fan of Unity Netcode. They have recently made some improvements that make developing on super steamlined
unity netcode seems more flexible too, I like that
Any of the modern libraries can more or less do whatever you need. The difference are mostly built in features(some paid for, others free)
Dont think make a concurrent copy of the driver before calling it?
Its been awhile since ive looked at the souce
all of the major unity friendly networking stacks have very very similar designs. RPC's, Network Variables, Network Transforms. They tend to share similar architectures.
which ones are those?
Photon Fusion 2, Mirror, Netcode for Gameobjects, Fishnet, Nettick. And Netcode for Entities if you are using DOTS
Did you factor in the free tiers?
The only exception to the UGS free tiers is Multiplay Server Hosting which can get very expensive depending on the game
It’s the industry norm
Yeah that's why I'd rather build my own server and host it, which is much cheaper not?
That's how the tutorial does it, so makes sense I guess
Depends. you still have to host the server somewhere.
Is the main difference between Photon Fusion & Quantum just that Quantum is specifically made for Unity? Or are there any other major differences?
fusion is state transfer,
while quantum is a deterministic engine
both are made for unity
it shouldnt really be, quantum has provided multi-regions, lobbies, and scaling problems for you.
but maybe you can opt in industry license or something to allow self host the photon quantum server
? ofc hosting it yourself is cheaper, you're not paying a 2nd party to do it for you
might a (a lot) more work though, that I don't know
right now quantum has 100 free ccu, which is a lot. 🙂
that is exactly the problem though
they draw you in with free tiers (like UGS does) then you lose TONS of money if your game ever gets big
the 100 ccu plan doesnt scale automatically
it will be capped there
the player 101, will get kicked
talking from a business perspecitve, if you managed to get 100 ccu consistently, then your game is hit
what is most user friendly networking solution
define user friendly?
what games do you want to build?
would like to make first person zombie shooter with only like 4 players in each lobby
its like asking, whats the most user friendly game engine, but you are trying to create High FX Open world Game, and other devs answered "Godot"
co-op game?
yeah
PC game?
yes
where would it be deployed? steam?
yes
how many zombies?
not to many it doesnt need to be able to handle that much
anything could work:
- (Client authority) Netcode for gameObject, Mirror, Fishnet
- (Rollback) Netick, Fusion
- (Deterministic) Quantum
allright thanks
What would you recommend for a fast-paced 2d adventure fantasy rpg with simple combat both PvE and PvP? Won't have a lot of monsters
Something similar to like Graal Online or Maple Story
Is it top-down game?
probably, but might go with platform instead, not sure yet
maps will have like a max of 10-20 players
but usually less
needs to be deterministic too
think Quantum still works for this type of game?
it is
what would the limitations of quantum be for this kind of game?
nothing really
like max number of players/zones? something else it can't do?
quantum can be not suitable for game with Big Maps
yeah probably not making huge maps, but maybe in cities it would be nice to have higher player counts
the Fog of war, wallhack, interest, hiding other player information
fog of war would still work for non-cheating players right?
might do something like that for atmosphere mostly
if player is a cheater, the fog of war doesnt matter in quantum
but if its regular player, its fine
Setting up a project with quantum now to do some testing 🙂
Hi everyone !
I have a problem with my proximity voice chat
It works and I can hear other players speak but the sound crakles and it's very annoying.
I use FizzySteamworks for the steam implementation.
Does anyone know how to fix this issue ?
What do you do if you want an RPC to return a value? I'm getting an error in steam that rpc must return void. Right now I'm sening and recieveing a networkObjectReference
When calling an RPC, you're running a function on a remote client. As your call is just sending off a message somewhere else to run that function, there's no direct way to get a return value as you're not the one running the function.
If you want a "return" you'll have to ask the receiving client of the RPC to send information back to the sender.
Usually with another RPC.
gotcha thanks for the help. I'm very new to multiplayer 
I would take some time to learn the multiplayer principles.
Understand that multiplayer communication is alot like me and you are sitting in an office, using an assistant to pass notes back and forth.
We both keep working, some notes get lost, and there is a delay in receiving a reply, since the assistant needs to walk the message.
Everything is just bytes (the words on the notes). RPC's are just one way of calling a direct method that gets translated down to bytes and then converted back up into a function call.
we dont know anything about eachother that wasnt in our predetermined starting knowledge.
So if you want me or anyone else to know something about the state, you have to tell us.
RPC are handy ways of sending commands back and forth that we both understand.
NetworkedVariables are convient ways for changes in them to automatically get sent over. Its all abstractions that take care of all the messy translation work to go from bytes to a specific object and value
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Thank you!
I'm looking for a solution to parenting objects in a 2 player card game. Before multiplayer I was parenting cards to the deck, hand, discard, board etc. Now I'm limited to only parenting with the server, so it looks like I might have to change how I was moving cards. How would you go about moving objects in multiplayer for clients?
For a card game, I wouldn't worry about parenting. I use a list of Card Ids for decks/hands. Instantiating and moving cards in game are all done locally after moving card id from one list to another
Hi, i have a issue of smooth movement with Photon Fusion 2 Shared Mode, i dont know where i can ask my question please
You can ask here but might get a better answer in the Photon server
I want to have a list of player gameobjects in the server only that things can reference, so I made the playerprefab send an RPC that tells the GameManager to go through the SpawnedObjects list and add players it sees. The list length is correct for number of connected players, but then in the NetworkBehaviour'd enemy script I try to reference the GameManager instance and get the list, but it seems to be incorrect. Is the enemy not going to reference the server gameobject? Is there a way to make it do that?
You would need a if(IsServer) check in your Enemy script to make sure its only running on the server
That makes a lot of sense thank you
is there any example of AnticipatedNetworkVariable or AnticipatedNetworkTransform? i want to create client prediction system
Reminder that Anticipation does not equal Client-Side Prediction
k i check it out thank you!
Hi! So I recently was recommended to look into decoupling my code in regards to networking for my game. From my understanding, network decoupling is where you separate out the code involving whatever networking I am using (in my case FishNet) from my core code, so that in case I need to refactor or swap to a different networking system it is easy to change my code.
I was just wondering, how easy would it be to decouple my networking code as a beginner to networking? Should I be doing that if I am planning on staying on Fishnet for my whole project? Is it common industry standard to decouple your code?
I would do it wherever you can, but wouldn't focus too much time on it, especially as a beginner.
In terms of wanting to do it for easy migration between networking solutions - FishNet is already very similar to other popular Unity networking solutions and migrating your code would be very easy and essentially just changing syntax.
There are very big differences between various networking solutions that what you are saying is simply impossible. Unless you try not to to use the specific/unique features of each solution and simply use the most common ones across different solutions, basically creating a bare-bones interface. This is simply a bad idea. And it will most likely not work in practice, due to the various small differences on how the different systems handle intricate details.
You just need to find the right networking solution for your game, and stick to it.
Industry standard is to write your own netcode.
Is Quantum 3 capable of using UGS Private Player Data? This data is only accessible from a server.
I'd also need the script to only be on the server, since it would have credentials for logging in that clients cannot have access to.
Also I just found out about photon Gaming Circle, which basically costs $500 for basic support and has more samples
It looks extremely scammy, basically sounds like they're denying basic tutorials for free users so they can sell this
Anyone using FishNet? Is it good?
Generally well received. Comparable to NGO and Mirror.
Haven't used either. Watching some tutorials now.
My main issue atm is that I really don't want to watch tutorials and try out 10 different networking solutions.
Took me 2 days to figure out Quantum and it seems pretty terrible for me
IIRC you wanted determinism - not really many better options (if any at all) than Quantum.
Yeah but it's not the most important thing, I mostly just want it for anti-cheat
The requirements for my game are:
- top-down 2d rpg
- fully server authoritative
- must be able to save/load character data on the server
- low latency, smooth gameplay
- fast paced action PvE & PvP
- lots of different zones to explore
- max 20 players / zone is sufficient, + if it's capable of more
- good documentation / easy to get started
Quantum doesn't seem very good for handling different zones or save/load systems
- it has basically no documentation unless you pay them $500/month
Anyone using Hathora? Seems extremely easy to set-up.
Does it support multiple zones/scenes? Why is their pricing not visible on their website, that's sus
Depends on what you mean by zones. A multi server setup is doable but it is non trivial, especially for a beginner. You can have your single dedicated server load zone scenes additively but that will be limited by hardware. Usually you'll get about 150 - 200 players max and that's if you really know what you're doing.
I think zones play the most important part to ditch the quantum
it looks like your game is similar to Online RPG
pricing is based on vCPU and bandwidth usage
been playing around with FishNet today and I love it ...
Hi! I have a quick question. I was just wondering what the best practice is for syncing projectiles in a peer to peer set up.
I was wondering if I should be making the projectiles network objects or if I should just have the spawning of the projectiles synced through rpcs. From the research I've done, simple, short-lived projectiles should be handled through RPCs, while multi-functioned, long-lived projectiles should be handled as network objects (No idea if this is a correct line of thinking or not, but seems to make sense).
Hey @ocean wadi,
It's not a bad way of approaching the problem. And it would depend on your use-case really.
The team summed up the design decisions quite well in the below docs that would help you to decide which approach to take :
https://docs-multiplayer.unity3d.com/netcode/current/learn/rpcvnetvar/
but yes, essentially if you want to keep the data associated with projectiles available longer for late joiners go with NetworkObjects, otherwise RPCs
Choosing the wrong data syncing mechanism can create bugs, use too much bandwidth, and add too much complexity to your code.
can someone pls help me set up photon for a gtag type game (vr) 🙏
Gotcha tyvm! ^^
Net stack agnostic question;
Any drawbacks to using AssetReference (Addressables) when dealing with object replication and coupling networked object ids to prefab assets? At first glance it seems pretty well suited, but before I start digging into it I figured I'd ask to see if anyone has any immediate reasons why it wouldn't be a good idea.
👆 Turns out this works great
I have an additional editor instance setup as a run config, and it takes forever to launch, any way to speed it up?
for example
it literally takes ~30 secoonds if not more to launch, my personal machine isnt garbage and my project isnt that large
How do delagates run in netcode for gameobjects? Is there a way to make it work like an rpc? This is an example of what I'm working with, it only runs on the server, even if the client is the one clicking the buttonendTurnButton.onClick.AddListener(() => { if (!GameManager.Singleton.IsPlayerTurn()) { Debug.Log("cannot end turn : Not current player turn"); return; } GameManager.Singleton.EndTurnButtonPressedRpc(); });
They don't change - they do not interact with Networking. You just need to make sure each client's instance is calling the AddListener.
Does that mean I need to make the button a network object or make it use unity events?
Your button just needs to follow this general flow:
- Client presses button locally
- Button press sends RPC to server
- RPC is received by server and needs to tell all clients the current turn is over
Making it a NetworkObject or using Unity Events won't really change anything.
A button is a button and doesn't directly have anything to do with networking. It is up to you to make it so that the press of the button sends info over the network via an RPC or NetworkVariable.
Okay thanks for the knowledge
I added in a yield return new waitforseconds(1) in one for the rpc calls and it works now. Is there a more elegant solution to timing issues?
You'll have to send your full code, I don't really know why that would change anything.
How would one handle spawning an ability from 1 of 2 players with Rpc for a class for setting up abilities that does not inherit from NetworkBehaviour? Basically, I am helping my friend set up and ability system for their game, and it works on the host, but when the other player tries to use abilities we've been encountering issues from it needing to be host (without rpc tag) or nothing happening (with rpc tag but no network behavior since now it looks for data like inputs from host). And when we do try with NetworkBehaviour it uses the variables from the host so things like when an ability was used don't get updated.
Problem: Getting player input from UI Toolkit to server
I'm in the process of converting the new UGS & Netcode for Entities action FPS template to RTS style.
Here's how things are happening right now:
- player clicks a UI button
- UI Document's controller mono code fires up the event callback
- the callback function spawns a "request" entity via EntityManager
- the player input system iterates over request entities, then writes to
IInputComponentDataaccordingly - the server input system checks
IInputComponentDataand spawns request entities for other systems
Snippet:
[GhostComponent]
public struct RtsPlayerCommands : IInputComponentData
{
// Lobby
[GhostField] public InputEvent IsReady;
[GhostField] public InputEvent StartGame;
// Fleet
[GhostField] public MoveFleet MoveFleet;
}
public struct MoveFleet : ICommandData
{
public Entity FleetEntity;
public float2 Destination;
public NetworkTick Tick { get; set; }
}
Can I even use MoveFleet like this? Is it possible to pass custom structures as command buffers?
Now, the thing is as you can see this system looks so complicated that I started to think I'm doing something terribly wrong.
I've initially thought about using RPC's for the entire "player input" system as this RTS game has no input other than commands. But after reading netcode manuals, they STRONGLY oppose against rpc for anything other than meta-game elements.
This is a bummer because a data only rpc of my custom types is simply what i need. Just have to write a system to map rpc's with Player ghosts. I lose prediction (iirc) but the system gets much simpler: spawn rpc request entity directly from the callbacks ( or just buffer a command queue to spawn from main thread )
And on the server, the related system can directly consume the rpc.
Am I missing something, or i should go with RPC's even though the docs say use command streams?
the full command system idea is
they are one-tick "messages"
commands are validated on server before they are processed
commands can be pre-validated on clients for clarity (like greying out UI elements)
executed commands only act on Ghost prefabs, they might also interact with server exclusive logic
I hope someone who knows this stuff helps because this became a huge roadblock for me as I need this to work to complete the main menu -> multiplayer game begin flow.
This is the first time i planned a game with this big architecture ( personal project for now )
Spawning Abilities
I honestly wouldn't try to cram a RTS into that FPS template.
I also wouldnt use input component data for anything other than direct player input.
RPCs will work just fine for mouse click events.
Check out the Unity Netcode discord server. We had some discussions on this with the devs
Hello. How can I force a client network transform to synchronize? Meaning that it would synchronize when I want instead of only when the object is moved.
For context, in my game if a player joins after a gameobject is moved, it wont be synced on the players client.
NetworkTransforms should sync for late joining clients.
well its not
That would indicate that there's something incorrect with your setup and/or management of the NetworkTransform - not that you need to force it to synchronize.
ive tried different settings but havent gotten it to work
i should note it was working before then i updated to unity 6 the other day and now its not working
What version of NGO do you have installed?
This may not be it, but if you're using a version of NGO that has Authority Mode on the NetworkTransform - you don't need to use the ClientNetworkTransform component.
But yea, use the regular Network Transform
I'm having a real issue in my script, so may a kind and gentle unity netcode user help me?
so I have a first script assisgned to a game object synchronized via network object, it references the variables for the names displayed on a leaderboard
everyone is getting a tag when spawning so this works very well (the owner of the server who is the first one to spawn will always get the tag 1, and the cients 2, 3 and 4 in order)
So the owner (with tag 1) is able to change the network variables
But the clients can't modify the network variables even via server rpcs
I've tried figuring this out for hours and even days but nothing I try work
All of this seems really confusing and unecessary to me
what's the end goal here?
WHy are you assigning custom tags to players instead of just using their Client IDs?
first time 😅
And why not just use the client ID as like the key to a dictionary or something
instead of having separate variables...
which implies a fixed number of players
The problem is that the clients aren't able to modify the network variables even by server rpc
I'm assuming networkNames is owned by the server and not the clients, so clients will not be able to modify the NetworkVariables.
As for the RPCs, you're not sending anything through them so the value will be set to whatever the server has for playerName which I'm guessing is not what you want.
I mean it's hard to tell what your code is even trying to do
where is this playerName variable coming from
Player name comes from an input field where every players enter their nickname and this variable is registered as it can be verified by checking the editor while running the code
How can I modify a network variable with a client?
the value of this input field needs to be sent through your ServerRpc
but... that input field is the one on the server when you're running server code
which clearly your players are not typing in
Send the name in the RPC, or, since you're basically just going to let the client set the name to whatever you want anyway it seems, you could also just let each client own their own network variables for their names.
I'll try setting a new network variable for each player thx
As owner, I suppose that the clients will be able to modify their own variable
Then, I'll try to get every player instance's network variable
And change the TMPs in consequence
For player names use a network variable on the player object with owner write permissions
Would I want to do something like above for all player stats? Working on more of an RPG thing with lots of numbers, so do I just attach a NetworkBehaviour with a half dozen NetworkVariables inside it on the player objects and use RPC to change values? I can kinda picture it but I want to make sure I'm not setting myself up for trouble later down the line.
Does anyone know how i can make it instant (its x scale)? (im using netcode for GameObjects)
Most likely, yeah. You can also use Owner Write Permissions to allow players to update their own data/stats.
You can also group related data in to a struct and make that a NetworkVariable if you find that you have too many individual NetworkVariables piling up.
I like the idea of a single struct network variable but probably not needed right off the bat
Isnt this just changing the vairable to the hosts player name?
Any other ways cuz im using network transform with owner authority and i get this error:
[Netcode] Non-authority instance of Player(Clone) is trying to commit a transform!UnityEngine.Debug:LogError (object)?
Make the sprite a child of the player object, turn off scale syncing on the NetworkTransform and use a NetworkVariable or RPC to flip the sprite manually.
Hi! So I have a question.
Pretty much I am trying to sync up my enemies across the host and clients currently. I am working on the Skeleton archer enemy, which charges up an arrow and then fires after a short duration. During the charge up time, the bow is pulled back, the weapon HOLDER gameObject rotates to face the player, and the enemy will flip horizontally to face the player, creating the effect of the bow rotating around the skeleton to aim at the player (2D top down game).
I made it so that the script that rotates the weapon holder syncs the rotation through the use of RPCs. But since there is a slight delay, when the enemy flips, the bow for a short duration flips as well, and then corrects itself when the observer RPC in charge of syncing the rotation corrects the orientation. While not a huge issue, it makes the enemy look really janky, was wondering if anyone had a fix for this.
Nah, the clients get their own name too
I understand what you meant to do. But what your code actually does is calls a server rpc and then on the server sets the name to the host/server player name. You need to pass in player name as a parameter
What is the best/most widely used solution for p2p?
I want to make a very simple p2p multiplayer game mode for my game,
My understanding is that Netcode seems to be the most widely used option?
Best is a matter of opinion. Most used is hard to say. Developers don't usually blog about their networking stack. Unity Netcode, Photon Fusion, Mirror, and Fishnet are the main Iibraries you'll run across. Bigger studios will roll their own custom solutions
So for uni we (class) want to make a lethal company style game. We just had a quick look to try and understand how a “moon” scene and a “maze” scene would work in multiplayer (p2p probably) but couldn’t find anything definitive that’s within a reasonable scope. Can anyone point us in the right direction or is it simpler to just teleport them somewhere else in the scene
(NGO ideally)
does anybody know how I can add a first person camera onto a player ghost prefab in netcode for entities?
What exactly are you trying to do there? I'm not too familiar with Lethal Company. I know that it does use NGO for its networking.
You'll want to use the DOTS Character Controller package
Oh ok thanks
The Competitive Action Multiplayer template is an FPS template will all that setup for you already
Yea I got that but I didn't understand it so I wanted to try to make copy of it by my own to make sure Ik how to do it myself but thanks
So like an inside the building scene and an outside the building scene, and a player doubles up as a host. We want to make sure that players can scene transition without everyone changing scene or something and the host remains host but aren’t super familiar with the system yet
Ok for that you would load scenes additively from the host. That's if you even need it to be separate scene.
It’d be a separate scene because the inside would be a procedurally generated bigger-on-the-inside thing
Using FishNet, would it somehow be possible to connect to UGS Private player data or like an sql database or something?
How would that work? I literally just started, but from what I see the client has access to all the same files & data as the server?
Are there like seperate files/folders that only go to the server? Or do you upload the account data (password / api key) to a file on the server or something?
Really no clue how this works or how to get started. But I need a clear answer on if this is possible or not (without doing crazy complicated/expensive stuff) so I know if FishNet is suitable for my game.
Using UGS packages, I believe combining the use of Cloud Save and Cloud Code would achieve what you want.
Wouldn't that cause issues where the client has the same "power" as the server and could just save whatever they send?
How would Cloud Code/Save verify the data is from the server?
I just find the whole FishNet server thing very confusing, since it's basically just another client acting as server if I understand it right?
The server will authenticate with a Server Account to UGS
There are also access controls that can block a client from accessing the different services
Which is exactly what I'm asking, where do I put the authentication details?
So far all I've seen is you program a client in unity, that also acts as a server, you can then press some buttons for several services that makes it a "dedicated" server, but the client would still have access to everything, including my authentication details. Unless there is a way to put those somewhere, somehow, which there probably is, but I don't know
Cloud Code Authenticates itself. If you are using a dedicated server then you can use a env file to store your Service Account credentials or use the ServerAuthenticationService
mate stop making stuff up
I'm not using a real dedicated server, it's created from the client with fishnet, as far as I know
which is exactly what I'm asking
No need to be rude. He's simply trying to answer your question.
The reason he's giving you details mostly related to dedicated server setups is because there's essentially no expectation of the level of security and authentication you're asking for in a Client-Host setup.
As mentioned above, Cloud Code is going to be your best bet.
But I'd still need to call cloud code from my client, which has exactly the same code as my server, so there's no way to differentiate?
FishNet just like all other networking libraries has plenty of ways to differentiate between client and host instances.
You can then verify any data sent through Cloud Code and be confident about that verification as it is not happening locally.
Yeah Fishnet has plenty of ways, but if one of my clients decides to adjust their client to think it's a server ...
You'll need to use fishnet to build a dedicated server if security is an issue. There is not much you can do if someone hacks your client.
but there are tools like edgegap that let you just start a server from the unity client, no setup required
Edgegap is a dedicated server provider..
this is the tool I mean
it just lets you run the game as a dedicated server
which again, is why I'm asking how I would get some form of authentication on it
Hi im using ECS and creating a system that is only simulated on the client side bit like a boid group that follows around the player's ghost object
I have some systems like spawn x amount of boid members connected to x player
I am struggling on how to communicate from one client to another to spawn said object because I don't know how to get a reference on every other client to the player / connection that is sending the RPC that says spawn this stuff to the server
This is like a very simple basic requirement for a multiplayer game not? A secure way and location to store player data? Why is it so hard to get an answer I can understand?
Like I can get the connection on the server's system from the RPC but how do I communicate that to the other clients?
If you are using Netcode for Entities then there is a predicted spawning system that you can use
https://docs.unity3d.com/Packages/com.unity.netcode@1.4/manual/ghost-spawning.html
perhaps I was unclear
the boid members are not ghosts
because I have seen no reason to make them so
Spawning them seems to be a reason to me. But your only choice in that case would send an RPC to instantiate the entities and then have another system created to keep track of them
would making hundreds of these things ghosts not just introduce an element of lag
their exact position does not matter at all
i just need x amount to be on x player and for that to be consistent between clients
and for their movement to be fluid
that's why I didn't make them ghosts
is that not the case?
I mentioned Cloud Code several times. Using it with Cloud Save is the way Unity recommends saving game/player data without giving clients access to the saving code.
yeah so what I do not know how to do is tell client 1 that it is specifically the client number 2 (and their associated player ghost from the linked entity group) that these needs to be spawned for
that's what I'm asking
If it's just like particle fx thing then sure. Just an RPC tell the clients to start the effect locally should be fine
in fact, does client 1 even know that there is a connection client 2?
No, the clients would not know about each other
hmm yeah so how then can I send an rpc from the server to the clients with a 'reference' so to say to the ghost object that it needs them spawned to
I would have an enableable ghost component on the player that you could use to trigger your boids
hmmm maybe but then each client would need some way of disabling it for themselves after the spawn is done for that specific client but if it was a ghost that's obviously not possible
perhaps I can have a ghost component that just says x amount of objects need to be currently spawned for this player but checking that and counting often seems costly
If its a timer then the local system can handle that on its own
its not
to elaborate it's a party game where you play as grim reapers collecting souls that follow you around
and you can steal other people's etc.
so I am making a system whereby say you complete a challenge that gives you x amount I need to communicate that to all clients
but I really don't want to make them all ghosts because the calculations for their movement is fairly complicated I don't want for tiny bits of lag to make them teleport all over the place and when you think you are walking into them to steal it its actually somewhere else but your connection just hasn't caught up right
like I prioritise most that when it looks like to the client they are here then everything you do to interact with them happens
thats why I didnt make them ghosts and just simulated on each client
NFE client prediction is actually pretty good. But if they aren't interacting with other players directly then its fine from them to be local only. A ghost field with the amount of souls for each player should work as well
yeah I think that's the fallback option but it's ideal if when you steal another player's soul it doesnt literally just despawn it and spawn for you I need to change that soul's target boid to the proper player's
and that system means that isn't possible
could a ghost list containing the player's ghosts work???
thereby if I say ghostlist index 1 wants to spawn souls then it would be consistent across clients?
though thinking about it I suppose this isn't possible except for the client doing the stealing if the souls are not ghosts themselves
because it is hard to say soul number 117 needs to move to player 3 on a different client
though I could just transfer across a random one for the other clients
cause the visual of them flying about to different players is a very cool one that I would like to preserve
and they are close enough together you probably cant even tell
so would this maybe work?
and I asked you every time how that stops my client from getting all my passwords?
I probably just don't properly understand how fishnet works, which I've mentioned several times as well and is exactly what I'm asking
If I add code in my game to save/load data through cloud code and then cloud save, then my client can just use that code to save whatever data they want.
So there must be some way to add code to my game that doesn't go to the client?
I clearly don't understand what you're trying to tell me, so repeating it isn't going to work.
For clarification, I do understand how a normal server works, I've worked with UGS and Cloud Code & Save.
I do not understand how FishNet works
then my client can just use that code to save whatever data they want.
Incorrect. This is the whole point of using Cloud Code.
I clearly don't understand what you're trying to tell me, so repeating it isn't going to work.
I'm offering suggestions and basic advice. If you don't want to go as far to read the landing page for Cloud Code's documentation, I cannot help you.
my questions have nothing to do with cloud code???
the way I sent a request to cloud code is by putting it in my game
my server is literally equal to my client
I start my game and click "start server" and then "start client" and then I can open another window to connect with another client if I want
there is no server specific code in the game
so it doesn't matter what cloud code does, if my client can just alter their files and pretend to be the server and send the same request
My issue is that there is no server for fishnet, it's just another client acting as a server.
Everything in the server is also in the client, as far as I know as a complete total beginner with FishNet.
So it would be impossible for cloud code to tell the difference between a client and a server, because they are identical
I've explained your two options.
- You trust FishNet to differentiate between a client and a client + server.
- If you don't because you are worried about someone modifying the game client, then you need to use a dedicated server.
From your perspective there are no 100% trustable parties in a Client-Host setup. Just because someone starts a Client+Server instance via FishNet in your game does not make them trustworthy. So spending time trying to 100% accurately differentiate between the two is meaningless.
That could work. You could also make them child entities of the players
The server would be a dedicated server ... It's still identical to my client though, as far as I know
If you are actually using a dedicated server, you would make different builds of your game. One for the server and another for the client. You can use preprocessor directives to include/exclude parts of scripts depending on the build type, as well as just entirely removing server-only/client-only scripts and assets depending on the build type.
There is also a dedicated server package that will help strip out things from each build
I am using net code for game objects and I want to set the playerController parent when the scene switches.
When the scene changes I run this code transform.SetParent(targetParent.transform);
But I get this error "NetworkObject can only be reparented under another spawned NetworkObject ". The object I am trying to set as the parent, does have the network object component. Any ideas?
When the scene changes
Where/when specifically in code are you doing this?
You'll need to wait until OnNetworkPostSpawn() before you try to reparent network onjects
im working on multiplayer, and the character controls the other players movement, not their own. ive been struggling on this for an hour so i just decided to come here
im using photon
show the code
for the player movement?
yes
how do i like put it in the special black box
so its not spam
''' hi '''
''hi''
'hi'
1 controls 2 and 2 controls 1?
That would mean that IsMine is returning true on Player Object 2 for Player 1 and vice versa. Which means the ownership of your objects is probably backwards.
I don't work with Photon, so I'm not sure how ownership is generally assigned - or how you're doing it for that matter
It was because i didnt attach the script to duplicate the camera for each player.. silly mistake
Ok now i can sleep at ease
When this event is fired OnActiveSceneChanged in the playerController
@red garnet Yeah, as said here you should make use of OnNetworkPostSpawn as NetworkObjects aren't spawned immediately when a scene change finishes.
Is OnNetworkPostSpawn a event that I would need to subscribe to in my controller?
it's a protected virtual function that's a part of NetworkBehaviour
Hm how would I make use of it then?
protected override void OnNetworkPostSpawn() { } should work in any NetworkBehaviour
Ah okay I see thank you
Another issue (maybe):
transform.SetParent(targetParent.transform); Does not seem to actually be setting the playerController as a child of targetParent though, and I get no errors. (That code is in OnNetworkPostSpawn)
actually seems like that method is never hit?
you can surround it in three ` next time to do this:
Debug.Log("Hello, world!");
How do big competitive games handle terrain collision? How do they prevent/check for cheating where players just walk through walls?
It’s usually a combination of integrity checking the client and validating the actions on the server. There’s no sure-fire way to protect yourself from cheaters though, which is why even the most popular games have very easy to access reporting systems and teams / admins monitoring the reports.
Hey
By simply running the same movement logic in the server too, thus completely eliminating the hack you described.
So, there is no checking at all, it just works.
Hi, can someone familiar with the Boss Room sample explain the advantage of using this ActionID wrapper instead of just a simple int, thanks :)
As explained, it just wraps an int "ID" value
I literally cannot find a single tutorial on how to get my terrain (tileset) colliders on the server.
Also the server would be very busy doing all those collisions checks.
Other devs have told me to do collision checking with my map on the client side.
I am not sure what you mean, you would simply run your client movement logic in the server too. This implies using client side prediction, it wouldn't work with client auth movement.
Probably because a struct is more "user friendly", or it has some helper methods.
it doesn't have any helper methods, just boilerplate
public int ID;
public bool Equals(ActionID other)
{
return ID == other.ID;
}
public override bool Equals(object obj)
{
return obj is ActionID other && Equals(other);
}
public override int GetHashCode()
{
return ID;
}
public static bool operator ==(ActionID x, ActionID y)
{
return x.Equals(y);
}
public static bool operator !=(ActionID x, ActionID y)
{
return !(x == y);
}
public override string ToString()
{
return $"ActionID({ID})";
}
Then most likely to simply add type-ness to the integer, since a raw int can be misinterpreted and used incorrectly while when wrapped in such a struct it would be differented from raw ints.
I think it's better not to focus too much on things like this because something like this fully depends on the original writer preferred way of doing things, and usually there is no strong reason for it.
Thats what I figured, just was wondering if there was something I was missing
I have noticed this sample to be very over engineered.
For a sample thats meant to be tinkered with its a good thing if anything in my opinion
But that might just be me as I'm specifically using it to learn about system design
Good system design does not mean overengineered. Things should be kept as simple as possible.
This is the KISS principle, which is very important in proper design.
I am not a fan of Boss Room
It is a good exercise in jumping into a preexisting project with no idea how/why anything was built.
For what it is and the actual content, sure it's overengineered yeah
If you guys have any better resources please let me know for sure
Depends on what you want to learn
i've found exploring projects exactly like that the best way for me to learn how to do it myself
Best way to learn is to do things yourself.
That's how you learn why someone did X instead of Y. Because you might do Y initially and discover its subsequent issues, which causes you to rewrite and do X instead and find better results.
Otherwise you wouldn't know why someone did this instead of that, etc.
The NGO bite sized samples are not bad
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-introduction/
If you are into long form video tutorials, Code Monkey recently released some multi hour courses on the NGO and NFE.
The Bitesize Samples repository provides a series of sample code as modules to use in your games and better understand Netcode for GameObjects (Netcode).
how to get ghost entity from ghost id on client?
Maybe GetFirstGhostTypeId()
That returns an int from an array of ghost instances
But nvm I was being stupid you just query ghost instance
I'm trying to set up multiple play mode instances for testing multiplayer, and I see there's this tag that I can change for each instance. How do I read the tag to change the behaviour of my scripts, though?
Its CurrentPlayer.ReadOnlyTags()[]
https://docs-multiplayer.unity3d.com/mppm/current/player-tags/target-network/
This example shows how you can use the Network Simulator and Players to test different network connections in Multiplayer Play Mode.
thank you! I was trying to google everything under the sun but unity 6 resources are getting buried
Hey guys - Sorry if this has been asked before, but how do you get around sending a Transform over the network? Do you split it into its respective Vector3's and send those? Or what are your clever tricks?
It kind of depends on your setup and what values you want from what perspective.
If I want Transform data from the sender's perspective at the moment in time they send the info, then yeah, I'd probably grab the position/rotation/scale and send it over.
If you're okay with the Transform data being based off of the receivers perspective at the moment in time they receive the message, then I'd probably send a NetworkObjectReference or NetworkBehaviourReference and just grab any Transform data from that on the receivers end.
Oooo, that's creative. I like it
idk if this is the right channel for this but how do i get access to the unity cloud organization
The owner of the organization has to add you to it
i am the owner
Can you log into https://cloud.unity.com/ and see the DevOps repos
apparently the subscription didnt go through before
devops wasnt enabled
i didnt notice
must have been a connection error
Hi everyone, i'm making a basic multiplayer fps and have some question about setting parents.
I'm using the animation rigging package to "attach" the weapons to the player, and wanted to set the weapons as children of a Rig, like it's show on this video: https://www.youtube.com/watch?v=s5lRq6-BVcw&t=525s
However, from what i understand, in order to do that, the rig itself would need to be a prefab with a network object, and i would have to manually spawn it first, is that correct?
In fact, not just the rig, but every part of the player visual would need to be turn into a network object.
I'm wondering if there is a better approach to this
Working with humanoid animations in Unity
Animation is a crucial part in games and Unity’s Animation system has been supporting projects for several years. In this video we will show you how to use the Animations systems in Unity to import existing characters and animations into your project. We’re going to look at key tips and techniques for w...
If you are on NGO2, NetworkRigidbody.AttachToFixedJoint() is an alternative to parenting
I'll take a look at that, thank you!
So I'm trying to call a ServerRpc from the client when it presses click to use my flashlight and toggle the light in all clients.
The thing is that it gives me a "KeyNotFoundException" every time I click when calling the ServerRpc, not really giving me any more insight.
FlashlightObject's class inherits from UsableObject (a custom class to make everything modular) which inherits from NetworkBehaviour.
The flashlight's GameObject with the flashlight script is inside my player's object holder inside a NetworkObject.
Can someone tell me why this happens and how to fix it? It's been haunting me for the past two days and I've searched everywhere for a solution. 😭
Do you guys know why this is returning a null PlayerObject for a client who connects?
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
playerUi = GetLocalPlayerUi();
}
private PlayerUI GetLocalPlayerUi()
{
return NetworkManager.LocalClient.PlayerObject.GetComponent<PlayerUI>();
}
I figured out it's when it spawns in the scene while disabled. I'll look into this. :b
Hey guys, i have tried the Unity Friends Sample, and its quite nice that you can get real time updates over ur friends (online status & bio) send and receive friend requests.
I want to know if there is anything related to custom notifications between friends, my objective is to aim for a party invitation system, so i just need to know how to send custom "message" with callback to the sender once the receiver chose to accept or cancel.
Thanks 🙂
Is it normal for the console to spam these random looking messages when I start my game in the editor?
Hi, When I change something like the colour of a sprite of a network object, will it automatically sync across all clients, or will I need to create a client RPC
I want to make a game similar to 'Muck'. Would using Network Transform for each NPC affect my game's performance? If it does, what can I do to prevent it?
Im doing some advance netcode for gameobjects INetworkSerializable work. Id like a second opinion on some of the design choices Im considering. My basic issue is I have a set of """Layers""". Each Layer can contain a List of """Features"""". Each Feature can be individually editted by who ever is currently using the drawing tool. I was considering a NetworkList of NativeArrays<Feature>. In this, each element of the list would be a layer, and the NativeArrays would be the individual features. Im somewhat concerned that this approach wont send the deltas in the individual features correctly though. Thoughts?
Id like to avoid spawning in additional network objects if possible. While it would be trivial to just make each layer its own network object, they're all handled through the same system and its just extra clutter
@blazing arch You likely need either a network variable or a RPC to sync the change. Any code thats not 'networked' will be executed as if your running in single player (Assuming your using Netcode For Gameobjects)
Personally, Id go with a NetworkVariable for your usecase, that way late joiners can also see the color change. RPCs are one and done, so if you miss the RPC, you miss the change in color
I'm quite new to unity and c#, (about 20~ hours in), is it possible to make the sprite renderer object a network variable
Or should I create a new variable, called spriteColor, and check the value of the spriteColor in the OnUpdate method
Or should I create an event, and subscribe all clients to the event, and call the event on the server?
Network Variables can only be made from 'structs'. This basicly means that the 'type' of data must be fairly primative. This means that the sprite renderer, which is a class rather than a struct, cant be made into a network variable. Instead, what i would do is delcare a network variable that stores the color (private NetworkVariable<Color> _colorNetworkVariable = new();) and then subscribe to its OnValueChanged event
You can read more about how it works here: https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/
NetworkVariables are a way of synchronizing properties between servers and clients in a persistent manner, unlike RPCs and custom messages, which are one-off, point-in-time communications that aren't shared with any clients not connected at the time of sending. NetworkVariables are session-mode agnostic and can be used with either a client-serve...
The basic workflow would be that you would setup a public void ColorChange_Rpc(Color spriteColor) rpc that would send a color to the server. The server would then update the value of the color variable. Finally, this change is sent to all the clients, who would then execute the code to change the color of the sprite renderer
ahh, thanks a lot
hello! quite often I get a Rate Limited Exception from GetJoinedLobbiesAsync(), even if I know for sure I haven't called it for a very long time. is it possible that it happens because I did another lobby request right before? I assumed their rate limits would be like, individual per function, seeing as they are listed as separate in the Rate Limits doc
It'll be helpful if you refer to stack overflow's question asking structure, and attempt to follow the structure somewhat. With you details you provided, it's not possible for anyone to help you out.
Nah
hii, im using Unity 6 trying to get a networking object to spawn and move, and currently works, but when I spawn 2 cubes, both players move around when touching the screen (its also a mobile game). I ran into a HasAuthority() so for my movement I have some debugs to track and when I run the game in the editor the debugs spit out correctly (host debugs Client owned, and player2 debugs Not Owned, but both objects are still moving around:
void FixedUpdate()
{
if(!HasAuthority))
{
Debug.Log("Not Owned");
}
else MovePlayer();
}
// in MovePlayer I have the Client owned debug at the top of the function ***
void MovePlayer()
{
Debug.Log("Client owned");
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPOS = touch.position;
Debug.Log("TOUCH POS: " + touchPOS);
// Create a ray from the camera through the touch position
Ray ray = Camera.main.ScreenPointToRay(touchPOS);
RaycastHit hit;
// Cast the ray into the scene
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
// If the ray hits an object
Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.yellow);
Debug.Log("Did Hit");
Debug.Log("HIT POINT: " + hit.point);
//transform.position = new Vector3(hit.point.x, hit.point.y, 0);
targetPosition = new Vector3(hit.point.x, hit.point.y, 0);
}
else
{
// If the ray doesn't hit anything
Debug.DrawRay(ray.origin, ray.direction * 1000, Color.white);
Debug.Log("Did not Hit");
}
}
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}
Does someone know how to handle this communication with Friends System?
You would have to implement this system with the messaging system Friends provides.
There's a callback for when a message is received. You would just have to put in some sort of "InvitationResponse" data in the message, and have it be read through the callback to see whether it was an Accept or Decline.
please
Probably not, so long as you’re unloading NPCs not in sight
how do I specify movement based off who owns the client? Ive tried isowned/hasuathroity and netObj.SpawnWithOwnership(clientId) ?
IsOwner, HasAuthority and IsLocalPlayer are all options depending on your setup
thanks
Hi guys! I'm using Distributed Authority in webgl project. In editor it works, but after Build and Run it doesn't. Specifically in Try and catch block it doesn't provide answer after await Multiplayer.Instance.CreateSessionAsync(options);
{
Debug.Log("Starting session..."); // this message is printed
// options setup code which use distributed authority
ActiveSession = await MultiplayerService.Instance.CreateSessionAsync(options);
Debug.Log($"Created session with ID: {ActiveSession.Id}"); // doesn't print this mesage
}
catch (Exception e)
{
Debug.LogException(e); // doesn't print this message either
}
finally
{
Debug.Log("final block"); // doesn't print this message either
}
Anybody have any thoughs why this doesn't work?
P.S I use UniTask, as somebody said that threads won't work on webgl build
im trying to set up a lobby rq for online multiplayer and trying to follow the docs, kinda struggling bouncing around different documentation pages and what not ngl. Anyways I installed the services package and copy/pasted the create lobby example of the docs but im getting an error on not importing it correctly ig:
using Unity.Services.Lobbies;
/// ...rest of code
string lobbyName = "new lobby";
int maxPlayers = 4;
CreateLobbyOptions options = new CreateLobbyOptions();
options.IsPrivate = false;
Create lobby isnt being read, and under Unity.Services.lobbies (Services), im getting an import error
Any reason you're not using Sessions instead? You may find it easier than using Lobby directly
im trying to learn networking and just looking up tutorials. I found some nice CodeMonkey ones but they were using a deprecated lobbies package so im just into a rabbithole at this point
ill look into sessions then and see if thats easier, lobbying seems to be overcomplicating things
You can build one pretty easily with cloud save. Update the MMR in the player data after every match then use that in you matchmaking rule
Hi, Can somebody explain me why MultiplayerService.Instance.CreateOrJoinSessionAsync(_sessionName, options); is able to connect by using _sessionName (which is just a text from input field) instead of actual sessionId?
You can join a session by name. If it doesn't find one by that name it will create one with you as the owner
There is a join by ID function, but you already have an ID then there is no need to create a session
Hey I have an issue, when 2nd player joins
Player Spawned. IsOwner: False, ClientID: 1, LocalClientID: 0 UnityEngine.Debug:Log (object) MultiplayerPlayerMovement:Start () (at Assets/Futbol/MultiplayerPlayerMovement.cs:24)
i can only move the player 1, the session owner, the second player does not register input
I understand that it can join by session name, question is why? As In documentation it says that it accepts sessionId, not the sessionName.
Oh the session id can be any string. so its just setting the name as the session id
Are you sure about that? As I have created another method which uses JoinSessionByIdAsync(string sessionId, sessionOptions), and when I have passed sessionName it said that lobby doesn't exist.
That's what I'm doing CreateServer method:
{
Name = _sessionName,
MaxPlayers = _maxPlayers
}.WithDistributedAuthorityNetwork();
_session = await MultiplayerService.Instance.CreateSessionAsync(options);```
In JoinServer method:
```_session = await MultiplayerService.Instance.JoinSessionByIdAsync(_sessionName);```
And this is CreateAndJoinMethod:
``` var options = new SessionOptions() {
Name = _sessionName,
MaxPlayers = _maxPlayers
}.WithDistributedAuthorityNetwork();
_session = await MultiplayerService.Instance.CreateOrJoinSessionAsync(_sessionName, options);``` - have no idea why this is working, and other two methods don't
Oh, CreateSessionAsync() doesn't use the name for the ID, I believe it will have a GUID generated for the ID
Okay that would explain whole situation. But where did you get this information from? I thought Name is stored in the SessionOptions parameter, no?
The API docs are not very clear. You have dig into the source code of the session manager to see how the sessions are created
Got it! At least now I know 🙂 Thanks
Any idea? not sure what I'm missing
Usually this happen if you aren't checking isLocalPlayer in your input script
oh i was checking isOwner instead
Just realized that means the session owner and not the local
Still, 2nd player is unable to move
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
A tool for sharing your source code with the world!
hasAuthority can work too
same results using hasAuthority
Oh, Change Start() to OnNetworkSpawn()
Start runs before it connects to the network
Yea... same stuff
i can move the player that creates the session
but not the 2nd player joining
A tool for sharing your source code with the world!
this is the code
I'm unsure if I have to change anything on the network manager?