#archived-networking
1 messages · Page 10 of 1
If I was to create a server-side networkobject
could all my clients see the variables and stuff going on inside it?
If you are using NGO and the clients have read access to the network variables
do they have read access by default?
Introduction
wait
does this apply to both networkvariables and normal variables? I would think not
No, regular variables don't have any kind of permissions at all
What about scripts?
i'd imagine yes
Network behaviours themselves do not
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior
Both the NetworkObject and NetworkBehaviour components require the use of specialized structures to be serialized and used with RPCs and NetworkVariables:
if(IsClient && IsLocalPlayer)
{
_playerMovement.ProcessLocalPlayerMovement(x, z, jump, mouseX);
}
else
{
_playerMovement.ProcessSimulatedPlayerMovement();
}
I implemented client prediction, and it works fine for the most part. Because the player is no longer a network transform, we need to simulate the other players. When playing as the host, it simulates the clients just fine, but when playing as the client, it doesn't simulate the host. This is the code to determine if it should simulate.
**posted in the wrong channel so posting here **
hello I'm new to net code for game objects and i have ran to a very wired issue that when i call my server RPC on client it gave me error only the owner o the RPC can call the RPC so I went ahead and added the requireOwnershiip= false and no I don't get the error but the code is not being executed on the server but if the server does the same it works just fine any way to fix this I would post errors but i don't get errors if you like i can show a vide might help explain better so I can get some sort of guidance that would be much appreciate it.
my game have 15ccu * 20 = 300 but i have 4k DAU, so, people that join my game usually uses solo instead of multiplayer mode, its normal in games that offer both options?
It really depends on the game. Those are just rough figures and a lot can influence them. Releases, events, etc. but also the gameplay and community. Maybe they like the online mode better.
With 300 CCU, I would expect about 6k DAU with those calculations. Your players seem to be quite active, if we go by those expectations. Could be good.
Anyone?
serverRPC not running
Hey, when it comes to networking and making a multiplayer game, is it something I need to be thinking about as I write the code for my game, or can I work on the networking after I complete some of the more fundamental stuff (player movement, assets, game design, etc)
If you aren't doing it at the beginning then you're going to just end up rewriting everything anyways
Good to know now, appreciate it
Quick question, If my player prefab is spawned in for each client, does that mean that I need my camera to be attached to the player prefab as well?
The opposite actually. Unity expects there to be only one main camera in the scene at any one time. So you need to make sure that only the local player has control of the camera
ah that makes sense, so its good that my camera is separate 🙂
yo on the photon engine, why can't I find any spawnpoint
Using the Unity Multiplayer Netcode for GameObjects I want to transfer ownership to the user/client that clicks on a GameObject. Whenever I try to call netObj.ChangeOwnership(NetworkManager.Singleton.LocalClientId); from the client I get NotServerException: Only the server can change ownership
Just like the error says, you'll need to send a serverRPC to change ownership
TransferOwnership.cs
private void Update()
{
if (Input.GetKeyDown("space") && GetComponent<NetworkObject>().IsOwner)
{
print("space key was pressed");
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
}void OnMouseDown() { if(NetworkManager.LocalClientId.Equals(0)) { print("TestCube clicked"); // Check if the local player clicked on this object // Get a reference to the network object NetworkObject netObj = GetComponent<NetworkObject>(); // Assign ownership of this object to the local player netObj.ChangeOwnership(1); } }
@sharp axle Yeah serverRPC seems the way to go. Though I've tried it likes this first. When the server clicks on the cube which has attached this script, the ownership is changed to the cliendId==1 (the second player which is connected). Still though the second player can't use the space button to move the cube
What am I missing in my logic ?
the cube has these attached
@sharp axle after your recommendation changed the script to this
`public class TransferOwnership : NetworkBehaviour
{
private NetworkObject netObj;
private void Start()
{
netObj = GetComponent<NetworkObject>();
}
private void OnMouseDown()
{
// Check if the object is already owned by the local player
if (netObj.OwnerClientId == NetworkManager.Singleton.LocalClientId)
{
Debug.LogWarning("This object is already owned by the local client.");
return;
}
// Call the server RPC to change ownership of this object to the local player
ChangeOwnershipOnServerRPC();
}
[ServerRpc(RequireOwnership = false)]
private void ChangeOwnershipOnServerRPC(ServerRpcParams rpcParams = default)
{
// Change ownership of this object to the calling client
netObj.ChangeOwnership(rpcParams.Receive.SenderClientId);
}
}`
and now the ownership can change when called from the clients
moving on to make the actualy movement work
can you make a network variable with a component like Transform?
No. You can send Vector3s but not the entire transform. This is what the Network Transform is for
are there things like Network Transform for all components, or just specifically Transform? I guess you wouldn't really need to send other components right?
Not all components, but there is network rigidbody and network Animator.
okay ty
(sorry for bothering you so much I'm just really lost): Let's say I have a player prefab that's spawned in for each client, and on each player is a movement script. Are all the players who spawn in accessing the same movement script, or are there separate scripts that store separate variables?
in netcode, is there a way to get a networkprefab from the networkmanager by index?
No you don't have direct access to the network prefab list.
"I'm working on a multiplayer game using Photon and I'm having issues with choppy/laggy movement for players observing each other. I've tried implementing smoothing using Lerp in my PhotonViewer script, but it doesn't seem to be helping. Can anyone help me identify the issue and provide a solution? Here's a snippet of my PhotonViewer script: https://gdl.space/uveqidozes.cppThanks in advance!"
https://forum.photonengine.com/discussion/18707/jittery-player-movement - I haven't used photon, but I wouldnt think you need a coroutine to do what you want. Here's the snippet I saw that seems to handle the lerp on others
private void FixedUpdate()
{
if (pView.IsMine)
{
//rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
rb.velocity = Vector2.Lerp(rb.velocity, new Vector2(horizontal * speed, rb.velocity.y), 0.1f);
}
else
{
SmoothMovement();
}
}
void SmoothMovement()
{
rb.velocity = Vector2.Lerp(rb.velocity, _smoothMovementVector, 0.1f);
}
also it seems like this link here seems to suggest you may not want to be setting the rotation directly - https://hutonggames.com/playmakerforum/index.php?topic=20899.0
i mean i have same thing, if i test it on my pc, open 2 tabs with 2 players, make a server, one of the players is always seeing the other player lagginng but if you go test it from 2 different pcs it work, at least that how it is on my side
Can you use net code to upload a steam game or do I need to use steam works?
Steamworks is optional. but it works along side Nedcode in any case
Awesome. So is it okay for me to focus on getting the net code to work for now and then I can inplement steamworks later?
I’m assuming that steam works mainly has to do with user profiles and lobbies
how to sync gameobjects and keep them synced (position, rotation, etc) with late joining clients? I am unable to sync the scenes when using custom scene management with netcode
hello guys, i need some help with networking (unity network)
so, i have a host and a client. I need to hide something for the host from the client (hidden visually i mean). But i get the error "can't hide something from the server". That's obv, cause server needs to know everything, but the host is a client too... and i need to hide that object from the "client" part of the host. What i should do?
i'm using GetComponent<NetworkObject>().NetworkHide(0)
maybe you guys have some less raw method, i need only to hide it visually after all...
how about using SetActive on the GameObject's graphics?
that's my plan but how can i set that on/off on a specific client from the server?
for all clients or for a single one?
single one
you can do a ClientRPC call and give it a client id
and i have its networkID
ok and next? I mean how i can access at the object into the client from the clientRPC (that is in the server)
it seems ClientRPC can't take a specific client id, but you can do a simple if check to see if the id of the current client matches the id of the client you want to call the method for
yeah but i don't know how call a method for a specific client from the server
how to sync gameobjects and keep them synced (position, rotation, etc) with late joining clients?
ServerRPC -> ClientRPC (will be executed on all clients) -> add the if check so only the required client executes the rest of the function
you can compare your stored client id with NetworkManager.LocalClientId in the if
hey guys is it possible to build a webGL with the unity Networking for gameobjects?
It is but you need to use Unity Transport 2.0 which is currently in preview
how can I get it, I already updated the project to 2022.2 but it does not show in the package manager
The Unity Transport com.unity.transport package repository adds multiplayer and network features to your project. See the following changelog for new features, updates, fixes, and upgrade information.
I have pre release packages enabled
but only installs version 1.3.1
Newest ones might only be supported by alpha builds
You could ask on their discord as well
Link in the pins
But usually very new features you can't see are either for an alpha or on experimental branch in their repo.
thank you so much
You have have to install it by name then specify the 2.0.0 version number
Hey everyone. If I wanted to create a basic chat room in Unity would it make sense to use the new Netcode for Entities?
Are you actually using Entities? Or are you using GameObjects?
Technically neither; I haven't even started a project.
Right well, for a chat room you definitely do not need Entities, so you'll be using good old GameObjects, therefore you need Netcode for GameObjects not Netcode for Entities
I'm not even sure how to frame what I'm asking but I think in my head it's a question of using the new Netcode (for Entities or GameObjects) vs something like WebSockets
Using netcode, how do i access the server? is network manager the server?
can u even access the server?
let me clarify my question
Does the host and the host's scene view represent the server?
You'll need to figure out what you actually want to do. Because a basic chat room wouldn't use Unity at all. If you need a chat service then Vivox is what you want
The Host is the Server
okay, so if I have a script as part of my server-side movement stuff, and I need this script to be run by the server, how do I go about having only the host read it?
The same as any script. It needs to be on a gameobject in the scene or you can reference it as a static class or singleton. Just have it check if(NetworkManager.Singleton.IsServer) before it runs anything
oh, okay. Thank you
Movement server side
does anyone know if netcode with server authoritative movement has problems moving a character controller?
[ServerRpc]
private void MoveServerRPC(Vector3 move)
{
if (_controller != null)
{
_controller.Move(move);
}
}
i can make the client jump with no problem but when i want to move him nothing happens.
hm. nvm it is working but the character moves very very slow. barely visible movement for the client
guys, I'm planning to start learning Mirror for networking, what are my options when it comes to port forwarding/relay service?
It's in the manual. https://mirror-networking.gitbook.io/docs/manual/transports
Also checkout pinned resources, including Mirror server link.
thanks
does a NGO server authoritative movement sample game exists from unity?
There are different samples in the documentation (and in the package itself) . Also it forces you by default to use authoritative approach unless you extend and make changes.
Check the pins for documentation and server links
you sure? havent found a tutorial or sample which does not use clientnetworktransform. doesnt seem authoritative for me or is there a misundertanding on my part?
client NetworkBehaviour objects are prohibited from calling server RPCs
prohibited like it doesnt work or bad practice?
Rather executing calls on other clients if it's not a server.
I would suggest this tutorial, it makes it clear how to use authoritative (or not) calls https://www.youtube.com/watch?v=3yuBOB3VrCk
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubref=ngo
FREE Third Person...
may i ask. when you use client network transform then the client can possibly send whatever position he wants and the server doesnt care? like easy cheating? because this tutorial also uses it for player movement
Yes, this tutorial shows how to workaround and apply things with client authority. You don't have to do that.
Authoritative setup is slightly more complex because client sends a command it wishes to do, then server will actually process that and apply it and then propagate to every client
yeah having a rough time finding resources for that. also doing movement prediction or all other things for a smooth experience is kinda hard to find for the NGO
Depending on your needs how advanced you need it to be, you might want custom prediction anyway.
not really. just want the most basic Authoritative movement
Like fake doing action before server agrees to it. Then server updating its position will be more minor.
Will have a better responsiveness and less of a hitch
by any chance do you know if there is a example for Authoritative movement for ngo?
As far as I know all of them are. I haven't look at a lot of them, though. Just it's a default implementation.
well ok havent found a single Authoritative movement implementation 🥹
In this video, we take a look at how to send your input to the server for him to replicate the player's movement!
If you have any questions, please leave it in the comment and I'll make sure to try and answer.
We just launch the discord server! Join us if you need help or want to talk about game dev! The link is in the channel banner!
00:00 -...
Any ServerRpc call you see is client asking a server to do something. This is server authoritative.
i know. but im talking especially about movement
For example client asking to move right. Server will take that and move the network transform 1 unit to the right.
If you have variable movement, it's your responsibility to write a verification for that.
alright. still cant figure out why my client character controller acts super slow.
So if client asks to move right 5 units. Server will process that and see max speed is 1 so it will move right only 1 unit.
So you would not want to client do any calculations. Server should keep track of velocity
and how far thing must travel
does network transform handle movement verification on its own when i use regular character controller?
server has complete control of network transforms by default. If your client move something with network object component locally without telling the server, next time server propagates changes it will reset object position to own values
Everything happens on the server, it only updates and propagates data to clients
Clients do not tell server to do something, they ask, then server does what it needs. In authoritative anyway.
thank you for your help
i still have this weird feeling that [ServerRpc] is eating the time.deltatime here.
var moveVector = targetDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime;
like i said. i cant control my client like i can control my server player. the client is moving in slow motion
private void PlayerMove(Vector3 move)
{
_controller.Move(move);
}
private void PlayerRotate(float yRotation)
{
transform.rotation = Quaternion.Euler(0.0f, yRotation, 0.0f);
}
#region Networking
[ServerRpc]
private void MoveServerRPC(Vector3 move)
{
PlayerMove(move);
}
[ServerRpc]
private void RotateServerRPC(float rotation)
{
PlayerRotate(rotation);
}
#endregion
two deltaTime values will make it a very small number
well its from the official unity starter third person controller asset :)
:D
same code is working fine for local/host
create a simple movement and experiment with it
they call the exactly same method
networked movement would be no different apart from slight ping delay and smooth lerping to the updated position.
are you processing it twice on client side and server?
well then it makes even less sense. no cant be called twice. its in a if else
// move the player
var moveVector = targetDirection.normalized * (_speed * Time.deltaTime) + new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime;
if (IsServer && IsOwner)
{
PlayerMove(moveVector);
}
else
{
MoveServerRPC(moveVector);
}
Debug, see the values you are using at different steps. Debug what actually executes and by whom
literally same move vectors
You need to actually debug to see that
i did. printing the values all out :D
well whatever. gonna start a new fresh project to check whats wrong
Need to learn to debug. Sample values when they are applied, find anomaly, start debugging up the chain to find where the anomaly. Then you know what to fix.
its not my first ride
just wasnt expecting to get stuck at the basics with some weird ass behaviour
simplify the thing you are testing. Don't use any weird formulas put values manually.
More things you exclude easier will be to find the problem
Sure, I understand what you're asking for. To simplify the testing process, you're requesting that we avoid using any complex formulas and instead input values manually. Is that correct?
Yes
Then if something is being proceeded twice you can easily see from the value, because you know what it should be exactly
could a star topology system where each user transmits their inputs to other users on a p2p server, which is then simulated locally work? how would you stop things getting out of sync without opening a vulnerability where position could be changed for flyhacks etc?
p2p server is not a thing. you either have client authority or server authority
I believe Photon Quantum allows this? The traffic probably goes through a relay server for NAT reasons, but I think the idea is otherwise the same
if I'm using server sided authority with client side prediciton and server reconcilliation, will the host's computer struggle with the calculations?
Hey everyone,
I just stumbled over a design problem for my networking code. See I have NPCs in the game. Those NPCs have daily routines but also can be assigned task by players.
The problem authority here. I want the server to have authority over NPCs movement towards target destinations and other things like collisions and also line of sight calculations.
For this however I kinda need my authoritive server to know the same as the a game client does now.
Currently I am using a standalone gameserver running a websocket connection (and some http endpoints) for client-server communication also movement syncing etc.
For the case of NPCs however I might need something like a headless Unity client. Has something like this ever been done? Maybe is there an asset for that 😕 ?
Every help is highly appreciated!
im assuming that in any networking framework (fishnet,NGO,Fusion....) host/dedicated server modes works the same for player controller and player input.
For both modes the character controller is setup the same
There is a build platform for Dedicated Servers. A new package was just released (in preview)to help with this. https://docs.unity3d.com/Packages/com.unity.dedicated-server@0.5/manual/index.html
So dedicated server is the keyword here
bascially yea. A dedicated server is just a host without a player client
in other words headless? Ok I will take a look. Thanks a heap
This is how it works in NGO
https://docs-multiplayer.unity3d.com/netcode/current/reference/dedicated-server/index.html
Dedicated game servers creates a stable, more enjoyable gaming experience for your players.
anyone know about this?
lets say you have a lobby of 20 players, would a host's computer really be able to keep up with running 20 position scripts and whatever else
It totally depends on your game. But the player's bandwidth will probably cap out before the PC will
okay, thanks.
I think in terms of processing power I should be fine
ill have to look into bandwidth
Hello, I have a question, so I just created a unity multiplayer game with Unity Transport. Is there an easy way to port all the client/server stuff into Photon Network? Or would I have to re-code the entire thing?
If you need more Info, feel free to create a thread and ping me
Yea pure out of the game engine solution is cool until you want to do these kinds of integrations, at which point it's probably more straightforward to reuse the facilities provided by the engine.
If you used NGO there is a Photon Transport that you can use
I don't believe I used NGO. I'll check exactly what I used when I wake up
if a serverRPC function is called and being executed on the server, must all chained functions (functions called from within that serverRPC function) also contain the serverRPC attribute? Or does it work exactly the same if only the first one has it?
Exactly. I try to keep the scope small for the dedicated server solution. At the moment it makes only sense for that NPC movement. However for my combat logic I don't need any unity engines features and there can leave it completely standalone as a classic webserver
anyone know how I can fix this? Assets\Scripts\Networking\Server.cs(211,43): error CS1503: Argument 1: cannot convert from 'Unity.Netcode.NetworkVariable<StatePayload>' to 'StatePayload'
StatePayload is a struct
Only the initial function that is called from the client needs that attribute. Once it's running on the server it's just a normal function.
You need to use the network variable.Value to reference the StatePayload
can I reference a Struct with .value tho?
oh wait
I think after I implemented networkserialize that works now
for some reason when i reload my scene, voice chat using photon just breaks.
I am getting loads of these errors, what do they mean and how do I fix them?
[Netcode] NetworkPrefab hash was not found! In-Scene placed NetworkObject soft synchronization failure for Hash: 68617734!
Hello smart people,
Does someone can spot my logic mistake ? The new joining client have their text be the default "Player" value. But people that were already here have all texts setup correctly :
using Debug;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
namespace Player
{
public class PlayerUsername : NetworkBehaviour
{
[SerializeField] TMP_Text nameField;
// 64 characters max - changes are server authoritative
NetworkVariable<FixedString32Bytes> username = new NetworkVariable<FixedString32Bytes>("Player");
public override void OnNetworkSpawn()
{
if (IsOwner)
SetUsernameServerRpc(PlayerPrefs.GetString("Username"));
}
[ServerRpc]
void SetUsernameServerRpc(string playerUsername)
{
if (playerUsername is "")
{
// Default username
playerUsername = "Player " + OwnerClientId;
}
else
{
// Limiting size to fit on network variable
if (playerUsername.Length > 64)
playerUsername = playerUsername[..64];
}
username.Value = playerUsername;
UpdateNameClientRpc();
}
[ClientRpc]
void UpdateNameClientRpc()
{
// Going through all players and updating their name
foreach (var player in GameObject.FindGameObjectsWithTag("Player"))
{
player.GetComponent<PlayerUsername>().nameField.text = player.GetComponent<PlayerUsername>().username.Value.Value;
}
}
}
}
Thanks in advance
You don't need a clientRPC if you are using Network variables. Also you should use probably String.IsNullorEmpty(playerUsername) insofar just checking for ""
Alright I understand now, thank you !
Anyone know why I get this error:
Your app com.PAWZ.PAWZRunner version code 2 includes SDK com.unity3d.ads:unity-ads or an SDK that one of your libraries depends on, which collects personal or sensitive data that includes but may not be limited to Advertising ID, Android ID identifiers. Persistent device identifiers may not be linked to other personal and sensitive user data or resettable device identifiers as described in the User Data policy.
Trying to use Photon Fusion since it seems more intuitive at its core
I'm looking to have one camera per player. The main camera is not networked, so could I just reposition that camera to each local player?
When I do this:
NetworkManager.SceneManager.LoadScene("Game", LoadSceneMode.Single);
```the clients load the scene after a long delay, with the server already finished when the clients start. I also get this warning
```cs
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 2, but that trigger was not received within within 1 second(s).
```Why and how do I fix it?
the clients load the scene after a long delay, with the server already finished when the clients sta
Just make sure that you only have one camera in the scene. Don't make the camera part of the player prefab
So I can move the local MainCamera around, as long as
A) MainCamera is NOT networked
B) There's no prefab cameras
And all should be swell?
just to double check that i'm right
Or on the right lines, at least
Right, Unity expects there to be only one main camera. Unless you are doing some weird split screen nonsense.
Hey lads, I have a question: if I'm using server side movement with client side prediction, can I let the client update movement every frame, and let the server check every tick? cause, otherwise, I don't really get how you can only update movement every tick on client side
thanks mate :D
That is what client prediction is. You are predicting every frame what the clients are all doing. Then correcting when you get updated server data
are you predicting what all clients are doing or just your own?
all clients. you don't really need to predict your own.
oh, so for each client in the scene, your computer is calculating their position each frame, updating it, and then each tick, the server calculates each clients position and you check if it matches with each client.
but how would you predict a different client's position if you don't know their input?
You can only guess. but most players are not changing inputs multiple times per second
just assume that the player is still doing the last input that you got from them
does each client receive all the other client's input through the server?
depends on your game. you can send whatever you want.
well how else what they know what the "last input" was?
if they were walking forward last frame then you just assume they will keep walking forward for the next frame too. until the server tells you they changed directions
hm okay, so I could just have some prediction script that took their current velocity vector and multiplied it by delta time to calc position, and then upon tick, server updates their movement properly?
that makes sense, thanks so much! I just have one more question on the implementation: to implement this, each player should have a script to calculate their own position each frame (that only the owner of the player can access), each player should also have a script that everyone ( except the client themselves) can access that predicts their movement each frame, and finally, each player should have a script that takes the client's input and sends it to the server to calculate their actual position, and then the server returns that information to all the other clients.
basically yea. I believe its called Dead Reckoning
ah, I mean of course that wouldn't be taking into consideration any acceleration but since the tick is updated pretty frequently i don't think it would matter too much
@sharp axle since not all inputs will be on the exact frame at which a tick is proccessed, should I keep track of "lastInput" or something and then send that the next time a tick is called?
Client prediction
Hello, I’m wondering how to send and receive audio in unity
https://docs-multiplayer.unity3d.com/transport/current/minimal-workflow
Is what I’m looking at
This Transport workflow covers all aspects of the Unity.Networking.Transport package and helps you create a sample project that highlights how to use the com.unity.transport API to:
Currently I think I’ll need to somehow convert an audio clip to a byte array in the sever then somehow parse the byte array upon receiving it from the client side
But I’m not sure how to go about that :/
If you want to do voice chat then Vivox is the recommended Unity service. Otherwise, it would be best to use a library like WebRTC for streaming audio or video
I just want to send an audio clip like an sfx really then move onto something larger.
I accidentally deleted my original player prefab which was working, I remade it and now only the y rotation and animations are synced between both players, both players can move but neither's position is changed on the others screen, the other player stays at spawn, I am very new to networking so I haven't a clue what the problem is
The character controller overrides the transform position
I figured out the problem, I had the animator apply root motion checked
i have an issue with netcode, my ServerRpc runs on the host but not on the client
how do i solve this
(and no, the forum post did not work for me)
Please share code correctly
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
a powerful website for storing and sharing text and code snippets. completely free and open source.
^ the code for above
Server rpcs only run on the server. If you want to invoke an rpc on clients, use ClientRPC
but i want the client to invoke the rpc
as opposed to invoking the rpc on clients
A client to invoke rpc on another client?
no, on the server as the server is authorizing the movement
You want client to invoke an rpc on the server?
essentially, as that is what a ServerRPC is
Because your initial question implied you want to invoke an rpc on another client.
oh no
Ok
what i mean to say is my host can run the ServerRPC with no issue, which allows it to update its movement
but the client is unable to
Are you sure it's not an issue with your logic? How do you confirm that non host is unable to invoke it?
when i run the game, the client doesnt log "loggin" and is unable to move
Why would it? The server rpc should be running on the server regardless of who called it. So the message is gonna be logged there as well.
would the client not be able to see it then?
As for why it's not moving, your logic looks a bit weird. I suggest looking at the netcode manual. Especially their examples.
No. Console log is not synced between clients/server.
is there one on movement?
oh, that makes sense then
I think there was something. And if not, look up some tutorials.
i had looked up many tutorials, but most of them used either ClientNetworkTransform or they had done something similar to mine in terms of movement. ill see if unity has something though
You will need a client network transform or you'll need to dispatch client rpc that move the object on the client.
Server rpc could be sending input from clients to the server, server them processes it and moves the characters. Then the changes need to be synced to the clients somehow. The most straightforward way is a network transform. Otherwise you need to do it manually.
alright, i updated my code and it works now
i just had to make the Update function watch inputs
if I make a static network variable, can I send it from a client class to a different host class?
as long as the network variable is in the scene, it will get replicated
ok, thanks
When joining a game with a client, I load a scene and it should load into the hosts scene but instead it loads its own separate scene, how do I fix this.
Is there any major downsides I should be aware if doing single player as local online? Considering options to avoid separating code into offline/ online. Game is quite straightforward "action" game (resident evil as quick example). Still early in development.
So I am having trouble with moving players with netcode via phyics in a fully authoritative server. It works perfectly for the host, but then the client just strait up doesn't move half as much as it should / velocity is weird. Changing it to move position for the rigidbody "works" how it is supposed to - but then can phase through the terrain with enough movement. This is my last hurrah before I switch to a different engine altogether. Anybody wanna discuss this issue?
it sounds like you need to set up the connection to the server in a different manner. what is your setup for spawning, etc? if you create a new scene via the network manager I would look at that and rethink that part, instead grabbing the scene from the hosts perspective?
I am not creating a new scene, I am just loading the hosts scene on the client, it shouldn't create a new scene and open that coinciding with the hosts scene, it should join the hosts scene.
Anyone here ever used Microsoft Orleans with unity before ?
Physics based movement
How can I update a UI when a player joins? The UI starts in the scene, but a player object only appears when a player joins, so how can I get a reference to the UI in the player without having to search for it during runtime?
You can use events to update the UI
would you be able to give a quick example?
Like for health you can have the UI Manager subscribe to local player's Health.OnValueChanged when the player spawns in.
You you could use just plain old c# events that the player class can fire off
is there an event for when a network object spawns?
how does the ui manager get a reference to the player so it can listen for the events?
You can get the player object from NetworkManager.LocalClient.PlayerObject
I just thought of a way
I want to display list of all players
so I can get the list of connected client ids
and pass them into my id, player map
Hello, i'm trying to learn networking and I'm wondering if my way of thinking is correct.
I'm trying to trigger an RPG ability. My understanding is that this is a non persistent event and so it should be handled by an RPC, from the client to the server.
Is that correct ? and if so How do I inform other client of the ability being triggered ? A RPC Broadcast from the server to all clients ?
That's correct. You can check out how the Boss Room handles abilities
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-actions
Boss Room's actions each use a different pattern for good multiplayer quality. This doc walks you through each of them and goes into details about how we implemented each and what lessons you can learn from each. You can get their implementations here
Got the basics of NGO working for my game - like it much better than UNET so far. Weird issue though. Everything works as expected except the gamepad...? Gamepad works when I have host but no clients, and then as soon as I connect a client , gamepad provides no input. Strangely keyboard input works fine when switching windows, so I don't think it's anything to do with my specific code...
you can see MoveX for example in the InputActions (right side of screen). Both KB and Gamepad drive it, but as soon as the client connects , I lose out on Gamepad input. Any idea what might be going on?
Very strange.... rolling behaves slightly differently. That's using a Button instead of a Value. Same thing, when it's just the host, everything works. But when the client connects ... strangely, ONLY the gamepad works for rolling and Q/E on the keyboard don't work for the CLIENT. And it's the opposite for the server. But MoveX,Y,Z and RotateX,Y still just don't respond to the gamepad at all for either client/server (only keyboard)....so... odd.
I'm using the client network transform...which I guess is not officially supported? I wonder if it's related to how that works? seems odd that it would make a distinction between input types though..
changing it to an authoritative ServerRPC model and using just NetworkTransform I'm getting the same thing , just with way more input lag
So while I may want authoritative input later, I'd need to implement some kind of client side prediction, and that does not seem to be the issue here
Input issues
Hello, I have a player prefab and after updating my project from 2021.?.9f1 to 2021.3.20f1 the player prefab position is being set to 0, 0, 0 when its loaded in by the network manager
Does anyone know how I can get it to use the prefab coords?
Say I spawn a network prefab from the server. How can I pass a reference of the network object which spawned it to the new object on both the client and server?
Without having a singleton
I think what I want is a network object reference?
I'm struggling to find how to actually use that though. I'm currently trying to pass a network id but can't find how to get the object from there @sharp axle
You can just cast it back to NetworkObject
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization#implicit-operators
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
Yep, that should work.
awesome 👍
Is there any reason to implement a acknowledgement & sequencing algorithm for UDP to ensure packet reliability and ordering instead of just using TCP ?
The header will be smaller for sure.
Most networking libraries are already doing that
Does anyone know why this is happening?
It was spawning as i expect for the old version
Are you using Connection Approval to change the spawnpoint?
i dont remember adding a connection approval thing
but idk if thats something you have to add
maybe looking for something that would change between versions
but not super major versions? i think? im not entirely sure on Unity's version numbering system
Yes, by default it will spawn players at the origin. You can use Connection Approval to change that
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval#server-side-connection-approval-example
With every new connection, Netcode for GameObjects (Netcode) performs a handshake in addition to handshakes done by the transport. This ensures the NetworkConfig on the client matches the server's NetworkConfig. You can enable ConnectionApproval in the NetworkManager or via code by setting NetworkManager.NetworkConfig.ConnectionApproval to true.
tf? then what was i doing to get it working on the old version?
and why did it change on new version
No clue. You can spawn players manually using Network object's SpawnAsPlayerObject()
how to deallocate server from multiplay?
I'm having issues implementing a multiplayer concept. I have a prefab asset that I bought that already has configured the movement, animation, design and sound. I created a scene where I can start a Host and a Client, which will spawn the prefab and allow each to control theirs.
My issue is that even though I can start the host and the client, and have both spawn their characters, only the host is able to move. The client, when trying to move, tries to move the host's character. Can anyone please help?
You'll need to rewrite the movement and/or the input code. Unless its just art, very few assets can just get dropped into multiplayer like that.
I see. I can edit the script of the input code, but I'm not sure what to change. What is the approach here?
Depends on how you have the game set up. Is it server authoritative or client authoritative? You'll need to make sure that only the local player is accepting input. usually that means just disabling the player input scripts for remote players.
@sharp axle It's client authoritative
hi anyone knows how to teleport clients(players) to position in multiplayer game?
https://www.youtube.com/watch?v=3yuBOB3VrCk
Try following along with something like this and by the end of the hour you will understand more than just this single question
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubref=ngo
FREE Third Person...
I still dont know
You can just have the server move the player transform. If you are using Network Transform then it will sync to all the clients
Ok
How should I go about calling a function only once when a client connects to the server? OnNetworkSpawn() is called every time a client connects, and I'd only need to run a function once
Also, is there a component that can handle client side prediction and reconciliation, or do I have to write that myself from scratch? (I'm using Unity's Netcode for Gameobjects)
I would make a bool that you can set the first time a client connects. You could also just unsubscribe the function from Onclientconnected when the function runs.
[Unity NGO]
I'm making a game with drop in/drop out multiplayer, and I'm not sure how to handle scene management.
Ex. A host player has been in the game for a bit and is currently in the "Dungeon" scene. Another player joins and is placed in the "Town" scene. The two players can stay in different scenes and do their own thing, or they can join one another in the same scene where it should then sync up.
How do I accomplish this in regard to scene management? I asked ChatGPT and it said I needed to have all scenes loaded on all clients + server so they can stay synced, but I feel like that would hurt performance and scalability and stuff? Been scratching my head on this for a bit now so help is very very much appreciated
NGO is not really built for that. You need something managing player locations outside of the game. That could be cloud code and the lobby system. Have each area host a lobby. Cloud code can keep track of who is in which lobby. When a player crosses into a new area cloud code can be used to connect the player to that areas server. I have no idea how feasible that actually is.
adding a ClientNetworkTransform to a dynamically spawned object during runtime: how??
tried adding it from the serverrpc before or after spawn(), no sync
tried adding it on all clients in the clientrpc, no sync
tried adding it on only the client with ownership, no sync
After you add the Client Network Transform, you probably have to reregister the prefab with the networkmanager on all the clients as well.
should that be done in the serverrpc? keep in mind that then only the server has the object with a clientnetworktransform
and how would you reregister the networkobject?
they all have to have the clientnetworktransform or they can not sync
i currently add the CNT in the clientrpc so all clients have it added. I think this causes the sync issue
The main component of the library
Hi everyone! New to the server so if this is not the appropriate place to ask I apologize! I am working on my first larger project and I am hoping to make it as server authoritative as possible. I have been doing hours and hours of research on what infrastructure backend I should lean into and I still can't figure it out. I am deciding between AWS, Firebase, and Azure(PlayFab). I am not running multiplayer, I am looking to do cloud saving, auth, and in app purchase validation stuff. Anyone have any preferences? I come from a traditional dev job and have used AWS for years but I am finding their gaming SDKs are meh. I haven't checked out Unity Services as much as I am worried a bit about the cost if things happen to scale and the maturity of the platform thus far but happy to check it out
this would have to be done before you spawn the prefab
so like an rpc in the middle?
this is not possible as you need a NetworkObjectReference, which can't be referenced before the object has spawned 🤯
I like Playfab. But I'm all in on the Unity Services. The main difference is mainly price
I have lots of loose strings but can't seem to tie them together
Yea. you're not really meant to be adding those components at runtime
How much of a price difference is it? From what I have been reading UGS would be a bit more expensive
i could technically add the CNT to the prefabs, but does that cause a lot of traffic if there's many prefabs spawned? I only need the movement to sync when the player is selecting a position for the prefab to be spawned at
I haven't run the numbers. It really depends on how much and which services you end up using. Its entirely possible you never break out of the free tiers of most of the services
I guess I could add the CNT to the prefabs and remove the CNT component once the object has been spawned. What do you reckon, will this work?
that would be way easier. just disable the component
perfect, thanks!
How would I call NetworkManager.Singleton.Shutdown() and wait for it to complete/get a callback when it's done?
Hello, I need some advice making a pickup system using the new Netcode system.
I have done it before using Photon but I am currently in the process of changing over.
I have a XR scene with 2 clients their hands and head locations are synched over the network no problem.
One of them picks up a item, the item on the side of the guy that picks it up follows its normal XR behaviour and follows his hand.
What I want to do is disable the network object on the item and on the side of the player that did not pickup the item make the item a child of the other players hand.
But I tried this and I get the message that only the server can reparent network objects. I currently only stop the NetworkTransform on the object.
Is there a way to quickly disable and enable networked objects?
I know my solutions sounds quite complicated but I like the idea of players not having to synch the items they are holding but only their hands.
Or is there a better solution?
I'm pretty new to Unity Networking so just an idea.
Shutdown is a void so no return from there.
Maybe you should call the function and then after that check the current connection state?
Wait until you are disconnected?
I don't think you're supposed to enable/disable the objects ever. The NGO docs has a whole page on the proper way to handle network object parenting though, hopefully it helps: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/index.html
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
Oeh thanks I will take a look. 👀
No problem. I think Code Monkey has a free (Unity NGO) multiplayer course that also handles network object parenting a little bit. If the docs don't help maybe you can download those project files and watch the relevant segments of the tutorial
I think I can check to see if the NetworkManager.isListening, but I wondering if there was something more "built in" than checking that in a coroutine loop. I guess I'll just try that for now, thank you :)
check out the Client Driven bitesize sample. it has an example it reparenting a pickup item
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven#client-side-object-detection-for-pickup-with-server-side-pickup-validation
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
There is an OnClientDisconnectCallback
https://docs-multiplayer.unity3d.com/netcode/current/components/networkmanager#client-disconnection-notifications
The NetworkManager is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
thank you
Hey, I want to transform a big FSM to work with Photon Fusion. (am using an Enemy AI unity asset that is working on Single Player only). It has many states and uses Scriptable Objects for state management. Can you give me any advice what should I do to make this happen? What is the way to convert it into Photon fusion, how to plan architecture, any tips? If no, is there any good asset that I could use for Enemy AI that uses Photon fusion?
Using Netcode for GameObjects I was setting the CanCommitToTransform = IsOwner on ownership transfer between server/clients to be able to move a gameobject. Now that I upgraded the related Netcode for GameObjects packages I can't do this because the CanCommitToTransform is declared as protected. What can I do about this ?
Any suggestions would be helpful.
Sounds like you should be using Client Network Transform
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform#clientnetworktransform
The position, rotation, and scale of a NetworkObject is normally only synchronized once (when that object spawns). To synchronize position, rotation, and scale at real-time during the game, you must use a NetworkTransform component. NetworkTransform synchronizes the transform from server object to the clients.
@sharp axle Hmmm, is the CanCommitToTransform supposed to be set automatically on ownership change ?
If you look in the NetworkTransform class, I believe this is the case.
interesting cause in my case it didn't, maybe because I'm on an older version.
[ServerRpc(RequireOwnership = false)] private void ChangeOwnershipOnServerRPC(ServerRpcParams rpcParams = default) { // Change ownership of this object to the calling client selectedNetworkObject.ChangeOwnership(rpcParams.Receive.SenderClientId); // Deselect item on ownership loss ClearGizmoTargetsClientRpc(); // Sync the correct transform data to all clients if(IsServer) { SyncGameObjectTransformClientRpc(transform.localPosition, transform.localRotation, transform.localScale); } }
I change the ownership like this and the CanCommiToTrasnform doesn't change automatically, will upgrade the packages and check again
hi huys,is there somebody that can help me with a multiplayer game i am creating?
i need somebody to test the game with me on oculus
@sharp axle wait, aren't WebGL Builds supported in Netcode for Gameobjects ?
WebGL (requires NGO 1.2.0+ and UTP 2.0.0+). Note: Although NGO 1.2.0 introduces WebGL support, there's a bug in NGO 1.2.0 that impacts WebGL compatibility
https://docs-multiplayer.unity3d.com/netcode/current/installation/install
How to install Unity Netcode for GameObjects (NGO).
hi guys i have a problem where i have a network lists that contain structs and i need to find if the two lists contain a struct with the same property name is there a way to do this more efficiently than to use several for loops? With normal list i can use .FirstOrDefault() but network lists dont have the same function
Im using netcode for gameobjects
hello, can someone please eplain what this error means: OverflowException: Writing past the end of the buffer
im using an rpc to send a byte array from one client to another for context
You can achieve it with NGO, but you'll have to first disable scene management from the NetworkManager and handle it yourself. You'd also need something on your NetworkObjects to ignore any gameplay calls that occur in a scene the client does not have loaded. In addition you need a synchronization method for each of the components to sync up when a client goes into that scene setup.
It'll be some real work though yourself
Thank you for the detailed response. I’m attempting this right now, and I figured for the synchronization it might be useful to make a SyncNetworkObject that extends NO and has a ‘Syncronize’ function than all child classes have to override, and use that instead of NO for most networked things?
as far as ignoring gameplay calls it seems like I could tag each player with a list of scenes they’re currently using and if !using that scene then ignore rpc’s and all that.
Do you think that’d work/forsee any issues with that method 🤔
i imagine there will be more to it than that, I just mean as a baseline approach/setup for the task at hand
Fairly sure it'll work, i use something like that in a live production game already, though not for your usecase but midgame reconnects
Yeah it'll be more work than implied by the simple setup for sure 😄
But it'll work too
awesome, thank you so much
I’m still trying to wrap my head around how the client would be able to exist in a scene that the server isn’t running?
As a practical dev tip, design the system in a prototype scene that has a single setup of all the features you need. Don't try to integrate it into an in production game before you've fully designed it or else you'll paint yourself in a corner by workarounds you make for existing code before the design is final
yeah definitely
it makes sense that the host would be able to be in any scene they want, because they are the server and there will always be an rpc reciever, but for a client I’m realizing that’s not the case
If the game is intended to be designed as server authoritative, the server will need to run the scene aswell. The clients simply react to different scenes
Gotcha, I see
my game is most likely going to be P2P so, i guess I will just need to load all scenes on the host either way
If you're running as Host and not a server it'll be another complication as IsServer / IsHost can be confusing at times
If the game isn't competitive and you're not worried about cheaters, you could avoid full simulation
You could simply have a class for each situation that keeps track of the things that occur in that scene setup, ie abstract the scene away entirely from the network side of things
that’s an interesting idea
It’ll be co-op, similar in multiplayer-structure to Diablo 3
But that's feasible only if you trust the Client (which you almost never want to do if there's any competitive elements or chance of the game becoming really popular)
Yeah I intentionally decided to make a game where idc if someone cheats because that’s😅 thats a handful
thank you, i think i have a good idea of what i need to do now
Just remember that the architecture won't be a good fit if you next decide to make a competitive FPS game with scoreboards 😄 (most devs take strong influence from their previous projects and all)
If the host subscribes to OnSceneEvent, do they get events as both the server and client? It's being called twice for them
They should yes if memory at all serves correctly
No given way around this? I just have to boolean my way out?
You could subscribe only when executing as the server to the event, then react to the event with a ClientRpc
But since you're reacting to an OnSceneEvent i presume you want the clients to individually react to it so it might not be a good fit there though.
Yeah it's tricky. I was hoping to span this section out for later and do it quickly now, so I guess I'll just patch it for now and think about setup later down the line. Thanks though, I was just wondering if this was normal
Hi so im having a slight problem with matchplay. Where if no server are startup daily they get deleted. Then when im in my game and try to find a match (or start a test allocation) it starts the all the server that it can
Howdy folks! Is there a way to make it so the NetworkManager doesn't reset the player object's position when instantiating it? I have scripts set up to set the player's position depending on which slot is open, but it seems to be moving the player to 0, 0 after OnEnabled completes as that is where the transform is changed
Move that code to OnNetworkSpawn() or you could use connection approval to change the player spawn point
Is it actually starting multiple servers? If you have minimum available servers set to 0 then it will take extra time for matchmaker to find a match as the server spins up. So the matchmaking timeout would need to be increased in that case
@sharp axle it's start it all well and fine but it doesn't start only one. One get allocated correctly and if I set the max number of server to 2. Then the second one goes to online state and tries to start
BUT because it's not started through matchmaker it can't get some info and give me an error and (I need to implement a check somewhere in the code for this to stop running if it doesn't have the info) and it just stays online stat until I stop it manualy
Hey there folks! I'm still clueless about how all this multiplayer stuff works but I'm doing my best. However, this script (which I have been doing my best to understand from the unity docs) is giving me the error:
MultiplayerManager.SubmitNewPosition () (at Assets/Multiplayer/MultiplayerManager.cs:39)
MultiplayerManager.Update () (at Assets/Multiplayer/MultiplayerManager.cs:27)```
Does anyone know what I am doing wrong here? Thanks!
Scripts used for multiplayer:
https://hatebin.com/mbskevnpzd
https://hatebin.com/keohnlgmdb
Hi how i can make one camera with tracking for player
Im using netcode for gameobjects and I'm trying to find a good way to sync players together with the network transform component. But the interpolation looks weird and turning it off will make the movements choppy. Is there a good way to handle this?
I'm pretty sure only the server has access to SpawnManager.
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject#finding-playerobjects
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:
Check out how the Client Driven Sample does it
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/d37c360bc8cdbbbf680e2afc5963571e20f28ffd/Basic/ClientDriven/Assets/Scripts/ClientPlayerMove.cs
You either have to write your own interpolation or write your own client prediction system
https://www.youtube.com/watch?v=TFLD9HWOc2k
Welcome to this Unity Tutorial where we go over Determinism, Fixed Tick Rate, Client Prediction, and Server Reconciliation. Deterministic Programs and Fixed Tick Rate are more theory but really important to understand in order to implement Client Prediction & Server Reconciliation. I then go into how to code Client Prediction & Server Reconcilia...
Figured I would have to do client prediction. Thanks for the reply!
the starter asset deletes a burst and i have many errors
this is strange
I only have 1 client connected (the host)
It says the owner is client 0, if only the host is connected they must be client 0, so why is IsOwner false?
I just checked and it's also not owned by the server...
huh. It's true if I check during Start rather than Awake
yep. awake is called before its on the network. its better to stick those checks in OnNetworkSpawn
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior#spawning
Both the NetworkObject and NetworkBehaviour components require the use of specialized structures to be serialized and used with RPCs and NetworkVariables:
pls help starter assets deletes burst and makes errors
You're gonna have to be more specific. What does burst have to do with anything and what are the errors you are seeing?
idk i need to see
i reinstalled
i used this
Is there anyway I can find out which network prefab it's talking about and where this error actually comes from...?
well I found what it was but not thanks to the error message. Talk about unhelpful
Make sure you are on the correct version of unity. And that the packages are the right version
Hey so Im trying to make a multiplayer game using photon pun and im trying to send a message to all the players telling them that the round ended. I looked it up and there is such thing called RPC which is nice but when I try to use it it does it for every object that has a photon view component attached. Is there a way to make it target certain objects because a few of non player objects have the photon view componet. Basically I want to send a photon pun RPC to certain scripts with the PhotonVeiw Component. Is there a way to do this? I hope that makes sense.
I don't use photon, but there is a way to specify the targets of RPCs. Might try asking in photon's own discord
You might want to use more client oriented (rather than individual photon view) network messages over RPCs for something like this. If those photon views are not client controlled, you might be able to check authority when you receive the RPC to only execute it on the player object.
"I'm implementing lag compensation for my game using Photon, but I'm having issues with the smoothness of the player movement. I've included the relevant code, but it doesn't seem to be working as well as I'd like. Can anyone suggest improvements or alternative solutions to achieve smoother player movement with lag compensation?" code = https://gdl.space/bidominoma.cs
scroll up a bit. I posted a short vid on client prediction that should guide you in the right direction
This one ?
.
yep
Thank you 😁
Can the client prediction you gave me to be modified with photons, right?
No reason why not
https://pastebin.com/ewnSUuvU
Hello, I need to make that all players were teleported to one place
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You can loop through all the connected clients then set to their player object transform to wherever
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject#finding-playerobjects
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:
To every network object?
Hey Unity Pro's, I wanted to ask if anyone here can judge NGO technically in the context of small scale competitive fps games
Since i would love to support Unity / stay as native as possible within the ecosystem I thought I might just ask before looking into things like Photon's fusion product
no tick system, no lag compensation, no csp, etc.
obv im biased but
😉 I was not aware that NGO did not have a tick system - edit - no client side prediction? well then its out haha
I already followed the 100 series which worked out well
I mean each to their own, but as far as I am aware NGO doesn't have a single advanced feature out of the ones needed for something like a competitive FPS
I understand* 😉
Fusion seems to be seen as the benchmark (based on research) which would make it a safe bet - The only thing unclear to me with it is its dedicated server (hosting) pricing
We don't do any dedicated server hosting, that's up to you. Our pricing is always CCU based.
You can ofc run dedicated servers with fusion, but how you do that and where is up to you
then I completely misunderstood the docs - my bad!
Hey,
I try to create a multiplayer game with a matchmaking system, but I don't know where to look. Because I search a system like APEX Legends or others where you click on a search button and the game create a server if anyone is available or connect the player to the server ( A server on demand system). And can be show on steam.
Some people tell me to use Netcode for gameobjects with Unity lobby and others stuffs, and I see mirror too ... I don't know if they things can do what I want to do.
Do u have a tutorial on Youtube or can u help me to search on the right way ?
Thanks
just FYI, there is actually a Tick system. There is indeed no client prediction but there is no reason you can't implement your own.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networktime-ticks#network-ticks
LocalTime and ServerTime
This is the matchmaker
https://docs.unity.com/matchmaker/en/manual/use-the-matchmaker
but you also have to set up a dedicated server hosting
https://docs.unity.com/game-server-hosting
Thank you so much, after adding a simple check it seems to be working! Sorry for the ping a while after you responded, I had just taken part of yesterday off from development and didn't see your response until now.
is there a way to put my custom enum List as argument in PhotonView.RPC using pun2?
I'm at this point and still I get "Unity Transport is not currently supported in WebGL. NetworkDriver will likely not work as intended." What am I missing ?
You need to install Transport 2.0. you'll have to install it by name and specify the 2.0 version
@sharp axle hmm can't find anything over 1.3.1
oh wait seems I'm on the wrong(Unity 2020 version)
How to use HostMigration with Mirror and Relay and Lobby?
And how to fix the "player timedout of inactivity"
Hi guys I am working in Unity 2021.3.41f and for networking I am using Photon PUN 2. I am trying to do the button. This button function is adding value for player who click on it. All players can click and get value from this button only once. So when for example player 1 click on this button it will add value to this player and when he click again nothing happens. Now I have problem that all players can click but after click it only change value for the first player not for player who clicked on button. Can you please help me? What can I do different? Here is my code:
[PunRPC]
public void OnFourPointsButtonRPC(int index)
{
if (!view.IsMine) { return; }
if (PhotonNetwork.LocalPlayer.ActorNumber == 1)
{
if (Context.newGameManager.players[0].selected_string == null)
{
Context.newGameManager.players[0].CallSetSelectedString(button4b_value[index]);
Debug.LogError($"Player {PhotonNetwork.LocalPlayer.ActorNumber} select value: {Context.newGameManager.players[0].selected_string}");
}
}
else if (PhotonNetwork.LocalPlayer.ActorNumber == 2)
{
if (Context.newGameManager.players[1].selected_string == null)
{
Context.newGameManager.players[1].CallSetSelectedString(button4b_value[index]);
Debug.LogError($"Player {PhotonNetwork.LocalPlayer.ActorNumber} select value: {Context.newGameManager.players[1].selected_string}");
}
}
// pointsAmountToAddForPlayer = 6;
}```
EDIT: Button function is RPC and adding value to each player is too RPC: `Context.newGameManager.players[1].CallSetSelectedString(button4b_value[index])`
I am in the development of a 2d top down environment. I am using netcode for multiplayer, which will only be for a few people. I have setup a network manager and added my prefab as a network prefab. My prefab has a network object component attached to it.
I have setup buttons, so that when I build and run the game I can choose between a server, host and client. I have the host on the main environment and the client on the new window that pops up.
My issue is that when my object spawns on the server side, it does not spawn on the client side as well.
My code looks like this.
Can someone help me?
Are you getting any console errors? Your code there is fine. Make sure you have the prefabs added to the network manager prefab list.
The prefab is added to the network manager prefab list.
On the host side I don't get any errors. The object spawns fine and I can move it freely.
On the client side I get this error:
NotServerException: Only server can spawn NetworkObjects
Unity.Netcode.NetworkObject.SpawnInternal (System.Boolean destroyWithScene, System.UInt64 ownerClientId, System.Boolean playerObject) (at Library/PackageCache/com.unity.netcode.gameobjects@1.2.0/Runtime/Core/NetworkObject.cs:475)
PlayerSpawn.Update () (at Assets/Scripts/PlayerSpawn.cs:15)
That means you are not calling Spawn on the Server/Host. You'll need to send a serverRPC if you want to call that from a client.
How can I add a serverRpc if you don't mind me asking? Sorry I'm kind of a beginner.
You can read up on it here
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/messaging-system
An introduction to the messaging system in Unity MLAPI, including RPC's and Custom Messages.
Okay thanks a lot!
Hi, "IsServer" is true even on the mirrors of the other players on the host right?+
Hello, I've been trying to create and spawn a network object for several days. The problem is that (in this case) the text (as a child of the banner) does not sync when I use NetworkObject.Spawn() it with the Clients PS i am Using Unity Netcode and Unity 22.1.23f1
Here is My Code thanks for your help
[ServerRpc(RequireOwnership = false)]
public void NameBannerServerRpc(ServerRpcParams serverRpcParams)
{
GameObject can = Instantiate(canvas, new Vector3(0, 0, 0), Quaternion.identity);
can.GetComponent<NetworkObject>().Spawn();
GameObject BannerGO = Instantiate(Banner, new Vector3(100, NetworkManager.Singleton.ConnectedClients.Count * 100, 0), Quaternion.identity);
BannerGO.transform.GetChild(0).gameObject.GetComponent<Text>().text = namee.Value.ToString();
//BannerGO.name = "Test";
//Debug.Log("Sender client id : " + serverRpcParams.Receive.SenderClientId);
BannerGO.GetComponent<NetworkObject>().Spawn();
BannerGO.transform.parent = can.transform;
}
That's right. OwnerID will still be that player's Id though
UI should not be networked like that. Keep all the UI local to the client. You can have a UI manager that updates your UI by singleton or events
Thanks, just checked with a serializeField bool 😄 good to know about the id though
Okay but how should i instantiate all the "Banners" if a Client is joining late and how can i get the name all connected Players? Like i know i can get the IDs but i need the string which is given to each Player Individual
You can have the players save it to a list when they spawn in. Then your UI manager can just loop through that list and instantiate your banners
hi! id like to simulate battles serverside in my game and have clients render the simulation. whats the suggested approach for this?
i figure networkbehaviours are out of the question, so what should i use to update the units and projectile positions?
I am learning mirror in hope to get a advantage in job and make some multiplayer games
or should I learn photon ?
ping me
Omg Thank you so much! I dont know why i diddn't get that idea!
I'm having issues with NGO NetworkObjectReference's not working, ie when i use TryGet on them it always returns false, i'm wondering if theres some undocumented feature that says only the server can build valid NetworkObjectReferences or what is going on?
Error : https://gdl.space/ibufamanid.cs code:https://gdl.space/hujipapore.cs What could be the possible reasons for the error "RPC method 'SetChildActive()' not found on object with PhotonView 3. Implement as non-static. Apply [PunRPC]. Components on children are not found. Return type must be void or IEnumerator (if you enable RunRpcCoroutines). RPCs are a one-way message." while using Photon Unity Networking (PUN)? How can this error be resolved?
i have a vr game Using XR Interaction Toolkit and Mirror Networking in Unity. But my players have shared input when they join.
for context: I host the server on a laptop. And when player one joins i can see them move on the laptop but when player 2 joins player 1 and 2's movement are shared and the same.
so player one can see player 2 do the exact same thing and player 2 can see player 1 do the exact same thing. (they copy each other)
That means that you're doing something sus in your movement controller.
It means that the method is missing on the object with the target photonView
Find PhotonView with Id 3 and see what components it has.
You have to make sure that the network object is already spawned in the scene
You should disable the player input on the remote players when they spawn in. I don't have the XR rig as part of the player prefab at all. Leave the rig local and then have the local player avatar find and follow the rigs head and hands
so you are saying that only the local player should get a rig? am i correct?
That's the way I do it. 2 rigs in a scene is a hassle of disabling components
wont that prevent the other player object from moving?
will it also be okay if i do it like this?
[SerializeField] private OVRCameraRig cameraRig;
void Start()
{
if (isLocalPlayer)
{
cameraRig.enabled = true;
}
else if (!isLocalPlayer)
{
cameraRig.enabled = false;
}
}```
You also will need to disable all the other OVR components like controller tracking
If those are all under the camera rig then it should be fine
i dont know what component does controller tracking (im still new to this)
You'd need to do it in OnNetworkSpawn
is that in the Network Manager?
It's part of network behavior
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior#spawning
Both the NetworkObject and NetworkBehaviour components require the use of specialized structures to be serialized and used with RPCs and NetworkVariables:
i am having trouble implementing your solution
ty so muchhhh omgggg
I figured this one out a moment ago aswell, i moved the place i set it to a ServerRpc that is called right after the object is spawned to ensure the correct order. Thanks for confirming it though!
What is the intended way to Synchronize a NetworkList when a client joins a server?
If i have a client that joins the server the client does not get the pre-existing values in the list from the server side. I can't write to the NetworkList during OnSynchronize either apparently, due to it being Server authoritative (and it's desired that it remain so)
Its supposed to be synced just like a network variable
It isn't in my case, there is the correct amount of elements in the NetworkList and the values are correct on the server, but they are default values on the client
Hello, Does anyone Knows how i can create a Network List with my own Datatype? I wrote this c# script bot it does not work
thank you for your help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using Random = UnityEngine.Random;
using System.IO;
public class UIManager : NetworkBehaviour
{
NetworkList<playerData> Players = new NetworkList<playerData>();
}
public class playerData : IComparable<playerData>
{
public string playername;
public int level;
public int id;
public playerData(string newName, int newLevel, int newId)
{
playername = newName;
level = newLevel;
id = newId;
}
public int CompareTo(playerData other)
{
if (other == null)
{
return 1;
}
return id - other.id;
}
}
explain what "does not work" means, also try adding [Serializable] to the playerData class
It needs to be a struct that implements INetworkSerializable and IEquatable. None of the fields can be of a nullable type.
Does this chat answer Photon related questions?
A few folks here use photon. It's not my area though
My question might be a more general kind of thing
Still related to networking though
So I'll shoot my shot
I have this script related to camera assignment
I'm trying to set the camera follow only if the found object has the "IsMine" property
But it doesn't seem to work
and the camera gets assigned to whatever player is first in the scene
hello! im having in issue with joining a game with my photon lobbies. I connect but it is not creating the the scene in the code. Im not getting any errors. im following this vidhttps://www.youtube.com/watch?v=mhfMOpsaHkU&list=PL6PsTmPNvw0eZirNDjO8dL0Y6X0ZFGaMt&index=14
but I applied my launcher script to a empty called launcher in Menu scene and i have set the build settings correctly. above are all the screenshots
In this tutorial Welton shows us how to get the framework for our Photon PUN matchmaking system started bro, you can't miss it...
(JOIN OUR DISCORD FOR A DOPE COMMUNITY, INFO, AND HELP: https://discord.gg/vrErfxa)
(CATCH UP ON OUR GITHUB: https://github.com/Kawaiisun/SimpleHostile)
Over the course of the next couple weeks, Welton will be teachi...
Please @ me if you are available to help. In class and won't notice otherwise. Thank you
I connect but it is not creating the the scene in the code.
Why would you expect it to create a scene for you? Where in your code do you do that? Scenes != photon rooms
the create level code?
or load level.
but you're not calling that?
and one referring to the 1 in build settings?
great, you're still not calling it
Im sorry I dont know what im doing wrong. im very new to this. Can you explain more in detail?
call StartGame in OnJoinedRoom
am i missing it somewherer else?
Multiplayer networking is not a beginner subject. If you require solution dictation for every error you come across, you're going to have a rough time.
You said you're joining a room, but you're not actually are you?
where you calling Join?
I called Join in the wrong area
thank you man so much for the help
and for being patient with me 😅 a
much love
ok, see you in five minutes
Hey, I started my game already and have some basic movement stuff done, is there some "easy" way to make it multiplayer? Or should I just start a new Project and reimplement everything with Multiplayer from the beginning?
yes
If you aren't too far along then you won't have as much to redo but you probably are gonna have rewrite a bunch to work well with networking
Well, how would I make it multiplayer?
I think I found a nice Video explaining it to me :D
Anyone knows why IsLocalPlayer always return false on a NetworkBehaviour? it does have the networkObject component
Make sure you are checking it OnNetworkSpawn() or after
bro why are you like this
like im sorry im slower and im trying to get better
like bro just shut the fuck up if your gonna be rude
i am a beginner
but everytime i have an issue hes like that
always shamming me one way or another
like bruh just dont say anything then
its not hard
bro yesterday when i needed help with a coding piece he was still doing the bs
i know that
and i said i found the solution in a stack overflow
but he still makes those comments
no but he did the same thing yesterday
when it was an error
i know and im learning and do not know how to debug etc
alr ill try and set away
is youtube vids a bad way to go?
yes
got it. thank you.
is learning unity and c# different?
also should i start with 2d?
instead of 3d?
what happened?
oh geez
is this a good vid? https://www.youtube.com/watch?v=7glCsF9fv3s
💬 Here is the Multiplayer Course! I really hope both of these FREE courses help you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Project Files, FAQ https://cmonkey.co/freemultiplayercourse
🎮 Play the game on Steam! https://cmonkey.co/kitchenchaosmultiplayer
❤ IF you can afford it you can get the paid ad-free ...
yeab
this is 6 hours
and its not anything specific i dont think
this one actually
💬 This was a ton of work to make so I really hope it helps you in your game dev journey! Hit the Like button!
🌍 Course Website with Downloadable Assets, FAQ, Related Videos https://cmonkey.co/freecourse
🎮 Play the game on Steam! https://cmonkey.co/kitchenchaos
❤ IF you can afford it you can get the paid ad-free version https://cmonkey.co/kitchen...
yeah alr thanks man
sorry for earlier
one seperate question
like is learning unity and learning c# completely different?
ik
but like in this vid will there be c#
ok perfect
ok so i dont have to go watch a 10 hour c# course right
ah
alr ill check it out.
thank you
oh lmao
isnt that the one where u connect things
together
nodes
yeah ive used those before with blender
nah
lmao
alr so ill start with that
vid
thank you man
Hey, I'm currently watching a Video by Codey Monkey on multiplayer and he mentions here: https://youtu.be/3yuBOB3VrCk?t=1975 that custom NetworkVariables dont support string, but it works for me? Has that been changed?
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubre...
the vid is prob older and the software is updated.
thats my guess
The video is 5 months old... and I guess that's it... but I can't find anything mentioning that it's now supported
Oh then I don’t know. Sorry!
@weak plinth I was trying to help you. Learning the basics before trying to do the advanced stuff will help you do what youre trying to do. Coming in here asking to be spoonfed the answer without being able to internalize how anything works is not sustainable.
To which video are you referring?
The codemonkey one with the title netcode for gameobjects
That one? That is from me... for my Question...
And I'm not using PUN
I didnt say you were
Ah ok
Ah, I see, I misread.
Thought so .-.
strings work at runtime too? Not just a thing where it compiles, but doesn't actually get sent?
because I can just slap a GameObject in there and it compiles, but I don't think there's any way that it's getting synced over the network
I'm pretty sure it works
But I guess I'll see that once I actually need to use it... for now I'm trying to "hide" the latency.. I know the theory of moving it on the client and then sending the Position to the Server to check if it's valid, but I don't really know how I would do that
when I create a room in PUN 2 it dosen't work. I have a funtion to create a room whenever a button is pressed
public void CreateRoom(){
if(string.IsNullOrEmpty(roomNameInputField.text)){
return;
}
PhotonNetwork.CreateRoom(roomNameInputField.text);
Debug.Log("Created room");
MenuManager.Instance.OpenMenu("loading");
}
Then theres the join room function:
public void JoinRoom()
{
string roomName = locateRoomInputField.text;
foreach (RoomInfo room in availableRooms)
{
if (room.Name == roomName)
{
PhotonNetwork.JoinRoom(roomName);
return;
}
}
Debug.Log("Room join failed");
}
Sometimes when I press the create room button and create the room I can't join it from the input field and I don't know why. I had a room list system before that I deleted to fix this and when it wasn't showing up ther either. and a debug.log in OnRoomListUpdate showed the created room not being detected
CreateRoom also joins the room it creates, so you dont need to do that in addition
Also you need to set the RoomOptions to isVisible for it to show up in room list
Im trying to spawn a networkobject as a child of another object, namely the hand object for my player, so i can make my player hold items over the network, for some reason, the object REFUSES to become a child of the hand object
Im using TrySetParent
and it just returns false
What could be affecting this?
if (data.item_type.is_holdable)
{
GameObject item_holding = Instantiate(data.item_type.item_prefab, item_hand);
held_item = item_holding.GetComponent<ItemState>();
// Make sure to instantiate the object on the other clients.
NetworkObject item_NO = item_holding.GetComponent<NetworkObject>();
NetworkObject item_hand_NO = item_hand.gameObject.GetComponent<NetworkObject>();
item_NO.Spawn(true);
Debug.Log(item_NO.TrySetParent(item_hand_NO));
}
ok nvm i was just told by the editor when i attempted to manually set the parent
SpawnStateException: NetworkObject can only be reparented under another spawned NetworkObject
so how can i tell netcode to stop doing that because thats dumb? 🙂
the hand object is part of my player prefab
and why doesnt it tell you these errors when you try to run the code?
Also it says network objects as children of other network objects is not supported unless its scene objects
so how would i go about spawning an item that my player is holding, in a way that it looks correct to other players AND to the player holding the item?
I'm developing a multiplayer game in Unity using Photon for networking. The game features a green cube that players can stack on top of each other, but I'm encountering issues with getting the stack to sync between players. Specifically, when one player stacks the cubes, the other player sees the cubes stack in a different position or not stack at all. Additionally, there are instances where the green cubes stack on top of each other even when there isn't enough space, creating gaps between the cubes.
I've tried using PhotonView to sync the position of the cubes, but I'm not getting the desired result. I've also noticed that the issue is partly caused by an if statement that incorrectly positions the cube when it is stacked on top of another cube.
Can anyone suggest ways to fix the synchronization issue with the green cube stack and make it work correctly between players? I would appreciate any insights or suggestions on how to address this problem. video =https://streamable.com/oipax1 script=https://gdl.space/uvogafetuj.cs
Hello, I am trying to create my own Networklist which is updated to all Clients but i get this error. I am very new to Netcode. Thank you for your help
bump, thanls for the help if you take a look
Use this link https://gdl.space/ to post your code, Please #854851968446365696
Oh Okay sorry
You need to read through this
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
Okok i skimmed this yesterday
I'm new to Networking for GameObjects, but i've watched videos and read documentation and also played around a bit with it. I got a question though that i can't seem to find the best answer to.
Let's say i have a game - for simplicity - with a Host and a client. I want to make it server authorative but at the same time with client prediction. I want the server to be the single source of truth but at the same time give the client instant feedback.
Let's say the client moves. I want the client to check if the move is allowed and if it is - move instantly - at the same time i want the server to check the move and then if the move was indeed valid, also move.
If i make the client object server authorative, i won't be able to instantly move it because the client can't move it. If i make the object client authorative - a compromised client can just set the location at will and never tell the server that it needs validation?
So what is the best approach here - to have the server actually be in 100% control of the state, but allow the client to temporarily show the location (if a client is not compromised the same logic is run client/server and the move should always be valid, but if compromised the server will know and can kick and/or correct the location)
I've been thinking of different ideas:
- Use NetworkVariables to hold the real positions of players, the the code update when the variable change. This allows the client to move the object and send the command, the server will then update the variable to the same/correct value and all clients will update accordingly. This approach should work, but i won't be able to use any NetworkTransform, NetworkAnimationSomething, etc.
- Have a parent object, with server authorization and a child object with the real object. When the client moves update the client object and send the command to the server. The server updates the parent and then the client is reset to 0. For this to work i will need to know when the server changes the value and also perhaps interpolate the values as the movement is not instant... (perhaps i have to swap the parent and child in this setup)
- Perhaps i missed something - can i still use some kind of combination of client/server auth and the check on
.IsOwnerand.IsServer. This is the option i thought was the correct one, but i can't seem to find out how?
I see the link above me, is that the best way to do it or what are the options?
This is the basic way to do client prediction
https://www.youtube.com/watch?v=TFLD9HWOc2k
Welcome to this Unity Tutorial where we go over Determinism, Fixed Tick Rate, Client Prediction, and Server Reconciliation. Deterministic Programs and Fixed Tick Rate are more theory but really important to understand in order to implement Client Prediction & Server Reconciliation. I then go into how to code Client Prediction & Server Reconcilia...
Thanks - i'll watch it right away 🙂 Looking great so far!
Ok so that video does not use netcode for gameobjects at all? Guess that was a 4th option to opt out?
thank you for pointing me back to this! that did contain the hint i needed to fix this
unfortunately now im having a really weird issue
im trying to set the Rigidbody on my held item to be kinematic, so it doesnt move at all. If i set the rigidbody to kinematic before I spawn the network object, its not set to kinematic anymore. If i set the rigidbody to kinematic after spawning the object, its parent status gets reset, and i would have to manually parent it
actually maybe if i set after spawn but before parent
maybe
NVM LOL even better, i deleted the line that sets the parent
briliant game dev here
actually i have a problem i need to solve now
How do I send a reference to a scriptable object asset over the network?
Preferrably without loading it from disk because that probbbbbably isnt great for performancce
Im trying to make an inventory system and right now im implementing the part where the player is holding an item, which obviously needs to be synced over the network
That video is more theoretical. But there are others out there that are NGO specific
Ok thanks - i'm just new to networking and wanted to try out NGO (just learned the abreviation now)
ok just as a side note you can make most things an abreviation, its not necessarily an official abreviation, just makes it easier to type since you know the context
I keep all the item SOs in a list and then just send the index. You can also use addressables and reference them by name
addressables? i can look that up later ig, im taking a break for a bit since i didnt expect a fast answer lol
can you automatically assign the index as part of the scriptable object when you add it to your list?
like when i add the SO to the list it should automatically update a field that is part of the SO to have its index
then all i have to do is Spawn_Held_ItemServerRpc(SO.index);
idk ig thats fine to do manually? seems mildly tedious after a few items
I don't know if its the best way, but I just OnValidate() to assign the id = GetHashCode()
Good point. I've seen the abbreviation before and didn't know what they ment
lol, for what its worth, NGO is the official abbreviation
what
how does that help
It automatically gives each SO a unique id. I have another SO with a list of every item in the game. I can search that list for an id
i just ended up using indexof
because C# would just internally compare addresses of the references right?
doesnt sound super expensive
Just do whatever is easiest. Don't worry about performance unless you are actually seeing a problem. But always keep an eye on the Profiler for potential issues
uhhhhhhhhh ok i think that might not work
it says it cant add the object
[Netcode] Failed to create object locally. [globalObjectIdHash=3301594181]. NetworkPrefab could not be found. Is the prefab registered with NetworkManager?
but on host it works finem
and it DOES create the object
weirdly enough
If you are trying to spawn a prefab then it has to be added to the network manager prefab list first
Is there any way to set the transform on a networktransform client side for the client itself only (other clients+host will not update) and then on server side - override that transform for everyone?
Network Transform uses Network Variables under the hood and those are automatically synced to all clients
You'll end up just writing your own network transform.
Is there any sane way i can turn manually placed network objects into spawned network objects?
Im trying to despawn that players pick up
But its not working because NetworkObjectReferences can only be created from spawned objects
but these items that you can pick up are resources that my player needs to have, and not being able to manually place them is painful
there is no way im hardcoding positions for 10s or 100s of items to do spawn calls
Ok thank you. I get it now. I think I'll use the network variables approach then.
btw i figured this out, it was trying to spawn my player hand object which i set up earlier
I am using Netcode for gameObjects and when i spawn a prefab I am doing
GameObject bulletPrefabGO = Instantiate(bulletPrefab, transform.position, transform.rotation);
NetworkObject bulletPrefabNetworkObject = bulletPrefab.GetComponent<NetworkObject>();
bulletPrefabNetworkObject.Spawn();
but this line
bulletPrefabNetworkObject.Spawn();
``` is giving me error
NotListeningException: NetworkManager is not listening, start a server or host before spawning objects
even though player movement syncs up meaning that the host and client are connected
How to solve this issue?
damn I made a typo in the second line it should be bulletPrefabGO damn
I'm developing a multiplayer game in Unity using Photon for networking. The game features a green cube that players can stack on top of each other, but I'm encountering issues with getting the stack to sync between players. Specifically, when one player stacks the cubes, the other player sees the cubes stack in a different position or not stack at all. Additionally, there are instances where the green cubes stack on top of each other even when there isn't enough space, creating gaps between the cubes.
I've tried using PhotonView to sync the position of the cubes, but I'm not getting the desired result. I've also noticed that the issue is partly caused by an if statement that incorrectly positions the cube when it is stacked on top of another cube.
Can anyone suggest ways to fix the synchronization issue with the green cube stack and make it work correctly between players? I would appreciate any insights or suggestions on how to address this problem. video =https://streamable.com/oipax1 script=https://gdl.space/uvogafetuj.cs
public override void OnNetworkSpawn()
{
if (!IsServer)
return;
foreach (NetworkObject NO in FindObjectsOfType<NetworkObject>())
{
if (!NO.IsSpawned && NO.gameObject.layer == 8)
NO.Spawn(true);
}
}
Trying to run this code to Spawn() my manually placed objects, but even though im checking if the object is not spawned, im getting this error:
SpawnStateException: Object is already spawned
Any ideas how I can get my objects to be spawned
In scene network objects get spawned automatically
? then why am i getting an error about an object needing to be spawned
huh
also wtf is happening rn, i cant destroy some objects even with a serverrpc
time for debug.log
yeah the debug.log is not going off interesting but i know why now at least
okokok i figured it out, it was some werd ownership related bugs
now i have to deal with this, and then it should be fine
these are the images of two different clients, and the second image a client that connected later
after the host despawned one of the items
and if i try to pick it up it says "cannot despawn an item that isnt spawned"
something like that, but i think its due to the fact that these items are placed in the scene beforehand
ahhhhhhhhh, this is covered here if anyone else has this issue: https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/inscene-placed-networkobjects/index.html
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
context?
there are several errors there
As I understand it, this is an error from the client because his data is not displayed and a nickname is not issued
the host is doing well
what is lobbymanager
...... which console is the error from
also are you using netcode
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
host unity play
client Build start PC
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
no the Player class
?
How can I get a number of players playing?
The server/host can access the network manager.ConnectedClients list
Which networking framework is more reliable in terms of count of job postings? Photon or mirror? Perhaps something else?
I've never actually seen a job posting specify a network framework before. Photon probably has the larger user base. But if you learn one it takes like a day to learn the others. They are very similar to each other.
I am having trouble learning networking any tips I am following this udemy course but unable to understand stuff I need a very very basic course in mirror engine unity
ping me
How does unity multiplayer compare to unreals? What should I use? Any good pointers to getting started?
i have a simple script listening via the low level utp unity transport using their tutorial, however for the client i want to use a python script. I successfully send a udp packet and it shows up as an accepted connection with a correct udp header, however, the PopEventForConnection never returns any data on the unity side. Do i need to send some special packet data to trigger this for utp to recognize it?
And how do you do it?
Check the pins for documentation. You can find tutorials and example projects there. Also Codemonkey has a great tutorials for Netcode for GameObjects.
Alright thanks
Same thing, Mirror documentation has tutorials and examples and creator videos for it
there are videos there ?
Community guides > Video tutorials
Is there a netcode override that runs after OnNetworkSpawn and only once? Im trying to set up an object that dynamically spawns in items that are part of the level, but i cant reparent my objects because the network object im trying to parent them too is Spawned after im calling TrySetParent
basically structure looks like this
which networking engine is best for jobs ?
Item Table:
-> Item 1
-> Item 2
-> Item 3
-> Item 4
-> ...
and OnNetworkSpawn is called on Items 1-4 etc.
before it is called on Item Table
what networking engine should I learn I want to make my own games as well as apply for unity jobs ?
ping me
any one you want to use
are they all the same ?
They are very similar but not exactly the same. Some features are different but almost all of them use some form of RPCs and Network Variables
Netcode unity client cant push ball by
I do understand that we override virtual functions in c# to replace their functionality with a new functionality I was watching this tutorial I think this dude is overriding built in function why is he doing that what purpose does it server ?
ping me
These methods are not fully implemented by the base class (they are stubs) and provided for the user to be overridden to add the desired behavior. Notice the call to the base class to trigger the provided behavior (if any), which makes the override additive.
stubs ?
a small piece of code used as a stand-in or mock for an actual implementation
protected virtual void FooStub() {
// implement me
}
also, if you see a pattern with protected void OnSomething() its usually provided as a way for you to extend functionality of a base class without accidentially overriding the base behaviour
public abstract class Foo
{
private void Something()
{
// internal behaviour here
// then call to client code
OnSomething();
// more internal stuff here
}
// stub that can optionally be implemented
protected virtual void OnSomething()
{
}
// stub that must be implemented
protected abstract void OnSomething();
}
then in a derived class
public class MyFoo : Foo
{
protected override void OnSomething() {
// your custom behaviour here
}
}
Ok this is intresting so what you are saying is if I want the old behaviour and new behaviour I can keep both by overriding a protected virtual function ?
Which networking solutions should I use for a 30 person multiplayer shooter game?
Client/Server:
- Fusion: if you want most groundwork done for you in an opinionated way
- Netcode for GameObjects: if you want to do some legwork to implement the competitive features yourself but still want to use a well supported framework for the basic stuff
- Mirror: same as netcode but you wish to go with a community solution
- FishNet: if you feel adventurous and can discover solutions without help from the community (which is larger for netcode/mirror)
- Quantum: if you have the money and want an opinionated, data oriented solution
- DIY with a proven transport: if you don't trust other people have solved a significant part of your project's specific needs for you
Hosting:
- PlayFab: if you want a scalable and proven platform to run your game
- Unity Gaming Services: same as above with better unity integration
- Photon Cloud: if you use any of their products (Fusion/Quantum) for best support and integration or as complement to the above
- DIY infrastructure: if you have specific needs not captured by the above
If i start with photon i can change it later right? It's too expensive
as long as you take care to keep it all modular, sure
docs say that OnClientConnectedCallback will be called on the server and the local client that connects. But using NetworkManager.Singleton.OnClientConnectedCallback += ClientConnectedCallback; It only runs for the host once they start the server. It never executes when a client connects. Any ideas?
When are you subscribing to it? You'll need to make sure its before the client actually connects
in my multiplayer manager singleton script (not a custom networkmanager)
public void CreateOrJoinServer()
{
NetworkManager.Singleton.OnClientConnectedCallback += ClientConnected;
NetworkManager.Singleton.OnClientDisconnectCallback += ClientDisconnect;
if (NetworkMode == NetworkMode.Client)
NetworkManager.Singleton.StartClient();
else
NetworkManager.Singleton.StartHost();
// other code
}
private void ClientConnected(ulong clientId)
{
Debug.Log("new client");
}
I can't figure out why it's only being called on the host once they start and never when a client connects
as you can see it's before the client starts
Is the singleton being destroyed and recreated like on scene change?
no, it's in DDOL
the scene events are being called when a client joins, but not the clientconnect/disconnect calls
why call clientrpc method rpc move in cmdMove to move player is this because we informing by saying clientrpc that the code must run from server to client and in order to call the rpc function we must run in cmdamove ?
cmd move is further being run in update function
This is a Server Authoritative setup. Commands are sent from the clients to the server . ClientRPC is sent from the server to update the clients .
what is clientRPC function doing in Command function ?
That is the server sending to the clients
so i'm planning to make very large world but i'm running into problems with floating point precision
so i made script with is moving origins for game objects in world back to 0,0,0 if is outside 5km range
so my question is how i can deal with transforms and physics this situation ? where all players are in the same space on clients
ps.image is representation of world with out origin shifting
can you explain a little bit more ?
how the functions are interacting ?
he i found this https://assetstore.unity.com/packages/tools/network/origin-shift-multiplayer-infinite-world-solution-204179 i hope is good
The clients are calling the command which is being run on the server. the server will validate the input the call the clientRPC which will be run on the clients
Thanks from me too! Do you/does anyone have a large and nice summary for comparing all of the (main) solutions out there? (client/server and hosting) or resources, links, etc… I have only found snippets of information online. Thanks.
The Fishnet devs had a benchmarking thread over on the Unity forums. It's more of an ad for Fishnet but has a useful chart
https://forum.unity.com/threads/updated-free-networking-solution-comparison-chart.1359775/
Yo what the photon discord server
Check the pinned message here. It's listed there
Uhhh, is it possible to get InvalidOperationException: Client is not allowed to write to this NetworkVariable on the server??? Im using netcode. Basically Im trying to handle network sync for an inventory, but my Server RPC is getting a client cant write to a network variable error. This is in the stacktrace on the server end:
InventoryController.Throw_Item_ServerRpc (Unity.Netcode.NetworkObjectReference object_reference, System.Int32 throw_count, System.UInt64 client_id) (at Assets/_Scripts/PlayerController/Inventory/InventoryController.cs:109)
it IS a host, maybe that's related? no clue
Hi, I am working on a server authoritative inventory management system. How do I turn my local inventory manager into a script that is synced across all clients and managed by the server all while supporting RPC calls? I haven't quite figured out how to work with singletons inside netcode
You could make it derive from NetworkBehaviour. You can set its ownership in NetworkObject component, then restrict access to ServerRpc calls with [ServerRpc (RequireOwnership = true)]. That way you could create an inventory instance on the server for each client and then spawn it.
Thanks, but there's one small issue; at the moment the inventory manager (ItemManager) is also used in the main menu to display items and their stats. I can't simply delete the instance and only have it as a networkobject on the server once the game starts. (Perhaps some separation would be required?)
The main menu only requires the list of all items that exist in the game, so I think that taking all other logic from the ItemManager and putting it in a network spawned InventoryManager which only exists in the game scene would be a valid approach. What is your opinion on this?
I probably misunderstood your previous question. Do you want to have one instance per player (where players have authority only over their own instance placed on the server) or 1 instance for all players (where all players have equal access to it?
Netcode has a possibility of spawning NetworkObject on clients, which becomes its equivalent. If an object is a NetworkObject, then you can use NetworkVariable to mark some of your fields and make them automatically synced. If you want a separate inventory for each player, then I would suggest splitting your visuals and logic from synced data, so you could have visuals and logic inside a singleton while having the rest in synced instances. If you don't want a separate inventory for each player, then it's not required, but it's still a good practice to separate data.
You don't. If you have one inventory per player then it simply can not be a Singleton. You can make a separate Player inventory class that is networked and have it ready from the item manager
Clients can not run ServerRPCs. Something is wrong with that RPC. Are you missing the [ServerRPC] attribute?
thanks folks, I'm working on the network spawned playerinventory script now. The itemmanager now only contains a list of all items
What is the latest unity networking please?
Learn more about the available APIs for Unity Multiplayer Networking, including Netcode for GameObjects and Transport.
Thanks. Is there a way to download the docs in raw text?
There is a pdf link at the top of each page
Thanks I was hoping to download everything in one pdf 👍
nope, its there
hold on lemme open up unity rq and triple check but its there
and its running as an RPC because im calling it on one client and its running on the other end, and if i check the stacktrace it shows RPC-related functions running
how would i assign a networkidentity created at runtime a assetid and sceneid
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
I'm trying to send a huge struct from the server to clients. I've tried [ClientRpc] and .SendNamedMessage, but both ways end up with an error OverflowException: Writing past the end of the buffer. Is there any way recommended method for handling huge structs?
How can I handle the latency of network variables? I call a client rpc after I change a network variable, but the client rpc fires before the variables changes on the client end
what do you need a huge struct for
To send a board state. In the case of randomly generated boards, I could send the seed alone (so the client could recreate the whole board on its own). In the case of asset boards, I could send some asset ID (so client could simply load it from assets). However, in the case of modified boards, I would need to send the whole board, which would result in a huge struct built from 100x100 or more tiles. It pretty much blocks me from any attempts of creating custom editors for players. It also might be a problem in the case of random maps with a fog of war - sending a seed would give an advantage to any cheating player with a modified build.
Technically I could split the struct into smaller chunks and send them one by one, but it doesn't seem to be an elegant solution. I could use another networking system for large files, but I don't like the idea of mixing several networking solutions.
if you cannot send the big struct, sending a split seems like your best option
just make a class that takes in the big struct and splits it into 2 differnet kinds of structs, one that tells the client what data it should expect, and one that is the split up board
I will try that. It's a shame it can't be done an easy way.
i mean there might be buffer size option, but if you want infnite scaling this is probably an acceptable option
also dont take my answer as the only truth because i am not a professional at this stuff lol
Infinite scaling seems like a risky design. It's better to keep it within some reasonable bounds. To be honest I was surprised it couldn't handle 100x100 array - an average image from the internet weighs more. 😅
how much data per tile?
also i dont mean infinite exactly, but i mean more if you just change the bufffer size, there is probably an upper limit
and then you can send data anymore
cant*
3 ints, so it's not much.
yeah thats tiny compared to most images
Any idea where could I find it? I already increased the limits in the UnityTransport component.
?
It works fine for 50x50 board (break on 100x100). After decreasing those values to default values it still works the same. It's safe to say those values don't affect it at all. Gonna check in google where the actual buffer size is hidden.
fair enough
If the Rpc is supposed to be a result of the variable change, then I would suggest to subscribe it:
private NetworkVariable<int> m_SomeValue = new NetworkVariable<int>();
//
m_SomeValue.OnValueChanged += OnSomeValueChanged;
The rpc is a result of a state change
so not directly linked to the variable
but it's important the variable is synced before a client tries to process the state change
Is there a way the server can know when a network variable is synced?
I guess I could use an rpc to update the variable instead, since rpcs are called one after another
It would be nice if network variables did the same
I suppose client could send a ServerRpc to notify about the received data. It sounds messy tho.
yeah I was thinking that and dismissed it for that reason
at that point just use an rpc to set the value
It seems that UNetTransport had such a variable configurable. It doesn't seem to be present in the UnityTransport.
what are the drawbacks of unet vs unity tho
isnt unet some deprecated transport method
Yep, it's deprecated. It's a significant drawback unless someone keeps updating it like people did with Mirror.
Oh wait, Mirror was build on UNet.
So I suppose I could switch to Mirror. 🤷♂️
but does mirror expose that option?
UNet did, so Mirror also should, since it's a non-official continuation.
interesting
the splitting/batching/streaming happens anyway on the transport layer, its by no means inelegant, if you need to send big chunks of data, you'd be better off using protocol that is built for it (like good old HTTP), multiplayer transports are all about collecting a lot of tiny fragments of data, batching them into a tick, sending them in one message to all peers and then splitting them up into their original framents for their consumption 10 - 100 times per second, all the while allocating zero garbage.
Perhaps I could create my custom splitting and then try to use it on any bigger data. It's worth a try.
Do you know if Netcode has any additional tools for heavier data?
Not that I’ve heard. It would be out of scope for a multiplayer framework of its kind.
Hello, I would like some help on a problem with a multiplayer game that I am working on.
I am currently working on a multiplayer aircraft simulator and I have a problem where when the two users connect to the same room, they don't officially connect (ie, its two different versions of the same room) my code is below this message and I will post a video of the problem. Can anyone help me?
I need help with photon, Im trying to make a Fall Guys game but I don´t know how to change to a random scene (maps), can someone help me?
I also need some help with my Photon Pun Project
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Photon.Pun;
public class ConnectToServer : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
private void Start()
{
OnConnectedToMaster();
OnJoinedLobby();
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
Debug.Log("menu");
SceneManager.LoadScene("Avatar");
}
}
``` why does this do absolutely nothing
i dont even get any errors
i just sit in the loading scene and it never switches
or
CreateRoom failed. Client is on MasterServer (must be Master Server for matchmaking)but not ready for operations (State: Joining). Wait for callback: OnJoinedLobby or OnConnectedToMaster.
Why does Start() call the callbacks? Those should get called by PUN...
Connect, Join a room (Photon lobbies are just for listing rooms / matchmaking) and OnJoinedRoom, you could load a scene.
"Switching Scenes" here is related:
https://doc.photonengine.com/pun/v2/gameplay/instantiation
Look up the keyword AutomaticallySyncScene or do the PUN Basics Tutorial (which does scene loading, too).
Most multiplayer games need to create and synchronize some GameObjects.
Maybe it's a character, some units or monsters that should be present on all...
Ask here or in the Photon Discord.
what is happening why is a clientrpc function in a command function
It's supposed to make the game server-authoritative. You want to call ClientRpc from the server, so the server can send the info to all the clients. If a client would be able to call ClientRpc themselves without server intervention, then cheaters could modify their build to cheat, e.g. they could move faster or even fly. So pretty much what you see is "I want to move, but other clients aren't supposed to trust me, but they trust the server, so I tell the server I want to move so the server can verify if it's not an illegal move, and then the server sends info to other clients that I'm actually moving and other clients will belive it".
okay but how is this working ?
i understand clientrpc is like when server sends signal to clients and then command sends singal from client to server
but still don’t completely get it
Inside CmdMove there is a comment // Validate logic here. The server should check here stuff like:
- is the player alive?
- is he not immobilized?
- does he have stamina?
- is the match not paused?
Etc.
i do understand how code is working and tags but dont understand how tags are in sync
with each other tags like clientrpc and command
thanks for this it gave some clarity
so cmd move is called by the client to the server and then rpc move is calling the client to move the player from server
why is this so hard for a newbie
Yep. Everything is safe, but there is a small delay between each step.
or am i dumb
Starts are always challenging.
ok i understand it a little better
thanks for da help
I'm having issues with syncing of network variables. I change a network variable from the sever before calling a client rpc. On the client the rpc can run before the network variable has updated, leading to some syncing issues. I've fixed this by making it regular variable and then setting it with an rpc, but it feels like this shouldn't be necessary. Any ideas on alternative fixes?
[Netcode] NetworkPrefab "Player" has child NetworkObject(s) but they will not be spawned across the network (unsupported NetworkPrefab setup)
i have that problem and i started to lose my sanity
alright, i've made my networking environment and everything is working perfectly, my character has 9 different meshes (more like prefabs) for looks and all of them are nested
i can select my character and join to the server but other clients' characters are looking like this(both for host and client situation). somehow its not synced across the network. i tried to attach client network transform script to the parent of these nested meshes but gave me that unsupported network prefab setup error
in every client, i'm getting the chosen character value from the login screen and i use a script that deactivates other meshes but the chosen one. i've tried to deactivate all prefabs and make them active via code but still didn't work. i tried network variables but wasn't able to make them spawn bcs i don't know how to make it, i also don't know much about rpcs. does anyone have an idea to solve this problem?
Hey guys, I am trying to set the colour of my gameobject in netcode however, it is changing the colour of all the gameobjects of the same material in that particular player's scene
How can I prevent this?
Also, how is it advised to sync/move the player ? Send data directly from client or send a rpc to server to move the player?
Instead of refering to material refer to renderer.material. When you refer to material through Renderer you have certainty it will modify only its instance and create instance if needed.
Client-client connections have a risk that someone will start cheating. E.g. you could receive information about a player who you're not supposed to see, so pretty much someone could modify its build to be able to see through walls.
Verifying everything on the server reduces the chances of cheating.
I did this on the client side, it will still change the material of another box to red
public class MovementScript : NetworkBehaviour
{
public Material Mat;
public float SpeedMultiplier = 2.0f;
// Start is called before the first frame update
void Start()
{
this.Mat = this.gameObject.GetComponent<Renderer>().material;
}
// Update is called once per frame
void Update()
{
if (!IsOwner) return;
this.transform.position += Vector3.right * Input.GetAxis("Horizontal") * SpeedMultiplier * Time.deltaTime;
this.transform.position += Vector3.forward * Input.GetAxis("Vertical") * SpeedMultiplier * Time.deltaTime;
this.Mat.SetColor("_Color", Color.red);
}
}
(Just ignore the c# tag, I was trying to kick in the syntax highlighting probably messed something up)
Is this what you meant ? @spring void
Oh my dear god, I did a horrendous mistake, I already had set the colour of the material to red and then i was reassigning it in the code above 😂
It's fixed for the client, but the server won't sync it for other clients, is there a need for RPC to accomplish this ?
Sending Rpc to other clients is the easiest way here.
But the RPC has to route via the server right? I am not sure if Client to Client RPC exists 😅
I don't think there is a possibility of sending client-to-client Rpc in Netcode.
NetworkVariables have the option to let the object owner modify the value, but honestly don't know if its client-to-all or client-to-server-to-all communication.
I suppose you could try storing the value in NetworkVariable and update meshes by doing it in overrided OnNetworkSpawn method:
https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkBehaviour/index.html#onnetworkspawn
The base class to override to write network code. Inherits MonoBehaviour
How do i get a list of every player in the room? Something like their GameObject or similar?
When making client side prediction with a RigidBody movement system do i have to manually simulate the physics? If so i tried doing that but having multiple players simulating physics causes the movement to speed up, I tried creating an idle scene and place all the other player's when someone is simulating physics but it completely breaks all movement checks
it would be better for you to save them on a list when you spawn them, but you can also use GameObject.FindGameObjectsWithTag
first off, they hadnt been working before so i put them in Start(), but i just removed them from start and they work now
Second, i did the PhotonNetwork.LoadLevel(); which works, but now ive got this that doesnt work still
public class MenuController : MonoBehaviourPunCallbacks
{
[SerializeField] private GameObject StartButton;
private void Start()
{
PhotonNetwork.ConnectUsingSettings();
}
public void CreateRoom(){
Debug.Log("Creating Room");
PhotonNetwork.CreateRoom("Game", new RoomOptions() {MaxPlayers = 5} , TypedLobby.Default , null);
}
public void JoinRoom(){
PhotonNetwork.JoinRandomRoom();
OnPhotonJoinRoomFailed();
}
public override void OnJoinedLobby()
{
Debug.Log("Joined Game");
PhotonNetwork.LoadLevel("Game");
}
public void OnPhotonJoinRoomFailed()
{
Debug.Log("Failed");
CreateRoom();
}
}
bc i get this error still
CreateRoom failed. Client is on MasterServer (must be Master Server for matchmaking)but not ready for operations (State: Joining). Wait for callback: OnJoinedLobby or OnConnectedToMaster.
Hi, when I try importing the Netcode for Game Objects in the Package Manager, I get this error.
The ffffffffffffffff is just to hide my PublicKeyToken (not too sure if I need to hide it or not, so just took a precaution).
I tried creating a new project and importing it, I've tried deleting the library of the project and importing it, I've tried downloading a new editor version , creating a new project and importing it, and it just keeps giving me the same error. If anyone can help that would be greatly appreciated, thanks 🙂
PhotonNetwork.CreateRoom(CreateGameInput.text, new RoomOptions() {MaxPlayers = 5}, TypedLobby.Default);``` photon doesnt create rooms for me
it just wont
nvm i got it!
have an issue, both of these guys are like, controlled by the same window
and yeah i know why
but
take a look. those avatar changing things find the player here, in ddol and change them. then, while switching scenes, the player is just casually brought to the next scene looking exactly the same!!
what im SUPPOSED to do is:
PhotonNetwork.Instantiate(playerPrefab.name, randomPosition, Quaternion.identity);```
but doing that just spawns in a new blank character, and i dont want that.....
so i need it to like instantiate the player i have in the hierarchy, but doing this:
GameObject player = GameObject.FindWithTag("Player");
Vector2 randomPosition = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
PhotonNetwork.Instantiate(player.name, randomPosition, Quaternion.identity);```
doesnt work
Yea that's not ever going to work. Youll need to send the player choices as well. Probably as json.
how do i do that
You can send it in an RPC
alr i know what those are but i have no clue how to rlly use them for this
You have a player class with the player's configuration. Serialize that to a json string then send it in an RPC to call the clients
https://docs.unity3d.com/2021.2/Documentation/Manual/JSONSerialization.html
hi folks, ive had a project running on pun for a couple of months now, that has been working absolutely perfectly, but for whatever reason it has just stopped working with 0 code changes at all
it seems to get stuck on PhotonNetwork.CreateRoom()
i have callbacks for OnCreateRoomFailed and OnFailedToConnectToPhoton setup too and it doesnt print anything at all
fixed, MaxPlayers in RoomOptions was too big, previously it would just create a room with the max allowed players allowed for your account if you set the maxplayers to a number bigger than what your account allows
(i had it set to 100 when my account only allows 20 people in a room, but it would just make a 20 player room just fine anyways before)
i do not understand why photon would change this behavior at all
If anyone has any suggestions whatsoever that could stop me from beating my head against the desk trying to figure this out that would be amazing
Sounds like you might be on the wrong version of Unity
That is usually when the client isn't fully connected yet
alright thank you first of all, i'm trying to make it right now, i hope it works
would i need to optimize this? Is FindObjectsWithTag() a bad idea to invoke every frame?
(on a mobile processor)
Run it once in start and cache the reference, alternatively subscribe to events that indicate that it’s time for an update, alternatively use a manager and inject relevant dependencies from where they are created down to the object that uses them. Any kind of search like you do there is bad design outside init of a manager
what is the equivalent of [Command] method in netcode?
ServerRPC
thank you!
Hey guys, I am new to Unity networking and want to announce a transform's material colour over the network, from a previous discussion over here someone advised me to use RPCs inorder to accomplish this. I am trying to send the Transform and the Material of the object as a parameter of the Server RPC (then I plan to announce it to other clients using the ClientRPC i will be writing) however, I am getting the error that Transform is not a Non-Nullable type and hence it cannot be serialized
Is my approach wrong here?
the approach you should be going for is in principle: 1) have states that both client and server understand, say you define those in an enum, maybe you have two enemy and friend; 2) you also give every object that is sharing this state over the network in your game an id-number; 3) then you send only a new state and the id-number of the target object you want to have that state info over the network; 4) then on the other side, look up the object that has the received ID and whatever should happen when the state becomes active, then do that. So if you sent enemy, 5, you'd find object five and make it red, but red is never sent over the network, its associated with the state enemy.
that number lookup thing is what network object components in your framework of choice are for, the enum and RPCs to send them are your custom code.