#archived-networking
1 messages · Page 20 of 1
is that method declared in a spawned NetworkBehaviour?
Is this using Photon or NGO?
they said they are switching from Photon to NGO
Derp totally skipped over that part.
Every other responsibility the prefab is responsible for works just fine
If using relay with NGO, do we need a heartbeat for the relay like we have for lobby? It seems like relay doesn't allow connections after the first 10 sec
Wait @sharp axle, was I supposed to config this variable to make this code actually remove the player
No the Unity Transport takes care of that
That's the amount of time the player can be disconnected before it's automatically removed.
I didn't think that effected the relay integration removing the player. If your players are not mobile setting to 0 should be fine. Just know that any dropped packets could kick the player in that case
Well the min is 10
So ig I have to set it to 10 and not 0
Also do you know the rate limit for SendHeartbeatPingAsync?
How often should we send it
So ig it gets auto disconnected after 10 sec now, is there a way to make it so it's instant?
(using unity's lobby system when joining a lobby)
does anyone know what this means? and yes the lobbyId/code is the same when joining and when created.
the invalid character is always different
a few days ago it worked and now this?? idk what i changed to cause this
code:
{
try
{
JoinLobbyByCodeOptions joinLobbyByCodeOptions = new JoinLobbyByCodeOptions
{
Player = GetPlayer()
};
Lobby lobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, joinLobbyByCodeOptions);
Debug.Log("joined Lobby: " + lobbyCode);
}
catch (LobbyServiceException e)
{
Debug.Log(e);
}
}```
Error:
you're inputting the lobby ID and not the code
either change it to be JoinLobbyByIdAsync or actually use the lobby code (which is 6 characters compared to the 22 of hte id)
ah thx makes sense
Can anyone tell what's the ideal way of setting these values?
MaxPacketQueueSize & MaxPayloadSize
Like for a game with 5-20 players what should be the value?
I found this on the forum is this correct?
MaxPacketQueueSize is (Clients * Clients + 10) * 2 (10 for a small buffer, 2 for the reliable message system)
MaxPayloadSize is: ((Clients + 10) * (sizeof(float) * 3 * 3) * 10 (10 again buffer, the flaot times three shall
represent the Transform at the Client spawn, and times 10 just as safeguard not being to low)
I believe that forum thread is still mostly accurate. If it's this one
https://forum.unity.com/threads/maxpacketqueuesize.1317384/
We have to set these values before starting host or server correct?
I'm not sure. There is a Transport channel over on the Unity Netcode server. The devs respond there pretty regularly. The link is in the pinned message here.
Ohh okay I'll check it out
How to manually spawn player object? Any idea how to do it? (Netcode)
Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:
So just this? GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId); and that is all?
Btw, should I update my unity editor? I have netcode 1.2 and now it is already 1.6
You'll need to instantiate the prefab first to use getcomponent but yea. also NGO is on 1.7.1 now
Keeping up with patches for whatever major releases you are using is probably a good idea in general.
Okay, but unity 2023 isn't LTS yet right?
I believe 2023 LTS will be called Unity 6
🔥
Does the fee apply on it or will it be applied on unity 2024?
It will
Why does my host get this error when a client leaves?
ArgumentNullException: String reference not set to an instance of a String.
Parameter name: s
System.Text.Encoding.GetBytes (System.String s) (at <787acc3c9a4c471ba7d971300105af24>:0)
Unity.Netcode.CustomMessagingManager.UnregisterNamedMessageHandler (System.String name) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/Messaging/CustomMessageManager.cs:218)
Unity.Netcode.Components.NetworkTransform.OnNetworkDespawn () (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Components/NetworkTransform.cs:2524)
Unity.Netcode.NetworkBehaviour.InternalOnNetworkDespawn () (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/Core/NetworkBehaviour.cs:529)
UnityEngine.Debug:LogException(Exception)
Unity.Netcode.NetworkBehaviour:InternalOnNetworkDespawn() (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/Core/NetworkBehaviour.cs:533)
Unity.Netcode.NetworkObject:InvokeBehaviourNetworkDespawn() (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/Core/NetworkObject.cs:1248)
Unity.Netcode.NetworkSpawnManager:OnDespawnObject(NetworkObject, Boolean) (at
How to play sounds to all clients? As for now I just play sounds locally and playing sounds using Rpc is one of the methods that I came up and actally working but is it a good practice?
If you send the RPC unreliably, then yes that is a very typical way to do it
(assuming the sounds don't matter too much and are sent quite often, unreliable RPC is the way to go)
but as with everything in programming, it really depends
Unreliable rpc. Whats the diffrence
I know how to code it and how code works
But I dont know how Reliability works
"This means they're guaranteed to be received and executed on the remote side" that doesnt explain to much
you should probably do some research on it, unreliable RPCs are significantly cheaper to send, but the tradeoff is that they don't always arrive
if the packet gets dropped, it will not attempt a resend
reliable RPCs will ensure that they arrive at some point, even if they get dropped
it will resend it
So that means sometimes with poor connection it may happen that I wont hear another player shooting for example?
yes
Ok thanks
How to create server browser for Game Server Hosting?
Is there a plugin or script I can use to expose all the values of every network variable that I’ve set?
I’m a visual person and I’d like to actually SEE the values in editor
Since theyre not serializable you cant expose them in the editor easily
The only easy solution is probably to just make a serialized field and copy the value of the network variable into the field in Update
You can set the Inspector to Debug mode
I’m shocked there’s no plugin made that does this already. Hm.
How do I do that?
I believe its in the 3dot menu in the top right of the inspector window
I have a SpaceshipMovement script that I would like to be able to be controlled by different players, meaning that based on something like a 'currentPilotId' variable or through other means, the script could perform its functionality on the spaceship rigidbody based on keyboard inputs from a chosen client or host. How would you go about making something like this?
What networking package are you using?
@sharp axle NGO
You can use either SpawnAsPlayerObject() or SpawnWithOwnership() then you movement script can just check if(IsOwner)
What's the difference and do you recommend a specific one?
The first one makes the object a Player Object. The second just gives the client ownership of it. If the client can control more than one ship then use the second one.
Could I just change ownership of movement script throughout the game? @sharp axle e.g. when new player is piloting
sure
Ok thanks a lot for the advice, with being new to multiplayer this is very helpful
I keep getting The name 'isOwner' does not exist in the current context
I have 0 idea what I am doing wrong. I have tried using localplayer instead but I got the same result
looking at the docs.. isn't it a property ? IsOwner
isOwner and IsOwner are very different things
You are so right I feel extremely stupid 😭
Right after pulling my project with free download PlasticSCM, my NetworkManager looks like this. I need to run the scene, stop the scene, run cm update with PlasticSCM, change scenes in the editor, and go back to the original scene, then it gets populated
that is odd, can you replicate this?
I personally use git and never had a problem, it even works cross platform, cloned it on a linux machine and it just works, so it is strange that you have to jump through these hoops
if you can replicate this, I would recommend opening up a support ticket, as this isn't how it is supossed to go
Hey my unity project is working over public ip/port forwarding. Can i just upload it to itch.io as a webgl build now and that should connect to my server the same as .exe does?
Ive configured WSS and SSL
If you have configured it properly, yes
just try it out
Hi, I’m hoping to share a gameobject transform (for example), with extremely low latency on a local network. I just tried in a project we have here using Mirror and there was quite noticeable lag. What is the way to achieve the lowest possible latency over LAN? 🙏
It looks like unity sample is more complicated than samyans YouTube tutorial. Is it true? https://github.com/Unity-Technologies/com.unity.services.samples.matchplay
https://m.youtube.com/watch?v=FjOZrSPL_-Y&pp=ygUWdW5pdHkgZGVkaWNhdGVkIHNlcnZlcg%3D%3D
A Matchmaking with Multiplay Unity example project. Implements the Unity Matchmaking and Multiplay SDK to create an end to end matchmaking game experience. - GitHub - Unity-Technologies/com.unity.s...
📥Get the Source Code📥
https://www.patreon.com/posts/82134830
If you liked this video please like and subscribe as it helps me a lot, and consider joining my Patreon or becoming a YouTube Member :)
►Check out the Previous Video
The Ultimate Multiplayer Tutorial for Unity - Netcode for GameObjects
https://youtu.be/swIM2z6Foxk
⚙️ Set Up ⚙️
►Mul...
Thanks I’ll look into that. I made someone using default Unity stuff about ten years ago, and over wired lab it still had significant lag. Is there any differences between different services, Unity inbuilt, mirror, photon, fishnet etc?
No, that was question
Ah right 😅
How can I teleport all players to a position with NGO? I made it so that when a player touches something, all players are supposed to teleport to a specific location with a serverrpc that calls a clientrpc. This only calls a single player to teleport tho, but it doesnt seem to work every time? and sometimes the player colliding with the trigger teleports back and forth on the other player's screen, as if they are going to the new location and back immediately (it's P2P so one player is host)
Hi - I have developed a game and am testing it, and my co-developers have asked me to rent a server to test out some bugs. It is quite expensive, and I have a fast PC sitting around doing nothing, so I thought i would just set up that PC as the server and leave it on all the time. I've used SteamCMD to install my own app to the local machine and followed all the same instructions that an external hosting provider gives for setting up servers, but they all stop helping at the point where they say "now go download the CSGO server software". Obviously i'm not installing counterstrike and my game does not have its own self installing server software, so i have a vague idea that i must create my own server config file etc, but i cant find any documentation on how to do so
Hey I have a quite complicated project going on.
We are currently building a PoC for a School Project, it involves a very basic FPS shooter with the whole multiplayer and backend being doing in Java and communication is done using gRPC (the assignment itself was around java and gRPC, and we wanted to make a game with it).
We already implemented the authentication and that worked great, currently this is what's happening:
User starts the game, the Login Scene is visible.
User Logs in and lands in the MainMenu Scene.
User Presses on the Play button and lands on the MP_Browser Scene, which is just a ServerList basically.
Now here comes the tricky part, when the user finds a server he likes and presses join a few things should happen:
- The Code will send a ServerDetailsRequest to the specified server, this will return the Netty Port. The Netty Port is used for the websocket that's purpose it is to receive and send data bidirectionally (movement, shooting etc.)
- it will send a JoinServerRequest to the specified server that has 2 different outcomes:
Outcome 1. The Server responds with success=true and message=AOK - The User is not banned and Server has sufficient slots free for the User.
Outcome 2. The Server responds with success=false and a message - This means something is preventing the user to join, this could be that the server is full or the user was banned from this particular server.
Now we have a couple of questions on how to proceed:
-
is Websocket the way to go? if so what data should be transmitted and how, and if not what are the recommended alternatives?
-
How should I handle the loading? should I keep the Player in the MP_Browser Scene and just show a canvas with some loading text? or should I do something else?
-
How do I actually do the Movement and stuff? The question is a bit difficult, but basically how would transmitting and receveiving movement updates work?
This is what I thought how it might work:
I join a lobby and start moving, on each move the Client sends a message to the Server saying "Hey I just moved to these coordinates".
The Server then compares them to the previous coords to make sure he doesn't suddenly appear on the other side of the map.
If everything appears to be fine, the Server broadcasts those coordinates to all connected players and that will cause the characters to move?
We have a free Humanoid RPG Character from the asset store that has animations, how would we move the player from coordinate to coordinate without them just teleporting around? -
what about bullets and hits? How would I transmit shooting and how would I check if the player actually got hit?
Thanks for reading and I hope someone might be able to help
PS: Feel free to @ at any point
Many many differences yes
From performance to architecture to server availability to player counts, to latency, etc
Thanks. I just want the lowest latency solution for up to 10 people in the same physical space in VR
For a long time, most network service providers would also provide many variants. As a multoplayer server for an RTS vs FPS etc has a lot of difference in requirements
The server as authoritative source of truth, clients syncing to that
Security/cheating etc. no issue
Yup that's one way to do it
But given that scenario, which networking stack/system would be a wise choice?
Rather that's a pretty common structure with any of them
But in short, for VR games, we almost entirely use photon. I think it mostly comes down to preference and comfort and effort
It's the best documented, most battle tested and longest supported IMHO.
Why do I get Exception: Teleporting on non-authoritative side is not allowed!? I am running ClientNetworkTransform.Teleport() in a ServerRpc method, is that not authoritative?
Hi, I've got a question
public void DrawCardsServerRpc(ulong clientId, int numberOfCards)
{
[... code]
zoneManager.MoveCardServerRpc(cardId, ZoneType.Deck, ZoneType.Hand, clientId);
}
}```
This serverrpc calls a serverrpc on another object (because the movecard function is a serverrpc clients can call directly so I just made it use the same method).
I've heard a serverrpc can only be called by the client, but it seems to work fine here, it does that it's supposed to. Should I be worried about having it set up like this?
This will only work on the host. Only a client can call ServerRPCs
The server does not have authority over Client Network Transform
Ah yeah that makes sense, it do be a host.
What's the best way to go around this issue? Should I just have a MoveCard method in zoneManager that's not a serverrpc on top of MoveCardServerRpc
Yea. Unless you have reason for clients to initiate a card move on their own. It should probably only be handled by the server
Alright yeah makes sense thank you!
How can I teleport both the players at once then? I also tried making a serverrpc inside the players’ own script that calls a clientrpc to teleport themselves but it doesnt call both, only for the person who touches the trigger
The server will have to loop through all the clients and then call a clientRPC on each player to teleport.
So the serverrpc calls a getcomponent on the players for a script that has a clientrpc that calls ClientNetworkTransform.Teleport()? But I thought documentation said that serverrpc calls all clients at the same time by default 😭
I’ll try that tho thank you 🙏
RPCs are tied to their gameobject. So each copy of that object on every client will get the clientRPC call.
So it’s more a way to sync the data? Every loop it moves a player and tells the other players that it moved? (And in that sense it runs for all clients)
Depending on what you code the RPCs to do yea. The network transforms use network variables under the hood
Ahhhhhh I see, thank you so much oml ive been so confused but I guess I had the wrong idea in the first place
Hey, really sorry to bump this but I need some help from people with more knowledge
Anyone pro at webgl setup? I just need to get it uploaded somewhere for free to test. I have a dedicated server that works flawlessless with .exe on different wans
hey everyone. i'm making a multiplayer fps, following the tutorial by "bananadev2". im just here to see if anyone would be kind enough to walk me through how i can set it up that when a room is created or joined, it puts you in another scene
im open to a vc call so i can screen share and i can learn as im newer to the photon stuff
var status = NetworkManager.Singleton.SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);
if (status != SceneEventProgressStatus.Started) {
Debug.LogWarning($"Failed to load SampleScene " + $"with a {nameof(SceneEventProgressStatus)}: {status}");
}
that should work
this obviously need to be included:
using UnityEngine.SceneManagement;
Hey quick question,
what's the best way to transmit movement to the gameserver and then to all the other players and how do I trigger walking animations when the player receives a movement update for other players
sounds very confusing xD
so I want to update all other players when Player A moves.
Whats the best way to tell the Gameserver that Player A moved, and how do I tell Players B-E "Hey Player A just moved, from xyz to xyz" and then trigger the walking animation fro Player A
if you just want to sync the animations use the network animator
if you want that information as well network vars and network transforms are a good way if doing that
you should use some kind of network transform anyway for playermovement
does that also work when I have a custom networking system?
Your custom networking system should have its own equivalent of Network Transform
sorry that im back but it still doesnt seem to work for me, am I still dumb? Currently it kind of works but it always only sends over the client, not the client+host player.
Here is the basis of what im doing:
This
[ServerRpc(RequireOwnership = false)]
public void PlayerDeathServerRpc()
foreach (GameObject player in players)
{
SCR_First_Person_Controller cntr = player.GetComponent<SCR_First_Person_Controller>();
cntr.PlayerDeathClientRpc();
}
And here is the other one
[ClientRpc()]
public void PlayerDeathClientRpc()
{
if (!IsOwner)
return;
ClientNetworkTransform cnt = GetComponent<ClientNetworkTransform>();
cnt.Interpolate = false;
cnt.Teleport(new Vector3(0, 1, 0), Quaternion.identity, transform.localScale);
cnt.Interpolate = true;
}
again apologies if it's too much of a bother but I just dont get it
Synching Movement / Anims
Hi all, so I am dealing with an issue of "jitter" for clients. This is because I am allowing the client to move immediately on their end, and then when the server is done processing it's moving the client again.
Basically client moves say two steps, but because of latency the serer will move the client back one step once it sends positon to client.
How else can I get the player objects to move on the server and be visible to clients, because cleary this isn't the right approach
does anyone have a recommendation for a good free or cheap example or package for a first person character controller using Netcode for GameObjects? The starter asset works okay but I'm looking for some examples of adding in animations from a first person perspective with a networked controller
I'm getting this error when I upload the newest build to my website
RangeError: maximum call stack size exceeded
at invoke_ii (http:mywebsite.com/Build
web_build.framework.js.gz:3:371759)
at wasm://wasm/04d1fa46:wasm-function[5506]:0x18a4dc
any idea what's happening here or how to fix it?
the build works fine connecting to the server from the editor
but as soon as I upload it to the website and open it in chrome it throws this during loading
You keep a list of states and time stamps. When the server sends an update you compare with your list and then resimulate if necessary.
But I’m confused how to actually show the movement across clients? When I remove that portion of code I showed, clients do not see any other objects but themself moving
Lerping to the latest position should work
Setting transform.position via a ClientRPC called by server is doing two things for me :
- Allowing all clients to see other clients and host movements (good)
- Causing jitter, since the client moves locally and then is reupdated by the server RPC.
How do I get rid of 2 without getting rid of 1 also? Right now if I remove tranform.position setting via ClientRPC called by server, it no longer does 1 or 2, so clients aren't seeing anything on their end
Nvm, I figured it out. I just needed to add if(IsOwner) return
How do i check if im already in a lobby? I've been trying to use ``await LobbyService.Instance.GetJoinedLobbiesAsync();
i want to add a map selection feature as well. whats the best way to go about it? im new to photon and stuff so im learning how to do things best.
I haven't used photon, but you would just have a selection screen which defines the string of the scene yoz want to load
as for how to load it, you have to look into the docs of pjoton, that example was for unity ngo
i guess a better question would be, if i have the map select and i have the connected users connect to the room and then get switched to the scene, would that work?
okay
in ngo it works at least, that is my whole scene switching code
may i dm you so i can work this out? ive never actually done multiplayer this in depth, so a helping hand into it would be great since photon's docs are pretty useless
sure, could take a while till I can respond in depth tho, I'm on my way to uni
no worries. i may scrap what i have and restart so its easier to work with
im making a multiplayer fps. would you have any tips on the best way to go about it?
prototype, get your stuff running and failing as fast as possible, with as much as possbile done.
you have later time for refinement.
This is iterative engineering and a technique I use for various things like video scripts, writing code, game features, solving any complicated problem, ...
if you mean the network side tho:
get it running with client authority and if that works start working on server authority you want to use client side prediction for that, idk if photon includes that per default ngo does not
sick. i appreciate it
can someone tell me, in a dumbed down version, the steps to teleport all players in a p2p server with NGO? i tried a serverrpc that loops through all players and calls a clientrpc in them but i cant seem to get it right...
is your movement/position server or client authoritive?
Dumbed down: is your client even allowed to move on its own?
if not do everything in the server rpc not the client rpc
Are there any developers using Vivox?
How would you do it?
Hello 🙂
All players join a Normal 3D channel
All players join a 2D channel
Then the players join the map, I switch transmissionMode to single on the 3D channel
Players can talk in a walky talky,
I then switch transmissionMode between single on 3D Normal and All so that it speaks on 3D Normal and 2D Talky
Players can enter a dead state while remaining on the map
When they are dead they can talk to each other and hear the living but no longer communicate with the living.
They can hear the living regardless of the position (so 2D channel) but if the living players are on single 3D Normal it doesn't work
So all players would have to be on a common channel at the same time.
Let living players have the volume of this channel set to 0 (inactive)
And for the dead players to set the volume of this channel to 1 (active)
So switching Transmission mode to single or all does not work, since if the players are on single they will not transmit on the common channel
In my opinion it would be necessary to be able to play with the volume of a channel or the volume of a player in a channel but the mute unmute systems are general to all channels
Is this possible?
Ooo thank you, currently looking into this. Are there any tutorials besides documentation that you would recommend out there?
Sorry it's not really a recommendation it's more the logic that I suppose but I don't know how to do it
add players in a 3d and 2d channel and communicate either in 3d or 2d in the talky (without effects) it's good
But I don't understand the logic so that once dead I can hear all the players but only communicate with those who are dead.
I would assume just switching channels should work. But I haven't used Vivox for much besides just testing it out
I try to schematize
Player 1
2d talky channel
positional channel
Player 2
2d talky channel
positional channel
Player 3
2d talky channel
positional channel
in game
Player 3 speak talky (transmit audio to all)
(Player 3 speak on talky 2d and positional 3d)
Player 1 & 2 hear player 3 non positionnal
Next
Player 2 is dead
player 2 speak dead 2d channel
how player 2 can hear player 1 & 3 2d channel if player 1 & 3 speak since 3d channel?
Player 2 can only hear player 1 & 3 if player 1 & 3 speak in talky?
but I would like to know if it is possible for player 2 to hear player 1 and 3 even if they do not speak on the talky
Maybe with audio tap but I haven't quite figured out how to use them yet.
I am searching for any people that might interested in making an MMORPG with a custom multiplayer solution DM me if you want.
[ClientRpc]
void DestroyClientRpc()
{
transform.SetParent(myParent);
Destroy(gameObject.GetComponent<NetworkRigidbody>());
Destroy(gameObject.GetComponent<NetworkTransform>());
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
gameObject.SetActive(false);
}
I have this simple script
I have to destroy NetworkTransform
And on host it works perfectly fine but on the client it doesnt because it says thath NetworkRigidibody require NetworkTransform
And that means that there is a delay for destroying component and I wonder does the do while is a good fix?
I mean should I use do while in rpc
Hey Together i'm using Netcode für GameObjects and can't Find anything helpful about the following Error. I'm getting it after using the Update() to move something the whole time. Can someone Tell me more?
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 120, but that trigger was not received within within 1 second(s).
How viable would a networking system like this work?
Assuming the "inputs" are just strings of keyboard stuff
What I want is basically, the host client runs the vehicles, npcs, etc, while it shares inputs of itself to other clients, and those in between
Kinda peer-to-peer
Well, I think I just reinvented the wheel-
Well, more like "rediscovered" the wheel
so you want the input of a client to be processed by the host instead of the client?
that would be terrible, due to latency except it is a lan party game where you have pings of 1ms
Or havs I misunderstood what you want to achieve
Update happens before network objects have been spawned. You'll need to wait until after OnNetworkSpawn() before sending messages
This is server authoritative. Perfectly viable and absolutely necessary for competitive games. But you will need to deal with the input lag somehow. Usually it's done by some kind of client prediction system.
I am getting this error:
Unity.Netcode.NotListeningException: NetworkManager is not listening, start a server or host before spawning objects
From this code:
{
if(!changes.LobbyDeleted)
changes.ApplyToLobby(newLobby);
if( newLobby.Players.Count > 1 )
{
StartRoomClientRPC();
foreach (Player j in newLobby.Players)
{
GameObject listInfo = Instantiate(playerListInfo, playerList.transform);
listInfo.GetComponentInChildren<TMP_Text>().text = j.Data["PlayerName"].Value;
listInfo.GetComponent<NetworkObject>().Spawn();
};
}
}```
Any idea whats going on? This code runs after I have already joined a lobby
@stiff charm
Thank you for your answer!
I think it's due to a circling ball that I added around the player. This message only appears on the host. I suspect it's trying to damage the opponent before they spawn. Since you instantiate first and then spawn.
I'm currently trying to work around this with the 2nd if, but it's not working. Do you have any idea what could be used? I'm very sure it's because of the damaging part, without the code, the error message doesn't come (which surprises me, since the other weapon in my Game works similarly)
I think it has something to do with this if not blocking it: if (enemy == null || !enemy.NetworkObject.IsSpawned) return;
private void OnTriggerEnter2D(Collider2D collision)
{
if (!IsOwner) return;
if (collision.TryGetComponent(out Enemy enemy))
{
if (enemy == null || !enemy.NetworkObject.IsSpawned) return;
PlayerStats playerStats = Player.Instance.GetComponent<PlayerStats>();
float damage = calculateDamage();
enemy.TakeDamageServerRpc(Convert.ToInt32(damage));
}
}
You'll need to startHost() before the 2nd player joins the lobby. You'll also need to make sure that this code is only running on the host
The timing of spawns get weird for the host. I'm assuming this code is on the Player. You might need to disable the triggers until after everything has spawned
Exactly, the code is in the "WeaponManager", which is a sub-object of the player. The problem is that "waves" spawn all the time. In other words, I can't actually disable it because there are enemies running around all the time.
Hey guys, what SSL format does unity support. if its PFX then how the heck do iconvert my .pem and .key into a valid format?
anyone know what this eror is?
TlsException: Failed to read data to TLS context - error code: UNITYTLS_INVALID_ARGUMENT
got it on my server side when trying to call ReadAsync from an sslstream
I'm still having the following Error and no idea how to fix this, tryd for hours now. It only happens when i try to despawn enemys after they get 0 Healthpoints.
Error: [Netcode] Deferred messages were received for a trigger of type OnSpawn with key 120, but that trigger was not received within within 1 second(s).
No Error if i don't do this: this.NetworkObject.Despawn(true);
Sounds like you may be destroying the object before Despawn gets called
But i don't destroy it, i only despawn it
sorry i was unavailable the rest of yesterday but yes the movement is client authorative
update: ok ell the flickering is now gone, i found that the charactercontroller component overrode the positional changes back to their origin, now the problem just persists that only one player is being teleported (the host)
update 2: i fixed it, finally
In Unity Netcode, I am able to set the NetworkVariable HostID when I am the host.
However, it seems that I cannot set the NetworkVariable ClientID when I am the client.
Essentially, I want to set a string (ClientID) for the host from the client side.
Can someone provide guidance or help me with this?
by default network vars can only be written to by the server
call a serverrpc, with the clientid as an arg and that it that way
You can set the write permissions of the net var to Owner
Hi, I am running into an issue where positions appear different on server / clients. Two different clients on left, and server on the right. What could cause positions to look different ?
I haven't implemented Server Reconciliation yet, could that possibly be why? Perhaps they aren't in line with the server?
MIRROR 86.13.4 IS LIVE ON THE ASSET STORE
Download: https://assetstore.unity.com/packages/tools/network/mirror-129321
ChangeLog: https://mirror-networking.gitbook.io/docs/general/changelog
What would be the proper way to synch a VR avatar using Netcode for gameObject and keeping it server authoritative?
Keep the avatar separate from the XR rig. The local rig will need to send it's positions to the server. The player avatar needs to follow the rig positions. You'll need to create some kind of client prediction system in order to deal with the latency.
Well having the local rig sending it's positions to the server means it's no longer authoritative. I already made a test with a Client Network Transform and it works.
The server has to get the positions somehow
well yes, the more I think about it the more it seems that a VR multiplayer game can not be server authorative
Even with server authority the clients still have to send it's inputs. It's just that for VR those inputs are positions
What are the major differences between photon and fishnet? I'm thinking about getting into multiplayer and I see a lot of talk about these two, what would you recomend? (For now Im just planning a simple create/join lobby game, but it would be cool if the tool would let me scale the project in the future, like dedicated servers or smt)
hey, so i have a problem that i think is easy to solve but i cant seem to find a solution for it. i have scrolled for about 3 hours now and still cant find it. the problem that i am having is that i have 2 players join a room and loading the scene. everything goes perfect there. now i have 2 players in the same scene and the master client can see the 2nd player, however the 2nd player cant see the master player because the master client has been instantiated before he joined. maby somebody here can help me? i already asked in the photon server but dont get a response there so i thought maby somebody here knows something about photon.
PUN should instantiate all networked objects to every client. Make sure you are using PUN to instantiate objects.
How do I get to this page???
Question about Network Manager and Unity Transport - when started as a host, what ip:port does the program listen to for connection requests from clients?
When Allow Remote Connections is enabled
I'm trying to implement a Network Discovery system where the host device gets all clients awaiting a connection, then on user input orders one of the clients to connect to it. My problem is, I can't figure out how to make the client connect to a specific host.
I found this, but I don't really understand the difference between the remote adress and listenAddress, does setting the listenAddress matter when connecting remote?
Figured it out, nvm. Turns out i just needed to use the ip of the host with the port of the Unity Transport
What is the best solution right now for multiplayer where one player is host and up to 8 players join? And if using DOTS I assume the only choice is Netcode for entities?
Any of the current solutions will work fine for that. Even using Dots, you are not stuck using N4E. But there is no reason not to. Built in client prediction system is no joke.
Does anybody have a good tutorial to start with netcode and relay from zero. I can only find some where they use a template and integrate stuff in there but I want to umderstand it from zero that i can implement it in my game
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo/
https://docs.unity.com/ugs/en-us/manual/relay/manual/relay-and-ngo
Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).
in unity lobbies, how do i check if i got kicked?
i kick them with LobbyService.Instance.RemovePlayerAsync(joinedLobby.Id, playerToKick.Id);
but how do i for example run a function on them to leave the lobby screen
i have some question, am i able to make LAN lobbies and LAN multiplayer with unity Netcode and Unity Services
You can use Lobby Events
https://docs.unity.com/ugs/en-us/manual/lobby/manual/lobby-events#KickedFromLobby
You can use them on a Lan but Unity Services require Internet access. You can use Network Discovery if you need something offline
https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
thank you
i spend almost 2 hours on figuring this out...
i made jump button to canvas, but how to make it work? i added jump method in player controller script, but.. how to make jump button trigger this method? i make player controller get joystick whit FindAnyObjectByType and it works, but, what to do with button? i dont think that storing cavas inside of player is good idea...
Ah thx
Btw, i use unity lobbies, can i on top of that add steam? So i can join someone through steam?
You can use steamworks. You can probably send the lobby join code through steam. I don't use it so I can't really help
No the canvas should not be networked. But you can have the button call a function that calls a serverRPC on the player controller
wait.. THANK YOU SO MUCH!! i forgot about it...
Sorry if this has been answered before, but I can't seem to find it here or a definitive answer through googling it..
I have a server/client game. However, if the person who is the server (creator of the session), leaves the game, everyone's networking just stops. Is it possible to pass the server-ship to the next available client connected, or do I HAVE to host a server version on unity cloud if I want to avoid this.
uhh, can u say how... please...
When the relay host leaves the network connection is dropped. No real way around that. You can use Lobbies to hold the remaining players together then create a new relay with the new lobby host. It will be a new game so you will have to deal with saving game state somehow
Oh I see. So would you suggest it be easier to just use Cloud Multiplayer to host server on there?
It's more expensive that way but will prevent the game from dropping
sorry what do you mean expensive? As in I have to pay for the services?
Server Hosting is not free.
no, but there is a monthly free amount they allow, no? all cloud services do?
Yes, simply if your game is going to be popular then you have to pay
gotcha. got me worried there for a second 💀 😭
did anyone here make their own host migration for unity networking/relay?
Not for dedicated servers. They only give you a one time $800 credit
Hello, I'm completely lost. How should the server handle multiple game modes? Unity multiplay and matchmaker
The matchmaking payload can contain map and game mode data. So the server can load up what it needs when the game starts
one more day... same problem...
i cant find any tutorial that teaches how to make mobile multiplayer game...
i made one, and it work good on pc, and i added jump button to canvas, all players are prefab, and its bad idea to put canvas into prefab cuz of multiple canvas and it will look weird, and, how to make jump button trigger function in player script?
Is it this? ```var players = new List<Player>
{
new Player("Player1", new Dictionary<string, object>())
};
// Set options for matchmaking
var options = new CreateTicketOptions(
"Default", // The name of the queue defined in the previous step,
new Dictionary<string, object>());
// Create ticket
var ticketResponse = await MatchmakerService.Instance.CreateTicketAsync(players, options);
// Print the created ticket id
Debug.Log(ticketResponse.Id);```
Those options
you can just disable the canvad by default and only enable it for the local client
or just have the ui spereate from the player
okay ill try, thx
why im getting this error?
im getting it when i drag joystick on host
i fixed
no i didnt, it happen when there is more than 1 player
I heard that unity netcode for game objects (so unity multiplayer) was small scale, so that you couldt make a battle royale with 100 players, only a real game with 1-4 players, is that still the case?
I'd expect most multiplayer systems to struggle with 100-player games
I'd suggest looking for benchmarks.
Yes. For large scale games you would need to use Netcode for Entities
Guys do you know how can i start a client with an URI instead of an ip and a port on Netcode for GameObjects 1.6.0?
on Mirror i would do this
Because i need to connect to a proxy server for securing connection, otherwise it will throw this error: The page at 'https://test.....io/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://34.....90:9000/'. This request has been blocked; this endpoint must be available over WSS.
But on Netcode for gameobjects SetConnectionData only accept ip address and port or a NetworkEndPoint
I'm on WebGL
Or do you guys know an alternative to use a server proxy?
Heyo, I have a multiplayer game using Relay and Lobby services, I only have player hosted servers. The game works but after a little while the host timeouts and I get this error: [Lobby]: NetworkError, (16998). Message: Request timeout does anyone know how to troubleshoot this?
couldn't you just dns resolve that url to an ip?
i was trying to do it but it gaves me this error:
how can i do it?
that is because it expects http(s) not ws(s) like the error says. What I would try, since for this response it does not have to communicate with the protocol, is just changing that to https or even leaving the protocol out entirely
I have to admit I never tried to do this in c# tho
ok i'll try
@nocturne vapor this is my transport settings, i tries to use http(s) o remove it entirely but it gaves me the same error
idk then honestly, currently I'm working mostly on other stuff not networking related
I also never worked with websockets, these were just ideas that immediatly came to my mind about this
well i think i will continue to work with mirror then and see where are the differences
@nocturne vapor Seems like Mirror is doing stuff with JS and the Uri it self
And this is the jslib function
// fix for unity 2021 because unity bug in .jslib
if (typeof Runtime === "undefined") {
// if unity doesn't create Runtime, then make it here
// dont ask why this works, just be happy that it does
Runtime = {
dynCall: dynCall
}
}
const address = UTF8ToString(addressPtr);
console.log("Connecting to " + address);
// Create webSocket connection.
webSocket = new WebSocket(address);
webSocket.binaryType = 'arraybuffer';
const index = SimpleWeb.AddNextSocket(webSocket);
// Connection opened
webSocket.addEventListener('open', function (event) {
console.log("Connected to " + address);
Runtime.dynCall('vi', openCallbackPtr, [index]);
});
webSocket.addEventListener('close', function (event) {
console.log("Disconnected from " + address);
Runtime.dynCall('vi', closeCallBackPtr, [index]);
});
// Listen for messages
webSocket.addEventListener('message', function (event) {
if (event.data instanceof ArrayBuffer) {
// TODO dont alloc each time
var array = new Uint8Array(event.data);
var arrayLength = array.length;
var bufferPtr = _malloc(arrayLength);
var dataBuffer = new Uint8Array(HEAPU8.buffer, bufferPtr, arrayLength);
dataBuffer.set(array);
Runtime.dynCall('viii', messageCallbackPtr, [index, bufferPtr, arrayLength]);
_free(bufferPtr);
}
else {
console.error("message type not supported")
}
});
webSocket.addEventListener('error', function (event) {
console.error('Socket Error', event);
Runtime.dynCall('vi', errorCallbackPtr, [index]);
});
return index;
}```
malloc, heap, Ptr?
it is wild to see that stuff used in a high level language, didn't even know js allowed memory allocation with malloc xD
Is there a way to have a Host have two active scenes but only see one at a time? The clients will also be able to jump back and forth between these scenes.
A simple way to put it would be, have two scenes, outside and inside.
Using Netcode For GameObjects
How can I spawn a player item as a prefab (that needs to be seen by other players) on the player under a gameobject inside the player that doesn't have a network object component.
Currently, I'm only able to set the parent of the players item to the player itself, with other objects needing a network object component to be a parent, yet I can't have nested network objects or I get errors.
Fix for this ^ https://forum.unity.com/threads/player-hierarchical-networkobjects.1207012/ its a limitation in unity, instantiated objects have to be parented to the root of the player so u can do it client side as a work around
is there anyone down to call? ye ik its weird but i really gotta figure out how camera works when spawning client.
im not sure. maybe the cinemachine gets overwritten by anotehr spawn or something
just have it disabled by default and only activated if IsLocalPlayer
or just have a camera for the scene
Is there an equivalent to OnNetworkObjectParentChanged, for children? ie: NGO's (grand+?)child had NGO added/removed beneath it.
I can't seem to find anything - am I missing something? Or would my alternative just be to manually bubble-up from the NGO that was reparented? (If so, any way to get the previous-parent? Or also have to manually cache that?)
private void PlayerTransform_ClientRpc(Vector3 pos)
{
try
{
Debug.Log("Im trying...");
GameObject.FindGameObjectWithTag("NetworkPlayer").transform.position = pos;
}
catch (System.Exception e)
{
Debug.Log(e);
}
}```
Why doesn't this work?
It doesnt give of any errors. It just doesnt move a player
Im also getting the "Im trying..." in console
with unity lobbies, in the lobby every player has a faction and an icon for it, how would i update the icon for all players?
https://www.youtube.com/watch?v=-KDlEBfCBiU
At the end of this video you have him go over everything he offers in his template, that you can download. That's what I used as a base. I opened it in a second project and more or less copied and tried to understand what he was writing there. That includes changing profile pictures. What basically is what you want. You can take that as a guideline, if you want.
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
✅ Learn more about Lobby and UGS https://on.unity.com/3XdKEd7
🌍 Get the Project Files https://unitycodemonkey.com/video.php?v=-KDlEBfCBiU
📝 Lobby Docs https://on.unity.com/3OtC0Du
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to mak...
How does Scene Managment with the Network Manager work, I have everything set up in the Main Menu scene and now i want to switch scenes and then spawn the player prefab in there, but the Network manager keeps spawning it in the current scene. How can I spawn it in the Game Scene?
Are you using Additive Scene loading?
no idea what that is
ah ok I see yeah that could solve the problem, but then the prefab wouldnt be in the right scene
The automatic player prefab will spawn immediately when the client connects just before the scene changes. easiest thing would be to disable the player renderer until the game is actually ready to start
But again then the prefab wouldnt be in the right scene
Of course if it were all in one scene that would work flawlessly but its not
player prefabs will get automatically moved to the new scene. As long as you are using NetworkManager.SceneManager.LoadScene()
Oh that makes it easy
thank you
Hey, anyone know what could be the reason of the jittering?
I'm Lerping the position by the elapsed delta since next position
var t = elapsedPosition / movementTick;
playerTwo.Position = lastPosition.Lerp(getNextPosition(), (float)t);
tick is 60 (60 times per second) and movementTick is 60/1000 which is 0.06
When I'm not moving it's clean, when I move along with player, player jittering.
It could be your camera... Do you transform it in LateUpdate()?
Yes camera is in Late
Mirror works fine with WebGL and Reverse Proxy - ping me in the Mirror Discord if you need help.
Thank you for the response, i have already switched to mirror and everything works with reverse proxy
I was only trying the netcode for gameobjects solutions just to play around
The double entendre there.... 😄
They are very similar indeed
Anyone can help with my problem higher can offer money for help dm me
I've tried using the photon transform view classic but it doesn't fix it
and yes, i have ticked rotation box for all of them
@mental pond Did you tried to make a build and see if the problem persists?
@mental pond Did you tried using slerp instead of lerp?
Yes
You think it will help?
netcode or photon?
my own networking
hey, i set it all up and its working great (GITHUB)
how does it actually work with others? if for instance im doing a fps controller and adding a gameobject etc., and my friend is adding a game object with the ability to only jump
how would that work, would it even?
or u just gotta communicate EVERYTHING
and how do we share small updates with each other (for example im adding a door that works, he simultaniously adds sth else)
and do i have to constantly download small changes the other person has made and add them back into the fuqin folder?
this is horrible
transport ..
Question on Netcode for Gameobjects:
Situation: Say that the server locally updates the state of the game on each network tick, then sends out rpc calls to all clients with the changes so that they can update their own local state. This entire state update/rpc invocation happens in the same frame (on the server).
Question: Will all these rpc calls be bundled into a message at the end of the frame and then send out? Or will it be sending every rpc separately? If separate, is there any issue here with performance, where I should instead combine into a few big rpcs? If big, don't I have to worry about payload size?
I've found a github post saying
NGO sends all pending out bound messages for any given frame as a single batched message.
But i'm not sure whether this also includes rpc calls or not.
source: https://github.com/Unity-Technologies/com.unity.multiplayer.docs/issues/1111
is unity lobby enough for a 2d turn game?
multiplayer? or i need something more complex
NGO has ticks. All messages are queued for the next tick and then bundled and sent together. These ticks are independent of rendered ‚frames‘ but could be called network or message ‚frames‘. RPCs are an abstraction on top of the lowlevel messaging API. Whatever is true for the low level messaging is also true for any abstraction on top.
What am I doing wrong that my RPC will not trigger on any clients?
{
if(!changes.LobbyDeleted)
{
changes.ApplyToLobby(newLobby);
}
if( newLobby.Players.Count > 1 && IsHost)
{
OpenLobbyClientRpc();
}
}
[ClientRpc]
private void OpenLobbyClientRpc()
{
foreach (Player j in newLobby.Players)
{
GameObject listInfo = Instantiate(playerListInfo, playerList.transform);
listInfo.GetComponentInChildren<TMP_Text>().text = j.Data["PlayerName"].Value;
//listInfo.GetComponent<NetworkObject>().Spawn();
};
}```
If anyone can please assist. I would like to know what the proper way to do an RPC is. I followed the Unity documentation and it has yet to work once. I was using Photon before this and it was quite easy in comparison.
Please?
That is the correct way to call a clientRPC. You just have to make the server is listening for the lobby changes.
But also you don't really need a clientRPC there. Each client can also listen for the changes and instantiate their lobby ui
It’s definitely listening. The Debug logs all fire.
The RPC simply won’t work and I’m at a loss for why.
I can’t continue work unless I understand why. Is there a stipulation besides both players being in the same lobby that I am missing
Sorry I’m so lost. I’ve been trying to get the RPC to work for weeks now. It was so easy with photon
You are correct each client can listen for the changes except unity made a weird change in lobby 1.1.2 where the client that just joined cannot see their own changes.
I contacted them and they said they will revert it in 1.2 but it’s not out yet
The clientRPC can only be called by the server. And it has to be on an active and spawned network object.
If lobby events aren't working then I would go back polling the lobby.
Here is thier response
The client should already know when it joins the lobby itself
When you say called by the server, does that mean the host cant do it if im doing peer to peer?
The host is the server
Does a lobby automatically have a host when its created? I cant fathom why this code is not being run by the host
It does. But you need to network manager StartHost() and client has to be connected with StartClient().
That not usually the case when working with lobbies
omg.....
So i have to actually start host?
Wow...
Yep thats how RPCs know where so send messages
wtf
I didnt see that in any of the documentation
Do you have an example code i can see?
Lobbies are a completely separate service from NGO
God... weeks of time Ive been trying to figure this out
Wait... what?!??
Unity Lobbies can be used with any network framework if you want
Do you need Lobby samples or RPC samples?
Im so sorry to ask this. I'm so confused so i am just going to ask in the absolute most basic, child-like means.
I thought once two players joined a lobby, they were now in a 'game' together. If thats not the case, can you explain in baby terms (or point me where) how i get the two players in the same place to start sending RPC's
No prob. But that is not the case at all. Lobby is not really meant to be sending messages
You will still need to connect using Unity Transport if you are using Netcode for GameObjects. You can use Unity Relay to connect peer to peer style or you can connect directly to the hosts IP address
With Relay you would save the relay join code into the Lobby Data then the clients can use that to join the game
I see. So the lobby stores the data but relay is what connects them.
Thank you VERY VERY much. This was definitely the part ive been missing. I appreciate it so much.
Have a wonderful rest of your day/holiday
Is there a sample of this do you know?
There is Game Lobby Sample in the docs. But honestly its way overengineered.
https://docs.unity.com/ugs/en-us/manual/lobby/manual/game-lobby-sample
I'll dig up the script I use in a minute
This is some older code but it should still get the idea across
https://github.com/evilotaku/MythOSv2/blob/main/Assets/_Scripts/Network/NetworkConnectionManager.cs
Thank you so much for taking the time to figure out where I was stuck. And thank you for finding this code. I will look at it now
Thank you!
Lobby is not meant to be used like that. If you don't need a real time connection to the other players then you can use cloud code
https://github.com/Unity-Technologies/com.unity.services.samples.multiplayer-chess-cloud-code/tree/main
does some1 have a idea how i can make a seprate inventory for every player i am using netcode
How do I change a client's position in a server RPC on another object? I'm using NGO and the player has a ClientNetworkTransform attached to it
Can u explain a little more
That depends on how you are doing items. each player can have a List of Item IDs or it can be a struct of Items and quantities if things stack
I have a server RPC on a "spaceship" object where I want to change the player's position based off a playerSpawnPos variable. Preferably I would like to change the player's local position but for now I'm trying to change transform.position instead
[ServerRpc(RequireOwnership = false)] public void AddPlayerServerRpc(NetworkObjectReference playerReference) { var playerObject = (GameObject)playerReference; var player = playerObject.transform; player.parent = playerGroup; player.GetComponent<ClientNetworkTransform>().position = playerSpawnPos; }
ty
Only the owner can change the client network transform position. So you would need to use a c!ientRpc from the server
but its using using Unity.Services.Lobby.Model, isn't the same thing?
almost
the thing is that only the host can modify Lobby data. Players can only modify their own Lobby Player Data.
Not to mention there are bandwidth limits on the Lobby service. 10GB/mo in the free tier
so the chess one its free?
does it have like a video tutorial?
https://www.youtube.com/watch?v=-KDlEBfCBiU&list=PLzDRvYVwl53sSmEcIgZyDzrc0Smpq_9fN&index=3&ab_channel=CodeMonkey i think this is what i was looking for
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
✅ Learn more about Lobby and UGS https://on.unity.com/3XdKEd7
🌍 Get the Project Files https://unitycodemonkey.com/video.php?v=-KDlEBfCBiU
📝 Lobby Docs https://on.unity.com/3OtC0Du
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to mak...
lobby and ugs?
Almost all of the game services have a free tier. Cloud Code and Cloud Save have something like 1 Mil read/writes per month
https://unity.com/solutions/gaming-services/pricing
do you know any tutorial for them?
[ServerRpc]
private void DestroyServerRpc(GameObject gameobject, float time)
{
Destroy(gameobject, time);
}``` i get this error
Don't know how to serialize UnityEngine.GameObject. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. If this type is external and you are sure its memory layout makes it serializable by memcpy, you can replace UnityEngine.GameObject with ForceNetworkSerializeByMemcpy`1<UnityEngine.GameObject>, or you can create extension methods for FastBufferReader.ReadValueSafe(this FastBufferReader, out UnityEngine.GameObject) and FastBufferWriter.WriteValueSafe(this FastBufferWriter, in UnityEngine.GameObject) to define serialization for this type.
They are pretty straightforward. The docs page is really good. But I'm pretty sure code monkey has done vids on them too
https://docs.unity.com/ugs/en-us/manual/cloud-code/manual
You can not serialize a gameobject. If it's a spawned network object then you can use NetworkObjectReference
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
thanks
why cant i get the animator and rb and why does the rb on the client get set to kinematic
public override void OnNetworkSpawn()
{
if (!IsOwner) return;
SpawnServerRpc();
rb = GetComponent<Rigidbody2D>();
animator = transform.GetChild(0).GetComponent<Animator>();
weapon = 0;
}
[ServerRpc]
private void SpawnServerRpc()
{
var ch = Instantiate(character.Prf, transform);
ch.GetComponent<NetworkObject>().Spawn(true);
ch.transform.parent = transform;
}```
TY
Network Rigidbody will automatically set isKinematic for network objects. The clients will get set to kinematic. If you are using Client Network Transform then the non owners will get set to kinematic
You should still be able to get the Animator and Rigidbody though. no idea whats up with that
i am making the inv using ids and array i did make the player inv working with array but not ui because the player is a prefab
Hello, I have a code block as follows.
Everything is working correctly but "ConnectionApprovalCallback" is never called, what could be the reason?
NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
NetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
NetworkManager.OnServerStarted += OnServerStarted;
NetworkManager.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.OnTransportFailure += OnTransportFailure;
NetworkManager.OnServerStopped += OnServerStopped;
Just a shot in the dark, but check if it's "explicitly enabled"? There's a warning that gets logged, but could be missed if you have a lot of messages. - ~"A ConnectionApproval callback is defined but ConnectionApproval is disabled. In order to use ConnectionApproval it has to be explicitly enabled"
[Still relatively new to netcode, myself; hence, shot in the dark. Heh.]
[Edit: Resolved]
Having a curious issue, myself. I'm not sure if I'm doing something wrong~~, or if I found a "feature" or a "bug". (?)~~
Create a prefab NGO with NetworkTransform using "In Local Space".
A.1) Start a Host.
A.2) Spawn prefab "Root", "Child" and "Grandchild"
A.3) Parent accordingly.
A.4) Translate each so they're in any unique position.
B.1) Start a Client, connected to the Host.
Note: It is important that the Host dynamically spawns the NGO's during runtime (ie: not scene objects), and spawned before the client connects.
Expect: Client spawns 3 objects in the same hierarchy and position as the host.
Actual: Client spawns 3 objects in the same hierarchy, in a different position.
It looks to me as though the objects spawn on the client unparented using the host's 'local position' as the clients 'world position', then reparents the NGO using WorldPositionStays.
ie: clientNGO.position = hostNGO.localPosition~~ -- Which is blatantly incorrect.~~
I see in the docs that it does say NGO uses WorldPositionStays~~, but in this scenario that seems... wrong?~~
Interestingly - as soon as the host moves an NGO, it suddenly updates on the client to the correct position. So, once spawned, it translates correctly... it's just the initial spawn, before anything has moved, seems incorrect.
Edit: Solution: I missed replacing transform.SetParent(...) with ngo.TrySetParent(..., false)
Reparenting in editor or using transform.SetParent(), will equate to:
ngo.TrySetParent(..., true)
I needed to ensure every SetParent() was replaced with ngo.TrySetParent(..., false) for my situation.
My friend, the approval check in the networkManager is not ticked. Thank you
I don't know if I fully understand your problem, but have you tried using the setParent method first and then spawning it?
I was inadvertantly/incorrectly using standard transform.SetParent() in some places, where I needed to be using ngo.TrySetParent().
That's effectively all the problem was, just didn't see it at the time. Thought something was wrong... but was just me > ; P
Glad you resolved your issue, as well.
If I want to test my game with some somewhere else where do I put my public IP address? In Address or in Override Bind IP
If you are trying to do a direct IP connection then the host's public IP address would go into Address but the host would also have to set up port forwarding from their router. A much much easier route would be to use the Unity Relay service
Ya I will use steam later, but for now it would be easier for me to use Unity Transport so that I can still test locally without uploading to steam every time I change something.
So do I check or uncheck Allow Remote Connection?
And Override Bind IP can stay empty?
I needs to stay checked if you want to allow remote connections.
The Bind IP field can remain empty
this unity Cli its giving me a hard time
any idea why i can't deploy the chess sample ?
i added all the roles, in the service
You have to actually log in through the CLI as well. I just use the deployment package from the package manager
i can't open the whole project
and i can't see the files
and i don't know to use it either
I mad an Multiplayer game and on my local network it works fine but i cant get it to work online i made a build with my public ip and send it to my friend set portforwarding for udp and tcp on my router and my firewall but he cant connect
(i was following a tutorial from codemonkey) so i am using unity lobbies and there is a limit for using it for free i think, but i pull the data every second, because i want to update the list of players the whole time so if someone does leave/join it immediately updates the list.
is there a better way to do it than this every second? (like a function that runs when something happens?)
heartbeatTimer2 -= Time.deltaTime;
if(heartbeatTimer2 < 0f)
{
previousPlayerCount = joinedLobby.Players.Count;
Lobby lobby = await LobbyService.Instance.GetLobbyAsync(joinedLobby.Id);
joinedLobby = lobby;
previousLobbyName = joinedLobby.Name;
float heartbeatTimerMax = 1;
heartbeatTimer2 = heartbeatTimerMax;
}
i cant spawn object on client side (this is a prop hunt game and another player is trying to turn into an object)
how do i tackle this? i dont even exactly know which part of my code is causing the problem
use ServerRpc https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/serverrpc/
Introduction
but don't i have to start a relay/networking for gameobjects? what i meant was before that in the lobby
You probably want to use Lobby Events instead of polling
https://docs.unity.com/ugs/en-us/manual/lobby/manual/lobby-events
the LAN across device doesnt work. I also tried the ips in ipconfig and they dont work either
i mean which exactly do i even enter?
The host can stay as 0.0.0.0 but the client needs to be the public IP of the host
oh i see. in essence the host is connecting to itself and the client it connecting to host
Kind of. the host is listening and the clients are connecting
normally its IPv4
hm doesn't look like there is something for the playercount being changed... and if i do playerJoined.changed it doesn't really work
Subscribing to LobbyEventCallbacks.LobbyChanged will give you ILobbyChanges. ILobbyChanges.PlayerJoined/PlayerLeft will give you a list of players that joined or left
Is this truly the shortest way to update a pre-existing player data?? Why is it so long?
{
UpdatePlayerOptions options = new UpdatePlayerOptions();
options.Data = new Dictionary<string, PlayerDataObject>()
{
{
"existing data key", new PlayerDataObject(
visibility: PlayerDataObject.VisibilityOptions.Private,
value: "updated data value")
}
};
string playerId = AuthenticationService.Instance.PlayerId;
var lobby = await LobbyService.Instance.UpdatePlayerAsync("lobbyId", playerId, options);
}
catch (LobbyServiceException e)
{
Debug.Log(e);
}```
Hi, I would like to know how to open new scenes using the networkscene manager. I know, sounds simple. But I just didnt get it to work and it took me way too long for what it acutallly is.
I have this scene. One Host button and one join button. When I press the host button a new Lobby (using the Lobby service) gets generated and when somebody else presses the "join" button they join the lobby.
When one of the players presses the Startbutton I want both to get into the new scene.
How do I manage to do that?
NetworkManager.Singleton.SceneManager.LoadScene(scene, LoadSceneMode.Single);
Evertime I execute my script this Error comes up:
NullReferenceException: Object reference not set to an instance of an object
StartGame.JoinScene () (at Assets/MyStuff/Scripts/Networking/StartGame.cs:10)
UnityEngine.Events.InvokableCall.Invoke () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <17484a9af6b944dea5cd9be4dbb0da2c>:0)
UnityEngine.UI.Button.Press () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)
This is my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour
{
public void JoinScene()
{
NetworkManager.Singleton.SceneManager.LoadScene("Playground", LoadSceneMode.Single);
}
}
But I cant get the heck out of what exactly is missing here!
NullReferenceException: Object reference not set to an instance of an object
Something in your scene is null. Either the actual NetworkManager doesnt exist in the scene you are calling it from or the button is using "AddListener" but the button reference is null.
StartGame.JoinScene () (at Assets/MyStuff/Scripts/Networking/StartGame.cs:10)
Its the NetworkManager. It says line 10 and the only thing in the method that can be null is the NetworkManager
can some dm me bc i need help with a inventory i am stuck on it for 2 weeks it works in singleplayer but idk how to convert it to multiplayer
Oh I may have realised something.
I hosted a lobby and all
public async void CreateLobby()
{
try
{
string lobbyName = "MyLobby";
int maxPlayers = 2;
Lobby lobby = await LobbyService.Instance.CreateLobbyAsync(lobbyName, maxPlayers);
hostLobby = lobby;
Debug.Log("Created Lobby! "+ lobby.Name + "Available Slots: " + lobby.AvailableSlots + "LobbyCode"+lobby.LobbyCode);
}catch (LobbyServiceException LobbyError)
{
Debug.LogError(LobbyError);
}
}
But I think the network manager never really hosted the thing, you know?
NetworkManager.Singleton.StartHost();
Is this right? I have never worked with netcode before only with Pun2.
How exactly do I implement that, with my Lobby code? Im so confused
I had this same issue yesterday. Id been struggling with it for weeks. If you scroll up in this same chat someone explains that you cant use most of this stuff until you start host and start client.
They give code examples too. Its so different from Photon and in my opinion too convoluted
Hello everyone!
Talking about the challenges for MMORPG games, the core is:
- Network to handle with connections;
- Database to handle with data;
- Security to avoid hacks.
Right?
Just for test purposes and to understand better those environment I decided to use for network, Phonton 2 PUN, database Mongodb, and easy the structure/code, Fishnet.
I have some doubts about the update flow works. About to update data, what do you think? Update every specific moment (like each 1 ... 5 seconds? Only with events? Both?) How to avoid hack for those updates?
Can I ask why you are staying with Netcode then? I would like to know, because im considering going back to Photon or trying mirror.
I tend to like built in solutions since they have more documentation. Photon was very easy to work with but got quite annoying when I hit a snag that no one would help me with
Im just a little disappointed at how incredibly fractured Unity's solution is. Once you get it, i guess its easier but starting out was VERY very painful and even the documentation doesnt make it clear what parts you need and why
I feel this. This is why I switched from Photon to netcode. Also having every service (Voice, Multiplayer, Accounts, Transactions, whatever) in this nice dashboard, it makes sense. But after over 22 Hours and no progress a part of me really wants to go back.
But thanks for the help! Maybe I'll stick with the Unity Services
I hope it works out for you. I've been stuck multiple times. Discord has been my only saving grace lol
I appreciate! Have a good one
Yea. scroll up a bit for this exact issue. Unity Lobby is fundamentally separate from NGO. You'll need to call StartHost() before you can use NetworkManager to change scene
[ServerRpc]
private void AttackDamageServerRpc(float size, float range, float weponDamage, float weponKnockback, Vector2 direction, Vector2 knockbackDirection)
{
knockbackDirection = new Vector2(knockbackDirection.x + (0.5f * transform.right.x), knockbackDirection.y + 0.5f);
// so raycast doesnt hit player
gameObject.GetComponent<Collider2D>().enabled = false;
RaycastHit2D hit = Physics2D.CircleCast(transform.position, size, direction, range, hitmask);
gameObject.GetComponent<Collider2D>().enabled = true;
if (hit && hit.collider.gameObject != gameObject)
{
GameObject enemy = hit.collider.gameObject;
if (enemy.GetComponent<EntityData>() != null)
{
enemy.GetComponent<EntityData>().RemoveHealth(weponDamage);
float enemyhealth = enemy.GetComponent<EntityData>().health.Value;
float knockback = 0;
if (enemyhealth <= 10)
{
knockback = 30;
}
else
{
knockback = 2;
}
enemy.GetComponent<Rigidbody2D>().AddForce(knockbackDirection * knockback * weponKnockback, ForceMode2D.Impulse);
}
}
}``` it gets called in the update function but if the host attacks it adds the damage but not the force but on client it works
If there is anyone here who uses Facepunch with Steam.
How do you do local testing with a second instance on the same pc?
For now I'm using the default Unity Transport for local testing or testing with my friends. But when I release the game on Steam I will use Facepunch Transport and Steam Matchmaking, but how can I test locally then, without uploading to steam updating the game on another pc with another Steam acc an then testing it? Do I need to switch between Unity and Facepunch Transport every time I want to test locally or want to Upload to steam. Or is there any way that I can use Facepunch Transport and Steam Matchmaking with one Steam Client on the PC but two Instances of the game?
U mean facepunch as in rust???
No I mean this: https://wiki.facepunch.com/steamworks/Installing_For_Unity
Hello, I'm planning a multiplayer project and could use some help from those with experience with Unity's Netcode for GameObjects.
The network will be true peer-to-peer. By that I mean that there is no specific host player. Every player is connected to each other. However, I've understood that Netcode for GameObjects requires one player to act as the host if I wanted to make a P2P game with it.
Is there a way around that? Is it possible for me to define each player as host? I would be using SteamNetworkingSockets with symmetric connect mode.
Hardly anything uses true peer to peer these days. It ends up being a security nightmare when everyone has everyone else's IP address. I think webrtc might be the only thing that uses it.
I use Steam's relay servers to hide the ips
Can you subscribe to the event of a network variable changing?
I'm integrating photon pun to my FPS game but the problem is, the player prefab instantiated has the main camera as a child to it. so multiple cameras getting instantiated casues some weird stuff to happen like the post processing being stacked as well as the players not seeing their own camera but rather other players
how do i work around this
All NetworkVariables have a OnValueChanged event you can subscribe to
Photon Fusion 2:
I have an object in my scene with a script where FixedUpdateNetwork should be called, but it isn't. However, for player prefabs that are spawned when players join the game, FixedUpdateNetwork works fine. It seems to be an issue only with objects that are already in the scene before players join. Can anyone help me understand why this is happening?
public class MovingTarget : SimulationBehaviour
{
public float Speed = 20f;
public float MaxX = 10;
private float direction = 1f;
public override void FixedUpdateNetwork()
{
Debug.Log("MovingTarget called!"); // This method never gets called
var position = transform.position;
position += direction * Runner.DeltaTime * Speed * Vector3.right;
if (position.x >= MaxX || position.x <= -MaxX)
{
direction = -direction;
}
position.x = Mathf.Clamp(position.x, -MaxX, MaxX);
transform.position = position;
}
}
It's NetworkObject should be correctly set up once the Host starts the game:
Found it... The class had to derive from NetworkBehaviour, not from SimulationBehaviour
Hello, I have a strange question. I'm fairly new to networking, but does Client Network Transform always refer to the GameObject or also to the Children ? Because I'm making a car racing game and had to add a ClientNetworkTransform to the tires.
Is it possible to start NetworkManager in offline mode so I can test stuff without worrying about Host and Client?
Just the game object. Anything that would need to be synced separately like the tires would need their own network transform. Though probably just an animator would work too. Would be less bandwidth
The host can just connect to itself. That is normally how single player is handled
How do you do that if transport is set to use relay?
You can just change the transport back
Having trouble accessing it. Is it NetworkTransport.TransportType?
Hello!
is there a way to link Lobby players with their respective Netcode players? to read the PlayerDataObject
I think it's under NetworkManager.NetworkConfig.NetworkTransport and you might have to cast it as UnityTransport. I've never really done it in code before
How did you know you had to cast it???
if (networkTransport != null)
{
networkTransport.ProtocolType = UnityTransport.ProtocolType.UnityTransport;
}```
This is as far as I've gotten. But i'm getting an error
You can create your own Transports for NGO like for Steam. Only UnityTransport has Protocol type.
Ah! thats genius. Im impressed you just knew that
This is what it's telling me. It seemed to accept the casting. It just doesnt like how im setting the value
networkTransport.ProtocolType should be networkTransport.Protocol
Says protocol is { get; } only
Figures it wouldn't be that easy. I guess you'll have to dig into how the Boss Room sample does it.
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/ConnectionManagement/ConnectionMethod.cs
hello guys, i want to create a rpg game (most like gta ) in multiplayer, i'm looking for the best way to make it without f3ck my wallet bcs i'm poor (i had a server), are any one know a free framework ?
Most of the frameworks are free. The connection services are what you are paying for. Unity Game Services has Relay. Steam has a P2P service and Epic Online Services has one too
can i use the unity technologies without paid the connection service ?
sure. you can have your players set up port forwarding on thier routers
i wouldn't recommend it though
You could also self host your own dedicated server
okay how i can download the framework ?
withoud the connection service sure
How to install Unity Netcode for GameObjects (NGO).
thx
I'm trying to spawn host as a hider and client as a seeker in a prop hunt game
now my player prefab is a hider
but spawning as a client i wanna prevent being spawned as a hider but as a seeker instead
how do i do that?
like i have it in my deafualt prefab list here
but i dont know where to start
public override void OnNetworkSpawn()
{
if (IsServer) // Make sure we are on the server when spawning objects
{
GameObject chosenPrefab = hiderPrefab;
GameObject spawnedObject = Instantiate(chosenPrefab, transform.position, Quaternion.identity);
spawnedObject.GetComponent<NetworkObject>().Spawn(); // Spawn the object over the network
Debug.Log(chosenPrefab);
// Optionally set the parent of the spawned object
spawnedObject.transform.SetParent(transform, true);
}
else if (!IsOwner)
{
GameObject chosenPrefab = seekerPrefab;
GameObject spawnedObject = Instantiate(chosenPrefab, transform.position, Quaternion.identity);
spawnedObject.GetComponent<NetworkObject>().Spawn(); // Spawn the object over the network
Debug.Log(chosenPrefab);
// Optionally set the parent of the spawned object
spawnedObject.transform.SetParent(transform, true);
}
}
Spawning host as a Hider worked. but Spawning client as a seeker didnt
it didnt even reach the Debug Log
so if i wanted to damage a player wiht a gun i know i need to send it thru the server first then the client, would i need to make a server script aswell as a script that sits on the player?
We need to know where this script is located. Also where are the hidden and seeker prefabs getting assigned. Keep in mind that only the server can Spawn objects.
Health is usually done with a network variable on the player.
When the player is damaged, have the server subtract from health.Value
Is it possible to send custom udp packets? I'm using NetworkTransport#Send, but this causes unity to complain:
[Error : Unity Log] [Netcode] Received a packet with an invalid Magic Value. Please report this to the Netcode for GameObjects team
```Is ``NetworkTransport#Send`` something that should only be used internally by unity? If I *am* allowed to use it, then what packet structure do I follow to make unity ok with it?
Hm, I think the issue is that my payload only includes the data that I want to send to the client.
The error message above comes from NetworkMessageManager#HandleIncomingData, which shows the packet structure that I should follow.
Still not sure if I'm supposed to avoid this way of sending packets completely though, but I'll probably try it anyways when I wake up tomorrow (unless someone suggests to do something else)
You can not send random udp packets to unity Transport. You would have to use a .net udpClient
Ah that's disappointing. Thanks!
If i just want the fastest way to send data from server to client, is unreliable rpc too slow?
And what about using NetworkIdentity?
reliability has nothing to do with the speed. Ping time comes down to your network connection. NGO does not use NetworkIdentity
Thanks a lot. I wasnt able to figure it out but that was a least a good thing to look into
Is there a way for. client to spawn/instantiate on the network? If only the host can do it, how does a client tell the host which prefab to instantiate?
No, only the host can. You can use a serverRPC to send the index of the Network Prefab list you want to spawn.
[ServerRpc(RequireOwnership = false)]
public void RequestSpawnPlayerServerRPC(int index)
{
var playerPrefab = NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs[index].Prefab;
var player = Instantiate(playerPrefab);
player.GetComponent<NetworkObject>().Spawn();
}
that works thank you
For this I ended up just having a Networkmanager in scene already for offlinemode and have ot set to Unity Transport and then if the scene is joined via an online method it gets destroyed and the Networkmanager from the previous scene carries forward already set to Relay Unity Transport.
Hey Im reworking my Singleplayer Game. I have a follow camera script:
` [SerializeField] private ThirdPersonCameraController m_CameraController;
[SerializeField] private PlayerController m_PlayerController;
private void Start()
{
m_JeepVisual.SpringsRestLength = m_Vehicle.Settings.SpringRestLength;
m_JeepVisual.SteerAngle = m_Vehicle.Settings.SteerAngle;
m_CameraController.FollowTarget = m_Vehicle.transform;
}`
what is the best way that my camera is following the player ? because it spawns as prefab and i cant reference it
I have player class and I have variables such as color, side, coin. How can I initially set this information for each player object?
with using Unity.Netcode
I thought reliability similuates TCP, where the client waits for packets if it's dropped and whatnot, no?
That's what I mean by it being too slow
Are you spawning the players manually or have you assigned the prefab in NetworkManager's player object?
I have it assigned in the NetworkManagers player object
this is my prefab, before I have it not as prefab
can I make it just as prefab too ?
It has to be a networkbehaviour, then:
protected override void OnNetworkSpawn() {
if (IsLocalPlayer) {
m_CameraController.FollowTarget = m_Vehicle.transform;
}
}
thanks is working
ScriptRunner.Exceptions.CloudCodeRuntimeException: Error executing Cloud Code function. Exception type: ApiException. Message: Unauthorized
umm why i'm not authorized to make a lobby?
solved, i used accestoken instead of servicetoken
What does LocalPlayer mean ?
Usually you can just set it using network variables in OnNetworkSpawn()
If you are sending updates every tick then you would want to use unreliable delivery, yea. Dropped packets should rarely be an issue unless the player is on spotty WiFi or mobile
Local player there means the local player object
How do I access the player object I set on the server in the client? I successfully set the side of the player in onNetworkSpan, but there are places where I need to use this player object in the client and I could not do this.
do you have any idea what tool i can use to test a lobby?
do i need to open the project twice?
I think , it is reply of my question
I'm not sure if I need to do player classic casting.
Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:
Do you know what the overhead on unreliable RPC is? This doesn't really touch on it too much: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/reliability/
If it's pretty much like sending UDP packet myself then that's pretty much what I'm looking for
You can use either ParellSync or Multiplayer Play Mode if you are on Unity 2023. But in either case you will need to switch the Authentication Profile
Guide covering the available workflows for testing multiplayer games locally.
I think I understand, thank you very much for your answer. But finally, I have 1 more question to make sure. I think localobject returns a networkobject. Since my player class derives from the networkobject, I will cast it to the player class, right? Because there is a variable called side in my player object, but this variable does not exist in localPlayer.
ty
There is not a lot of info about the actual overhead of the delivery types. But unreliable is the closest you can get to sending udp. If you need more control then you will dealing with Unity Transport directly.
Yeah my goal was to use Unity Transport directly for minimal overhead, but then that goes back to the issue that I'm not supposed to use it directly 😭
Yea it's a networkObject. You would need to use GetComponent() to access your player class
I guess I'll just try unreliable rpc to see if it fits my usecase first and if it's not good enough, I'll just have to think of a better solution
Thanks for the help!
How do I sync a list of network objects to all clients?
Oh you can totally use UTP directly, it just has to be within Unity
https://docs-multiplayer.unity3d.com/transport/current/about/
The Unity Transport package (com.unity.transport) is a low-level networking library for multiplayer game development.
As long as they have been spawned, then you can use a NetworkList of NetworkObjectReferences
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#networkobjectreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
I'm dumb... never noticed it and only found NetworkTransport#Send so I was trying to use that the whole time LOL.
Thanks a lot, that looks like what I need ❤️
` public class VisualsStateUpdater : NetworkBehaviour
{
[SerializeField] private Vehicle m_Vehicle;
[SerializeField] private JeepVisual m_JeepVisual;
[SerializeField] private ThirdPersonCameraController m_CameraController;
[SerializeField] private PlayerController m_PlayerController;
public override void OnNetworkSpawn()
{
if (IsLocalPlayer)
{
m_CameraController = FindObjectOfType<Camera>().GetComponent<ThirdPersonCameraController>();
m_CameraController.FollowTarget = m_Vehicle.transform;
}
m_JeepVisual.SpringsRestLength = m_Vehicle.Settings.SpringRestLength;
m_JeepVisual.SteerAngle = m_Vehicle.Settings.SteerAngle;
}
private void Update()
{
m_JeepVisual.SteerInput = m_PlayerController.MySteerInput;
float forwardSpeed = Vector3.Dot(m_Vehicle.Forward, m_Vehicle.Velocity);
m_JeepVisual.ForwardSpeed = forwardSpeed;
m_JeepVisual.IsMovingForward = forwardSpeed > 0.0f;
m_JeepVisual.SpringsCurrentLength[Wheel.FrontLeft] = m_Vehicle.GetSpringCurrentLength(Wheel.FrontLeft);
m_JeepVisual.SpringsCurrentLength[Wheel.FrontRight] = m_Vehicle.GetSpringCurrentLength(Wheel.FrontRight);
m_JeepVisual.SpringsCurrentLength[Wheel.BackLeft] = m_Vehicle.GetSpringCurrentLength(Wheel.BackLeft);
m_JeepVisual.SpringsCurrentLength[Wheel.BackRight] = m_Vehicle.GetSpringCurrentLength(Wheel.BackRight);
m_CameraController.SpeedRatio = m_Vehicle.Velocity.magnitude / m_Vehicle.Settings.MaxSpeed;
}
}`
Why does give me this line of code a 0 reference ?
m_CameraController.SpeedRatio = m_Vehicle.Velocity.magnitude / m_Vehicle.Settings.MaxSpeed;
I ask a lot of simple questions but I really want to understand fully. I have a code like the one below (I'm typing it from my phone right now, there may be errors in my spelling).
OnNetworkSpan()
{
if(IsServer)
{
this.side = "anything"
}
}
After creating this player object, how will I access the side of the player object in the client? With getcomponent
Thanks I'll use that, I tried network lists before but they don't let you use a network object refrence, you have to do a massive amount of other stuff so I kinda gave up.
If other clients need to know then side should really be a network variable. Then those clients can access side.Value
If othet clients dont need to know?
Then you can access it like any other component from the server
Thanks bro
Can you send me an example of how to write a network list? The only examples I've found throw error or are very unclear.
I tried using https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.0/api/Unity.Netcode.NetworkList-1.html#constructors but it has no examples of how to actually create a network list.
The sample code here should help. The big gotcha is that you must initialize it in Start() or Awake(), unlike regular network variables
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#synchronizing-complex-types-example
Introduction
Thanks thats what I need! Thanks for your help. I've found what I've been doing wrong, I've been trying to make the list hold Network Object refrences. For some insane reason, you can't sync lists of network object references but you can sync a variable holding a network object reference. This page has a workaround to allow you to sync a list of network object refrences, except its like 150-200 lines and is hela complex, kill me now. Its probably easier to just to sync the lists manually via creating a local list on each client, and syncing each index via a clientrpc.
What's the error that you're getting?
i don't know how to read this
isn't that usefull
does this 2 be the same?
isn't any way for multiplayer..? like something similar cuz this is quiet hard to debug
i dont find any topics on google and the documentation suckks
When I run this:
`public override void OnNetworkSpawn()
{
if (IsLocalPlayer)
{
m_CameraController = FindObjectOfType<Camera>().GetComponent<ThirdPersonCameraController>();
m_CameraController.FollowTarget = m_Vehicle.transform;
}
m_JeepVisual.SpringsRestLength = m_Vehicle.Settings.SpringRestLength;
m_JeepVisual.SteerAngle = m_Vehicle.Settings.SteerAngle;
}
private void Update()
{
m_JeepVisual.SteerInput = m_PlayerController.MySteerInput;
float forwardSpeed = Vector3.Dot(m_Vehicle.Forward, m_Vehicle.Velocity);
m_JeepVisual.ForwardSpeed = forwardSpeed;
m_JeepVisual.IsMovingForward = forwardSpeed > 0.0f;
m_JeepVisual.SpringsCurrentLength[Wheel.FrontLeft] = m_Vehicle.GetSpringCurrentLength(Wheel.FrontLeft);
m_JeepVisual.SpringsCurrentLength[Wheel.FrontRight] = m_Vehicle.GetSpringCurrentLength(Wheel.FrontRight);
m_JeepVisual.SpringsCurrentLength[Wheel.BackLeft] = m_Vehicle.GetSpringCurrentLength(Wheel.BackLeft);
m_JeepVisual.SpringsCurrentLength[Wheel.BackRight] = m_Vehicle.GetSpringCurrentLength(Wheel.BackRight);
m_CameraController.SpeedRatio = m_Vehicle.Velocity.magnitude / m_Vehicle.Settings.MaxSpeed;
}`
and I join as client. Then I have on this line of code a NullReference:
m_CameraController.SpeedRatio = m_Vehicle.Velocity.magnitude / m_Vehicle.Settings.MaxSpeed;
is it about networking?
Yes. When I start as Host all is working fine. But when I join as Client the Host loose the "reference" of the camera and the client has it.
and the host has after that the nullreference
C# Cloud Code Modules are still very very new.
The only this that might be an issue is your JoinLobbyAns might not actually be returning a lobby
Also I don't think the Cloud Code Function name has to be the same as the actual function name
if its not the local player your Update() will not have a m_CameraController assigned
just put another check before that line
What is a "Local Player?"
the player object of that client
OnNetworkSpawn() is checking if this script is on the local player object
Which line of code do I have to add as check ?
right before the line that give you a null reference error just add if(!IsLocalPlayer) return;
but then it does not work because he returns
the non local player objects should not need the local camera
and there is another option " as free as this" ?
and more used?
Ok i think i have a mistake
but also why does the camera controller have the Speed Ratio for the vehicle
Depends on what you are trying to do
The client can access their own camera with Camera.main
And the host ? 😛
public override void OnNetworkSpawn()
{
m_CameraController = Camera.main.GetComponent<ThirdPersonCameraController>();
m_CameraController.FollowTarget = m_Vehicle.transform;
m_JeepVisual.SpringsRestLength = m_Vehicle.Settings.SpringRestLength;
m_JeepVisual.SteerAngle = m_Vehicle.Settings.SteerAngle;
}
When I use this and I join then the camera swap from one player to the other one.
becuase you are not checking for IsLocalPlayer there.
But when I check
public override void OnNetworkSpawn() { if (IsLocalPlayer) { m_CameraController = Camera.main.GetComponent<ThirdPersonCameraController>(); m_CameraController.FollowTarget = m_Vehicle.transform; } m_JeepVisual.SpringsRestLength = m_Vehicle.Settings.SpringRestLength; m_JeepVisual.SteerAngle = m_Vehicle.Settings.SteerAngle; }
I get a Nullreference on:
m_CameraController.SpeedRatio = m_Vehicle.Velocity.magnitude / m_Vehicle.Settings.MaxSpeed;
and only one player has the CameraController reference
follow is working
that's correct. you need to also check if(isLocalPlayer) in you Update() too.
the positions will sync if you using a Network Transform
yes but then its not working for the client
ok its working
strange
I have tried this but got errors
is there a wokr around for funcs needing monobehaviour but thee rest of the script needs networkbehaviour
a game like chess game
same logic
every player makes a move(2players)
What do you mean? Networkbehavior inherits from Monobehavior
Could you get the Chess sample working at all?
https://github.com/Unity-Technologies/com.unity.services.samples.multiplayer-chess-cloud-code
There are other serverless platforms you could use like AWS Lamda, or Playfab Could Functions.
But I guess it might be more straightforward to just use Unity Lobby and Relay. You are not likely to go beyond the free tier limits even after you launch
i can't open the full project in unity
so i can't deploy the modules
from unity.. and by cmd isn't working too
i found a way to deploy but the game isn't working(chess)
can't even host lobby
when I starthost how can I change spawn position of the player prefab ? 🙂
(using NGO) more of a logic question on how to approach my issue: Network objects can not be a child of a non network object. I need my player to be able to equip a new "gun" when they walk into it on the map. Issue is that I have 2 guns that need to appear, one for the client who collects the gun (they dont see their body, arms or anything just the gun when it spawns) which is easy as you can do this locally without spawning a networkObject. However this second gun is for the other clients to see when looking at the player who collected the gun. The player runs an animation in all states which means I need the gun to be a child object of a transform attached (child of) the Players Rigs hands. But again you can't do this as network objects can only be a child of a network object, and additionally a network object can not spawn with nested network objects. So am I supposed to run a client RPC to tell each client to instantiate and destroy the gun object each time, or is there another way to do it that sounds less bad than instantiating a nested network object in the players hand just for the sake of being able to spawn the gun on it in one ServerRpc?
I don't know what the issue is. But if it's giving you that much trouble then don't bother with cloud code. You can do all of it in game through the Relay service and lobby
i was going to use lobbies services in cloud, but it doesn't work
I don't know what I'm talking about but look into asynchronous methods and using the await function in unity (I think this works with RPC's)
NGO can only operate on the main thread. You probably shouldn't be calling RPCs every tick in any case
If you are using the automated player prefab then you can change the spawn position in the Connection Approval callback
and do i need to use netcode?
Yes
You aren't trying to make a multiplayer chess game using lobbies and cloud are you? Netcode is the code that sends data such as a moved piece on the chess board not cloud data. Cloud data is for storing information to then pull at a later date like unlocked chess board skins or something.
You would use an RPC or network variable on the root player object to tell the client what gun to Instantiate
You totally can. Check the unity repo I posted above. It uses cloud code to validate moves and update the game state saved to Cloud Save.
I guess it makes sense as the cloud is essentially running as a server at that point? Holding all the data for any movements. And its a low action game so not much data is needed to be sent.
the best option is still the cloud code.. i ll try to take step by step with the join lobby until it works
i hope
Right, cloud code is basically a server that runs one function at a time. You'll see it called serverless architecture
what I mean is, what is best practice / uses less bandwidth, calling a clientRPC to instantiate the gun locally on each client and then also a clientRPC to destroy the local to the client gun. Or is it better to instantiate a nested network object on each player post character creation in order to allow for a single server RPC to be called creating, parenting and destroying the gun. (or am I digging into this too much)
like i only need moves.. netcode is like a live connection, right?
so its too much for what i need? i think?
Parenting network objects is a huge pain in the ass. I've never really gotten it to work properly
yeah it is a pain in the ass lol, I have it working just don't know if the approach I take is even close to being "efficient for bandwidth"
For weapon switching I wouldn't worry about efficiency. It's not like players are doing it every frame.
true, that's enough help for me lol. I didn't even think about that, I keep getting so caught up in doing everything "the right way"
CloudSaveData.SetCustomItemBatchAsync its like a structure where i can find my save data and i can update it or read it when ever i want?
You are not wrong. If you can figure out where your issue is then cloud code would be the better option
Premature Optimization is the Devil
SetCustomItem is only for saving data. There should also be a GetCustomItem or something like that
so frustrating that i can't get any info from this logger
like what's the error thrown
(Unity Lobby Service)
Hey guys, is there something like "unsubscribe" lobby events? Opposite of SubscribeToLobbyEventsAsync method, I mean.
I would open a ticket on the Cloud Dashboard for that. You should not be getting that from the Chess Sample module
rn im trying to use quickjoin
but it looks like i dont have a lobby
even it is hosted
nah, i don't know what to do anymore.. can't find a way to see what's the problem
Quickjoin will not find a lobby if its not already been created. You'll need to use CreateLobbyAsync then return the lobby code
i use 2 clients, on first i host the lobby and on second
i try quickjoin
do i place NetworkObject component on every object in the player?
@sharp axle are you here?
I'm around
I did what you said yesterday and it worked successfully, but after adding networkVariables to my player class, I started not being able to connect.
this is public class Player : NetworkBehaviour, IPlayer
why does this not work?
and in another script i have this
its giving me an error
line 112
I don't think you can use a network variable as a property like that. I'm surprised get;set; did not throw any errors
I avoid using singletons. especially with networking. Movement.Instance is likely not getting set on the clients
so just reference it manually?
yep
i know why, initilization was in awake
so it was initializing before the network manager
but still imma stick with manual
hi, did you work with photon? its worth? I'm thinking switching to it instead of the cloud code
I've used it before. But it's a replacement for NGO not cloud code. Plus its way more expensive. I'm not sure if photon has a replacement for cloud code.
how expensive is netcode?
NGO on its own is just the framework. It's free. The services like Relay and Lobby is what you pay for. But they have a pretty generous free tier.
https://unity.com/solutions/gaming-services/pricing
I'll try tomorrow, ty so much for your time to explain these things 4 me. Happy new year!
this is a short script for switching weapons
why doesnt it work properly for other players?
this is what i mean
it only switches the weapons for myself
the owner
i mean it looks like its also switching for other players but the old weapon is not getting disabled
i think i got it but im not sure
You need an RPC or some Network Variable to tell the other clients what to enable/disable
would this be fine?
or can i do it better
That should be fine.
do i have to pass it the client rpc through the server one tho?
or can i just call the client rpc straight away
Has to go through the server
then cant i just put all the logic inside the server rpc?
im trying to understand it sorry man
The other clients need to know about the change too
oh i think i get it
You could also just make the activeWeapon a NetworkVariable.
then the client can listen for activeWeapon.OnValueChange and do the weapon swapping there.
Either way works
could u just help me understand one more thing
here im just passing selectedWeapon
instead of the weaponIndex
and it doesnt work anymore
why is that
the weaponIndex is what is getting sent across the network
could u just help me out with one more thing
gimme a sec i'll show you what i mean
the name of the function is misleading because its not ik
all this does is rotates the lowerSpine bone around the x axis
accordingly to how much the player is looking up or down
and the player can only see this happening on himself
and other players cannot see it
this is the bone im rotating
i tried adding a client network transform
to affect the x rotation
same issue actually. you would need to send the x rotation as an RPC
really?
or you could use IK rigging package and just have the IK target have a network transform on it
so would this work?
Yea. it should
its buggin out
maybe cause its in LateUpdate?
i might just do it with ik
all i'd have to do with ik is just have the client network transform on it right?
On the IK target, yea
alright
also should i be checking IfLocalPlayer
instead of IsOwner
cause im gonna have 3 players
and IsOwner checks if its the player hosting right?
IsOwner and IsLocalPlayer will normally be the same. IsOwner just checks if the client is the owner of the object. The player could own multiple objects not just the player object
Photon Fusion question: Does anyone know why FixedUpdateNetwork is never being called on my NetworkBehaviour derived class?
There's a NetworkObject component on the same gameobject. Not sure what else I'm supposed to do
Oh and it IS being called on another class that gets spawned. Just not on this one manager class that's already in the scene
Im using photon PUN 2 and im trying to access a random player's script which is in the room i tried using an array and tried finding a random player by using Random.Range()but that didnt work since PhotonNetwork.PlayerList.Length OR PhotonNetwork.PlayerListOthers.Length isnt a gameObject
how would i do this
public GameObject[] players;
int randomPlayer = Random.Range(0, players.Length);
GameObject[] playerGameObject = GameObject.FindGameObjectsWithTag("Player");
for (int i = 0; i < players.Length; i++)
{
players[i] = playerGameObject[i].gameObject;
}
GameObject playerWithTheBomb = players[randomPlayer];
playerWithTheBomb.GetComponent<PlayerBombManager>().bombText.SetActive(true);
``` i tried this but it doesn't work
Can someone explain and show me an example of how to synchronize variables via rpc for a health script. Using netcode for gameobject
Normally health would be a Network Variable. Those are synced automatically without the need for RPCs
will this code be synchronized?
no, those are not network variables
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/
Introduction
If it's not too much trouble, can you give us an example?
There are examples in that link
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#onvaluechanged-example
Introduction
i want to make a isSingleplayer bool
which if true would always return the IsOwner to true
and if it isnt then let the network decide if IsOwner
how can i do that?
i tried something like this
but i dont know what im doing
Are there any helpful resources on sceneloading in netcode. I have it working other than when it doesn't my client will randomly decide every now and then that instead of loading the scene along with the host it will just not.
you can only change ownership by asking the server/host. To do this you have to send a ServerRpc (a function that runs on the server / host only, but is told to run by the client). Its also worth noting that if you are calling a serverRpc to happen on an object the client doesn't own then you need the parameters [ServerRpc(RequiresOwnerShip = false)].
In Single player, you would be the host and would own everything anyways
Netcode is server authoritative meaning any changes made are required to be done by the server (instantiation, ownership transfers, etc)
what im trying to do is not having to hide the player every time i wanna test
and then host
cause at the moment i have to hide him before playing
then host a game
and change stuff
Oh your statement confused me lol, you are trying to make a singleplayer vers and a multiplayer vers? Do you need the networkmanager to still run for the game to work?
yeah it confused me as well lmao
as long as you are usine Network Manager Scene Manager to load the scene then it should automatically sync to the clients
i just wanna be able to start the game and if the player is active to not need to host a lobby
yup I'm just an L rn cos I am using that and it aint working sometimes lol
If the network isn't started then there is no ownership of anything.
yeah thats why my code breaks
how do i overcome that?
it returns false
just use the bool like normal. IsOwner is not going to work
use isSinglePlayer instead of IsOwner
several approaches, could make a player prefab for the multiplayer vers and a prefab for the singleplayer vers and different scripts. Or you could just copy and paste the code under two different if statements asking if it is singleplayer == true {do singleplayer vers of events} and else {do singleplayer vers of events}
you cant ask "IsOwner" without errors if you aren't connected to a game
yeah i thought the easiest way would be to check if isSingleplayer is true, and if it is always return the IsOwner to true
because the isSingleplayer bool would be for testing
only
i'd get rid of it later
in this script in awake i wanna check if isPlaytesting is true, and if it is to override the IsOwner to always return true;
and if isPlaytesting is set to false, to let NetworkBehaviour decide if IsOwner is true or false
ok so IsOwner is a network variable instead of using this create a new variable in your player script that asks (isOwner) for all the movement and other actions. instead of using the (isOwner) variable make a new one and call something else like "IsPlayerUsed". At the start of the script take the Isplayerused and make it = isPlaytesting. Then OnNetworkEnable(){IsPlayerUsed = IsOwner}
I don't know if that would defnitely work but worth a shot sounds logical
let me know how it goes
Normally for single player you will just connect to yourself as host
by default, clientRpc sends to all clients? I am calling a clientRpc with params to set a singular client to send the rpc to (works fine). but then in this clientRpc i call another clientRpc without any specified params, but it just ends up sending a clientRpc to itself, how can I make it so that it sends to all clients again.
only the server/host can call clientRPCs.
thanks
so have a bool called IsPlayer, and another bool called isPlaytesting
and in some script in awake check if isPlaytesting, and if its true return true, and if its false make IsPlayer = IsOwner
wait no it would have to be in update as well
right?
something like this would work right?
also whats a better name for the bool
other than IsPlayer
cause it doesnt really make sense
Is owner is always going to be false if you are offline
bruh its so broken
i dont know what to do
like when i wanna make animations
i gotta host a lobby
and all that
What you do mean? If you just need to test stuff then just call StartHost() and do your thing
so i could just do that
the second screenshot
automatically start a host
if is playtesting
is set to true
pretty much, yea
why did it automatically add a network object?
when i attach the script
and i cant remove it
Netowrk behaviors must have a network object
how come this doesnt need it?
it doesnt have one
and it still works
oh its mono behaviour
alright my bad
so this is what it looks like
i mean it works
i had to change awake to start
because it was giving me the "NetworkManager is null"
cause this was running before network manager was even initialized
that's correct. Singletons are normally initialied in Awake()
lol, naming is the hardest thing in game dev
I call my script that does all that NetworkConnectionManager
yeah could do
alright thanks man
you'll probably see me here shortly again with another problem 🥲
why when these objects are not active by default i get an error?
but when they are active by default it works
i need them disabled tho
i think the network manager isnt initializing them or something because there not active
Child objects have to be enabled by default. If they are network objects then they should be disabled with a RPC
hi, any idea why it says that im already in lobby? i create a lobby on a client and join on 2nd..
You need to switch authentication profiles if you are testing from the same PC by signing in anonymously
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/testing/testing_locally/#ugs-authentication
Guide covering the available workflows for testing multiplayer games locally.
ty
i think this is what caused the cloud code not to work
so how do i overcome that problem
because i need them to be disabled by default
You can disable them in OnNetworkSpawn() if needed. Or just disable the renderer on them if it's a visual bug
what s wrong?
That code is outside of the class.
#if types don't need to be outside?
or i need to include other libraries?
they are still functions so they still need to be within the class. Its just that they only get run under certain conditions
i m pretty sure im doing it so wrong
It needs to be just after you initialize UnityServices or right before you SignInAnonymously()
also that specific is for when you are using ParrelSync to clone the project
worked, thanks. i don't need to clone again, right?
instead of doing it in start, how can i call the SelectWeaponServerRpc() when a client joins
https://hastebin.skyra.pw/imecozoray.csharp
I don't think so.
You could call it in OnNetworkSpawn() if this is on the player object
how do i access that method
hei, i ve got back to the cloud code, but now i can't req anything because i get 422 bad request. I've found this https://forum.unity.com/threads/getting-422-unprocessable-entity-bad-request-in-cloudcode-request.1510301/ and my question is, do i need to sync anything ???/
like i can't even get the sayhello to work
What is the cloud code constructor doing?
um..? what constructor?
In GameLogic
Maybe try commenting out the constructor since is not being used
samething
i ll try to remake everything
please help. How do I synchronize this on the server. This is an array with the health of body parts. And how to make it synchronized.
netcode for gameobject
https://streamable.com/qdrfh8
@sharp axle i started from 0 again and got it to work(get lobby, join by code etc), now i don't understand how startgame is called
it hans't any command filed..
found it
hey man, could u tell me what networking solution you're using
cause im new to networking and i wanna see what other people are also using
hei, im makeing a 2d game like chess and i'm using Cloud Code
and lobby to make/join lobby
oh alright thanks man
You would either use a custom network variable or a NetworkList of health values
I did not understand how to use it, I spent almost 2 evenings and still do not understand how to record and call functions.
I'm not sure what you mean by record and call functions. By default network variables are server authoritative. When a player gets damaged the server would update the network variable which would then get synced to the clients.
If it was built as a single player system then a lot of it will likely have to be rewritten.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Unity.Netcode;
public class health : NetworkBehaviour
{
[SerializeField] private NetworkObject NetworkObject;
[Space]
[SerializeField] private bool isHitBox;
[SerializeField] private health basicHealth;
[SerializeField] private int healthPartsNumber;
[Header("Basic")]
[SerializeField] private int[] healthParts; //<--- health counts
[SerializeField] private Image[] iconParts;
private void Start()
{
iconParts = FindObjectOfType<getIconParts>().getParts();
}
private void Update()
{
if (!NetworkObject.IsLocalPlayer)
{
enabled = false;
}
}
public void GetDamage(int Damage)
{
basicHealth.healthParts[healthPartsNumber] -= Damage;
}
}
You can show me with the example of this script. Please do.
any idea why i get a message twice?
I don't have time to rewrite your script but an example of a network list is here
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#synchronizing-complex-types-example
Introduction
I would guess that start lobby is getting called twice. check the event message and see if its the same too
Why i cant change value
Whichever Client is trying to change that value is not the owner of that object
ChatGPT is telling me to use NetworkPrefabs to access the prefabs list but Unity is saying that doesnt exist... Did the internet lie to me?
Try Unity Muse instead
But it's .Networkconfig.Prefabs.Prefabs[]. Prefab
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.6/api/Unity.Netcode.NetworkConfig.html
Man... how do you find this stuff so fast. Youre the best
How can this be fixed or circumvented?
Check if IsOwner before trying to change that value
When I shoot from the host, everything works, but when I shoot from the client to the host, nothing happens
Sounds like the client is not the owner of that object. You would need to send a serverRPC to change the value in that case
How can this be done?
Here is how to use serverRPCs
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/serverrpc/
Introduction
Hello, why is my client gameobject floating in air. And the server side camera is not following the GO. I am using netcode for gameobjects
this is my movement script. But i dont think its the one causing the issue.
private PlayerInputActions _playerInputActions;
private float _speed = 3f;
private void Start(){
_playerInputActions = new PlayerInputActions();
_playerInputActions.Player.Move.Enable();
}
private void Update(){
if (!IsOwner){
return;
}
Vector2 inputVector = _playerInputActions.Player.Move.ReadValue<Vector2>();
transform.Translate(new Vector3(inputVector.x,0,0) * (Time.deltaTime * _speed));
HorizontalAnim(inputVector.x);
}
private void HorizontalAnim(float horizontal) {
//animator.SetFloat(Speed, Mathf.Abs(horizontal));
Vector3 scale = transform.localScale;
if (horizontal < 0) {
scale.x = -1f * Mathf.Abs(scale.x);
}
else if (horizontal > 0) {
scale.x = Mathf.Abs(horizontal);
}
transform.localScale = scale;
}```
public void GetDamageServerRpc(int Damage)
{
basicHealth.healthParts[healthPartsNumber].Value -= Damage;
}```
If this is the case, the client can damage the server. But the server can't damage the client.
``` [ClientRpc]
public void GetDamageClientRpc(int Damage)
{
basicHealth.healthParts[healthPartsNumber].Value -= Damage;
}```
And like this, the server can damage the client, but the client cannot damage the server
why so?
https://streamable.com/1zzj49
what's wrong, I'm [ServerRpc(RequireOwnership = false)] and only the client can do damage to the host. And if you shoot from the host to the client, nothing happens

It depends on who has write permissions for that list. It can either be server only or owner only write permissions. ServerRPCs can only be called from a client and will only run on the server and the clientRPC can only be called from the server and will only run on clients. The host is the server and a client so it can call clientRPCs on itself
So what do I need to write to make it work for both?
It can only be one write permission for the list.
anyone?
Looks like the characters are getting spawned on top of each other and gravity isn't triggering. It's still acting grounded
But it's landing on the ground on the client side. The problem is only occurring on the host side.
In what sense? I mean, I can't make sure that both sides can do damage to each other. If that's correct. So what do I need to do?
dunno. are you using a network transform or client network transform?
You can. You just have to make sure that the network list permissions are correct and that the right client is making the changes
If you can do it in 1 line, you can write it like this. Because I couldn't find it on the Internet
You definitely can not do it in one line.
heei, simple question, when i call an cloud code command, i can only pass string right?
if i want to send int data etc i need to sent it like string?
No, believe its a dictionary of parameters. The key of the dictionary is a string for the variable name, and the object is the value of it
hey there guys
could you help me spawn this for other players?
so im trying to instantiate muzzle flash in different places for different people
so for the owner of this object so the player that is shooting i want to instantiate a muzzle flash at the clientBarrel.position and for other people to see it at serverBarrel.position
how can i do that?
so the first check would be correct
because it would only spawn it for the player that is shooting
and other player wont be able to see it
but now in the else statement i need to spawn it for every client that is NOT THIS PLAYER
this is what i have now
and it spawns the muzzle flash on every client
i just need to spawn it on every client other than the one that shot it
so every client other than this one
wait i dont have to spawn it as a network object
i ended up with this
but it still doesnt work because it still spawns the muzzle flash on the player that shot
so on the owner
Hello, I am trying to get Vivox setup with Mirror in Unity. My goal is to have proximity chat in my game. I can't seem to find any resources or examples of how to set this up though. Can anyone point me in the right direction as to how I should implement 3D positional audio with Vivox? I have this script in my Game scene that I think is joining the channel but I cannot figure out how to update the players position in game
welp nevermind i got Dissonance lol
client network transform
Any idea why this networkvariable doesn't sync??
It works if I make it a ServerRpc instead, but that feels inefficient
@sharp axle if i save a bool in cloud when i do this: var HostReady = saveResponse.Data.Results.Find(r => r.Key == "HostReady") it will return a string or bool?
I created a short tutorial for anyone who is interested to start with Unity WebSocket and WebRTC networking 🙂 https://www.youtube.com/watch?v=fgQw_sClwVo
A short tutorial of how to use #Unity #WebRTC in combination with #WebSockets. In this project, we'll implement everything from scratch in Unity. NO npm, NO webdev, NO complex setup.
Unity WebRTC package: https://docs.unity3d.com/Packages/com.unity.webrtc@3.0/manual/index.html
WebSocketSharp Github: https://github.com/sta/websocket-sharp
Unit...
If you saved it as a bool then it will return a bool
i might have a problem checking it..
it wont let me use the boolean false
You've got false in quotes there making it a string
i m trying with
didn;t work
im trying with (bool)HostReady
to the value
I mean in your if check there
yes, worked. ty
one more question
when i save data to cloud like this
when i want to save anything else, do i need to save the old variables again??
No, you don't have to
how do i make it so each player has its own camera