#archived-networking
1 messages · Page 14 of 1
Hello guys,i need an help with a game i am developing,if you know how to implement interpolation in a multiplayer game write me please
how do i get my teacher player to teleport the student player i have tried several methods but nothing is working.
Teacher Scripts:
https://pastebin.com/9Wtm0DLQ
Student Script:
https://pastebin.com/0qj3BLQv
GameManager Script:
https://pastebin.com/RayLrrCD
So I'm working on a multiplayer game is there a way to improve the lantency of my game when using Netcode?
You can't really improve it without getting a better network. You can mitigate it's effects by using Client Network Transform or by writing a client prediction system.
I understand and if other players gonna play the game, will they have a different network than me or the same? (Like the same latency)
Depends on where they are located and if you are using a relay service or not. Or if either of you are on wifi. Also latency can change during a match.
You can also set the delivery packets to be unreliable if they are sent a lot, so if the player is lagging they wont have to receive old ones as I understand it.
By default they are reliable, that means every packet is guaranteed to be delivered.
[ServerRpc(Delivery = RpcDelivery.Unreliable)] //Movement is updated many times a second, package reliability not needed
private void HandleMovementServerRPC(string SuggestedAnimation, Vector2 suggestedVector, float suggestedSpeed)
{
animator.Play(SuggestedAnimation);
rb.MovePosition(rb.position + suggestedVector * suggestedSpeed * Time.fixedDeltaTime);
}
//Starts host if info valid
manualHosting.onClick.AddListener(() =>
{
getConnectionInfo((bool isInfoValid) => {
if (isInfoValid)
{
//Disconnects from other server
Disconnect();
//Start client
NetworkManager.Singleton.StartHost();
//Remove start menu UI
allUI.SetActive(showUI = false);
startMenuState = StartMenuState.manualHosting;
}
});
});
public void Disconnect()
{
NetworkManager.Singleton.Shutdown();
}
I got a problem where I sometimes I have a host or client already running.
I shut down the NetworkManager, then I want to start another connection.
The problem is that the shutdown is delayed and it happens after I tell it to start hosting or being a client.
I'm trying to simulate someone swapping servers or starting a new one
You can check NetworkManager.ShutdownInProgress before trying to reconnect
There is also the OnClientStarted/OnServerStopped events you can listen to
So I'm going to make a singleton that is a "Data Manager" which holds a dictionary of a dictionary prefab with a unique key for each player, making it so you can get the players key, then get the value from their specific dictionary (and make it so if you rejoin etc your data is the same etc).
This data manager is going to be only made once a lobby is made and is going to have server authority, making it so only the server can change stuff on it (the clients can call RPC's for changing stuff like cosmetics or something, like keeping track of score).
How would I "Make" the data manager?
I mapped out the scenes etc and the flow state for the data manager, upon creating a lobby I want the data manager to be created upon loading into the "lobby" scene and having it so if clients connect they get a synced data manager
Would I use the network manager I made to make it so upon hosting a lobby you create a data manager?
Would I make it so upon leaving you remove it?
I'm only asking instead of experimenting and googling because I'm uncertain about how to approach this and feel like someone may have experience enough to recommend one way or another
Player Manager
Hey, I have problem, I'm trying to create chat system but it doesnt really work as intended althrough code seems to be fine
public void SubmitText()
{
string str = inputField.text;
str = str.Replace(" ", "");
if (inputField.text != null && str != "")
{
string newStr = "<color=orange>" + playerNetwork.playerName + "</color> " + inputField.text;
SendMessageServerRpc(newStr);
}
}
public void PrintMessage(string str)
{
TextMeshProUGUI newText = chatQueue.Peek();
newText.gameObject.SetActive(true);
newText.text = str;
newText.transform.SetSiblingIndex(0);
chatQueue.Dequeue();
chatQueue.Enqueue(newText);
}
[ServerRpc(RequireOwnership = false)]
public void SendMessageServerRpc(string str)
{
ReceiveMessageClientRpc(str);
}
[ClientRpc]
public void ReceiveMessageClientRpc(string str)
{
PrintMessage(str);
}
message is send to all clients on server but its not received by local player instance but its only received by instance of player thats send message but in other clients side?
Its weird and I dont understand it, anyone had similar issue?
Put a debug log in you RPCs to make sure they getting sent and received. I have feeling your PrintMessage function isn't quite right. Normally you would instantiate a new line for each message or use a giant string with /n new lines
i mean PrintMessag doesnt really matter because if i put for example print(this.gameObject.name); before it like that
[ClientRpc]
public void ReceiveMessageClientRpc(string str)
{
print(this.gameObject.name);
PrintMessage(str);
}
it somehow still only print one name
it looks like it only invoke in one player instance across all clients and its weird
Mske sure this script is on an active network object on all the clients. ClientRPCs get broadcast to all clients by default
yes it is, yet it doesnt work
If you're making a network variable then you'll need to use a Native Container like NativeArray or NativeList
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/arrays/#native-containers
Arrays of C# primitive types, like int], and [Unity primitive types, such as Vector3, are serialized by built-in serialization code. Otherwise, any array of types that aren't handled by the built-in serialization code, such as string], needs to be handled through a container class or structure that implements the [INetworkSerializable interface.
How can I effectivley syncronize a lot of data ? I want to make my enemy behabe realistic therefor im going to use a boss simulation but i do not know how i could sync these massive enemy swarms without lag
sounds like you wont be doing that then ;-), typically "a lot" of anything in multiplayer, does not work out.
Is there any other solution i could use for the enemies?
how do games like battlebits sync so many players ?
🤔
[Netcode] [DestinationState To Transition Info] Layer (0) sub-table does not contain destination state (0)! i cant find anything on google about this but im getting this error with the ownernetworkanimator
Sounds like an error from the network animator complaining it’s missing a state. 0 should be an invalid state so I’d assume the state data received is invalid, maybe the authoritative animator isn’t configured right.
What is the problem you are having? and what solutions have you tried?
The enemies in my game are pigeons and birds are kinda like a swarm inteligence so i wanted to simulate the big bird groups with a boids simulation the problem is sending location data for arround 500 birds is probaply way too much and its probaply even too much for just 100 birds. I did not attempt to code the birds as i wanted to find the best solution for the data problem first.
If it's just a visual effect then you can just sync the lead boid or whatever the main object is and have the rest of the boids simulated locally.
If the individual boids are gameplay relevant then you're gonna be forced to use DOTS and probably Netcode for Entities along with it.
thei need to be able to be shot down and attck you so Dots it is
im just worried that the game will have a lot of lag when i send so much data
NFE has built in client prediction and a priority system for sending packets. It should be ok
I need urgent help. This is fucking my brain so hard.
I'm trying to use netcode for gameobjects to make a multiplayer game, but the transforms aren't syncing well.
I've attached the script and a video with an example of my problem
I wanted to use Rpcs so that the server with be the only one with authority, but that was happening, so I tried using the exact same script that I had for MonoBehavior and tweak it just enough so that it would work on multiplayer with client authority, but I encountered the same exact problem and I have no idea what is causing this
I got a question about Networking apps:
Which app/program is the best to use. I would like to have unlimited CCU, so many people can play the game.
Photon has limited, that’s bad. What bout mirror? Any other suggestions?
You're gonna have a hard time trying to retrofit networking into a single player game.
But is there an issue with just putting a Client Network Transform on the player?
You can use a free relay service like Steam P2P or Epic Online Services with Mirror or Unity Netcode. Unity's Relay has a free tier that is fairly generous.
I ain't. I wrote the original script as a MonoBehavior, but I always intended to make a multiplayer game, not a singleplayer one. I have tried rewriting it using ServerRpcs and with a non-authoritative Network Transform but I was having that result. I thought that maybe my problem was related to calling two different Rpcs working with the same components, so I tried using a client authoritative version with a Client Network Transform, which is almost all the same same as the original one but the MonoBehavior now being a NetworkBehavior and the IsOwner.
I also tried disabling interpolation since I have had problems with it before and it actually worked, so I tried setting interpolation on and position threshold to 0 and that also worked, but when I try that in the non-authoritarive script it adds an unbelievable amount of delay between the moment I press a key and the moment something actually happens
I still want to find another way to fix this since I don't want to give any control to the client
hey, hwo would I go about syncing a large array between the server and the clients with NGO? NetworkList is a peace of garbage and makes more problems than anything else
nvm I ditched the array idea completly, I found a better approach
the animator is setup perfectly and i have the ownernetworkanimator setup from the unity docs why would i get an error
is it triggers causing it? i have a trigger but im calling it from the network animator
if u had one "big game", which would u use?
If it's already on Steam then use Steam P2P. If it's not out on steam it's not a big game and you have nothing to worry about.
Personally I'm sticking with Unity Relay and Lobby services
is it easy to switch to steam p2p when the game is getting big?
If you are using NGO it's just a matter of swapping the Transports and a few API calls. Mirror I believe is similar.
i think ill go with mirror. it has more tuts. should be good enough
[Netcode] [DestinationState To Transition Info] Layer (0) sub-table does not contain destination state (0)! still stuck on why this is happening
i have a normal animation state setup just transitions i double checked nothing is abnormal but i get this error anytime a animation plays is there a simple setting im forgetting
when its just the host i dont get the error
i made a more basic version and got this error:
[Netcode] [DestinationState To Transition Info] Layer (0) does not exist!
That's usually when the network animator is not on the root object
it is
The regular animator is as well?
yes
Do you have multiple animators?
just one
public class OwnerNetworkAnimator : NetworkAnimator
{
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
``` this is the script its just the basic ownernetworkanimator i dont get why its doing this
is there a difference in the unity 2022 lts vs the 2021 in how animations work
im using the newest version
No difference. If this is happening in a fresh project then open a bug report here
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/new/choose
is this defined as fresh lmao
everything works the animations sync perfectly the error effects nothing its just annoying
it only debugs if im in developer mode on error logs
I want to create a game with mirror networking. When it would be finished, can I hire someone who rewrites it for steam. So people can play it on steam. Is that possible?
I would look into details of Steam transports made for Mirror. Worth noting that Steam's networking services aren't a requirement.
https://mirror-networking.gitbook.io/docs/manual/transports/fizzysteamworks-transport
this would work right?
Should work.
Hello everyone, I want to send a request to a custom backend when the game is closed.
I have tried using the OnApplicationQuit() and WantsToQuit() methods, but they don't seem to work.
It seems that there is not enough time for the game to send the request when the closing sequence is initiated, which is why this process doesn't happen, and I'm unable to send any message to the backend.
However, as we know, many games are able to perform this action. For example, even if I force-close the game from the task manager, the game still sends web requests before shutting down.
How can I solve this issue or what approach should I take when faced with such a problem?
This is the code of the request I sent when the game was closed
do you know a good tutorial for dots and nfe ?
The YouTube channel Turbo Makes Games is the best and only resource I've found for Dots. There is even less regarding NFE.
I'm currently working on some videos basically walking through the Netcode samples on github
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/NetcodeSamples/Assets/README.md
hey guys can anyone familiar with photon pun here tell me how should i make a game manager, i am not talking about the code itself more like, how to make one object control things like game time, game end, game events and stuff like that, i already asked on photon server but i am waiting 10 hours and nobody answers
Anyone have any available benchmarks on Photon Fusion vs FishNet? I'm leaning towards FishNet as I've used it before and it's free essentially; however, I'm wondering if I'd have better luck using Photon Fusion for an FPS game
how can i add force to another clients rigidbody from another
im using non server authoritive movement so when i do serverrpc the client can hit the host but not the other way around
using netcode
The serverRPC will need to call a clientRPC to add the force to another client
i already tried just calling a clientrpc will calling a clientrpc from the serverrpc be different?
only the server can call clientRPCs. So it needs to be in a ServerRPC if the clients are initiating it.
should you use unity's new multiplayer system for a commercial product yet? or is it still being worked on
did not know that.. on tutorials it has the client sending a clientrpc
Yea. RPCs are one way only
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.
so i should make the client call a serverrpc then in that call a clientrpc to the one client i want and make it add force?
exactly
when doing a client rpc do i need to get the object and components or can i just do rb.addforce using the reference i have in the scritpt, every player has this script
@sharp axle
this clientrpc is called from this serverrpc
clients don't have access to ConnectedClients[].
You'll need to send a NetworkObjectReference of the player you want to move
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#networkobjectreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
ik i havnt changed it yet but do i need a reference at all
im guessing not
what im saying is when a clientrpc is ran on a client do i need to get the component rigidbody or jjust use the rb reference in the script
If you have the client Id then you can just send the clientRPC directly to that client
Yea. once its running on the client just call getComponent()
That should be fine.
ok thank you
just transitioning from pun 2 and with that u need to get the components seperately
confusing
did not work
i tried this and it does not work no force is added but the debugs are correct @sharp axle
What is movement there?
which player? that is being run on the server. so movement will always be the host
only the client im sending the clientrpc to is running it though no?
the ids lineup the correct client is running the clientrpc
ah, you're that two functions there
im getting the id from this and calling the serverrpc with the client id i want to have force added
That should work
no movement when i try it
keep in mind im using the ownerNetworkTransform
and network rigidbody
yea. thats why you need the clientRPC.
are XYZ values correct?
yes when i had a different rpc setup the host could get hit by the client and the xyz was correct
so yes
im bad at explaining
why is it so hard to make a client add force to another client damn
@sharp axle do u have any idea why its not workinmg
not really. Its just not meant to be doing what you are trying to do. Its meant to be server authoritative.
do i need to get ownership add the force then give it back
it works with the normal networktransform
the serverrpc only one
but server authorative movement i added was SUPER laggy so i wnet back
rigidbody serverauthoriative movement seems to be bad
or atleast my implementation
yup. thats the trade off
terrible
The real solution is to make a client prediction system
all i need is this one thing to add force and i can keep client side movement 😭
can i get ownership then add force
then give ownership back
in netcode does the networkobject script keep a reference to the original owner
nope, it doesn't. but your code there should work. You'll need to make double sure that you have the correct rigidbody
how would i get the right rigidbody from just an id in a clientrpc
if i cant use connnectedclients[id].playerobject
just call GetComponent<rigidbody>()
thats probably your problem then
ok so i put this in the script with the rigidbody:
and the server rpc is in the playerstats :
u mean like this?
i can call a rpc on a different script with a reference correct?
this does not work either
it is running on the correct client
why cant it add force to itself?
its done 5 times in the same script
Oh, the serverRPC should be [ServerRpc(RequireOwnership = false)] If the other client is calling it. It should have thrown an error though
so can i use the first solution of just the server rpc and put that
tried both neither worked
might need to do networkTransform and make it all server authoriative and make player client prediction
ugh
@sharp axle found a workaround, i already have the isTagged network variable that is synced and works properly ill just make it so when its true it adds force locally idk why i overcomplicated things
List<ulong> playerIDs = NetworkManager.Singleton.ConnectedClientsIds.ToList<ulong>();
Debug.Log(playerIDs.Count.ToString());
foreach (ulong playerID in playerIDs)
{
Debug.Log(playerIDs.ToString());
Spawn(playerID);
}
what did i do wrong?
the list lenght is the same as the player amount
but all of the ids are 1 or so i think cus idk how to read this really
pls ping if you respond
nvm
it works but there is a issue somehwere else i find it
someone pointed that out already
the issue is somewhere else
im finding it now
i found whats not working
[ServerRpc]
public void StartGameServerRpc()
{
List<GameObject> spawnLocations = new(GameObject.FindGameObjectsWithTag("SpawnLocation"));
List<ulong> playerIDs = NetworkManager.Singleton.ConnectedClientsIds.ToList<ulong>();
foreach (ulong playerID in playerIDs)
{
Spawn(playerID);
}
gameStarted = true;
void Spawn(ulong playerID)
{
int spawnLocationID = Random.Range(0, spawnLocations.Count);
Vector3 spawnLocationPosision = spawnLocations[spawnLocationID].transform.position;
Debug.Log("PlayerId: " + playerID.ToString() + " was spawned at spawn: " + spawnLocationID.ToString());
NetworkManager.Singleton.ConnectedClients[playerID].PlayerObject.transform.position
= spawnLocationPosision;
Debug.Log("the posision of the spawn is: "+ spawnLocationPosision.ToString());
Debug.Log("the posision of the player is now: " +
NetworkManager.Singleton.ConnectedClients[playerID].PlayerObject.transform.position.ToString());
spawnLocations.RemoveAt(spawnLocationID);
Debug.Log("the count of the spawn list is now: " + spawnLocations.Count);
}
}
everything seems to work fine but the player with the id of 1 isnt moved
it has a clientNetworkTransform
code here
pls ping if respond
Only the owner client can move an object with clientNetworkTransform
not even the server can?
thats pretty stupid but alr i guess i do a clientRPC
You can be server authoritative or client authoritative but not both at the same time. There can only be one source of truth. Otherwise you end up with race conditions if the server and client try to move at the same time
alr then
can someone guide me about how can I make a local multiplayer game in unity which run over a LAN?
I am working with netcode but it's not providing me functionality to make rooms or lobby kind of functionality
for this its asking me to use unity gaming services like Relay and Lobby but these are making my game gloabl multiplayer
whereas I want my game to work over a LAN only
That functionality is not built into NGO. For LAN play you will either have the players enter the IP address manually or write your own network discovery system
Hi, does anyone now how to get the content of a string inside a Cloud Firestore document without nowing the name of a document? (1A2B3C4D-5E6F7G8H-9I0J1K2L should be a random ID)
An example path is:
**mails **(colection)
|- 1A2B3C4D-5E6F7G8H-9I0J1K2L (RandomID) (document)
|- **messages **(colection)
|- **message1 **(document)
|- text: "smth"
Ask gpt to provide a regex string for extracting the name and a c# code example for how to use regex.
I'm running NGO and trying to build a player class system.
I have a Player prefab that I spawn in, then I want to attach a Class (Warrior, Mage, ...) visual prefab to the player, but not sure how i'd communicate that via networking.
My first though is to Instantate the Player then the Class then parent the Class to the player, however that doesn't appear to work over the network, any thoughts on how I could do this?
how do i get the player object of the client the code is ran at
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:
Can someone please help me get backfill tickets to work in the Multiplay Matchmaker service? I'm trying to implement server backfilling but users can't return to the same server if they were disconnected. I'm using Matchplay sample (https://github.com/Unity-Technologies/com.unity.services.samples.matchplay) but re-implemented it with FishNet networking library.
I am starting backfilling loop with BackfillTicket.Id retrieved from the allocation payload. Default-Queue backfilling enabled and Equality rule enabled for userGamePreferences data in all players. Users can join once server already started. But can not re-join through Matchmaker if they were disconnected. Do I need somehow update backfill ticket when user leave?
string regexPattern = @"^[A-Z0-9]{6}-[A-Z0-9]{6}-[A-Z0-9]{6}$";
Id I told ChatGpt to use as example:
DBLG58-RFAJFA-6BFNDT
After a little reaserch on regex it generated this and I tried it on a regex test and it works, thx (I didn't know about regex strings)
you really shouldnt use chatgpt for regex, and be wary of any advice that starts with "ask chatgpt". Itll just be bad advice.
Firestore lets u iterate through all documents in a collection, you dont need to know the name of it.
https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
also this definitely wasnt networking related, i just really wanted to correct that advice
Thanks
where should I ask?
probably one of these: #💻┃code-beginner #archived-code-general or just #💻┃unity-talk
#🔎┃find-a-channel tells u what each is for
ok, ty!
Does anyone have an idea about this problem?
don't run it async run it blocking on the main thread. e.g. .GetAwaiter.GetResult
Note that even then you won't get a 100% guarantee. It will send over TCP but if the packet is lost the TCP connection will already be terminated, so in case of packet loss it will never arrive.
Yes even if I somehow send this web request it will not be 100% guaranteed.
So, how can a solution be applied in such a problem? As a result, every network-based game forwards certain requests and data to the servers at the time of exit.
No most games don't do that
Some do it simply to allow for faster disconnect instead of using a timeout
Sending data is pretty much never done.
If you do absolutely have to do that use a separate process for this. So that if they terminate the app you have as much time as you want to interact with your backend.
It is common to have a launcher and a game process for instance.
Frankly, what I wanted to do was send a request to the backed service when the user exited the game and indicate that the user exited. But as you said, sending data in an escape sequence is unreasonable.
But I still haven't figured it out, how can I notify the backend that the user has exited the game?
For example, by setting up a socket structure, I can send a request per second in the backend, the backend processes this request and understands that the user is still in the game, if the request does not come, the user is not in the game and acts accordingly.
I have such ideas in my mind, but I'm thinking how can I do this without using the socket and listening infrastructure.
How do you think I should proceed?
Got a question about NGO of which I couldnt find answers in the docs.
The .OnValueChanged action called when NetworkVariables are changed, is it invoked only on clients or also on the server? And im not talking about host mode
Same with NetworkManager.Singleton.OnClientDisconnected ...
Am I missing something in the docs?
I cant be testing every event on execution side
The clients and server should all be getting OnValueChanged events. You won't see it in OnNetworkSpawn though even if its been changed
For OnClientDisconnected, the one that initiated the disconnect will not get that event
thx
Is it common for multi-player fps games to do both tcp and udp protocols?
No, games usually only use udp or some custom implementation of udp
Usually udp for live gameplay and then either a rudp protocol or a tcp bichannel for reliable slow stuff like accessing backend services etc.
How can I check that a player is already connected on a client using the authentication service? I don't want a player to log into the same account through 2 different clients.
Probably use Cloud Save to save logged in status
How will I check that the player has exited the game? After all, I need to notify the cloud save side that the user has exited the game.
But I can't control the exit status of the game. Methods such as OnApplicationQuit do not work in communicating with these api services.
You can use the OnClientDisconnect callback on the server
Is this callback specific to cloud save service?
No its part of NGO
I made a lobby system using Lobby Service. Therefore, there is no NGO connection in my project at the moment. I plan to switch to NGO when the lobby functions and controls are completely finished. Can I do this without using NGO?
I guess you can tie into when the player leaves the lobby
I can check that the player has left the lobby, the problem is not there, my goal is to ensure that the same user cannot enter the game with 2 different clients.
Right, use cloud save to store when a player enters and exits the lobby
How do the length in ms that it took for a server to recieve a serverRpc from a client after its invoked, been struggling this for HOURSSS
i need this so that i can adjust a projectile position based on the time difference in ms so that the bullet is synced
You should be able to subtract local time from Server Time
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networktime-ticks/
LocalTime and ServerTime
this seems to work
what im doing rn is taking the server time on the client, sending it to the server, and then subtracting the servers server time from the recieved server time
is that accurate?
im tryna adjust the projectile position on the server
no need to send it the client has access to NetworkManager.ServerTime.Time
Oh wait I see what you mean. Yea that should work.
do i need to divide it by 2 maybe cus my prediction is still off
especially with gravity
where gravity is -9.8m/s im taking the value of gravity and multiplying it by the calculated latency (serverTime - RecievedServerTime) and it ends up very loww when spawning it
nvm im dum
Anyone managed to get Unity Transport 2.0 running?
Keen to check out the websocket stuff they have
ok ok
but how can I make this
like which unity services I should use or I have to make an ASP.NET kinda project
basically I am quite confused
For a lobby sort of thing you can use pretty much any transport that is both supported in regular C# and Unity. C# provided networking should work on most desktop platforms. HTTP, TCP... UDP.
What's the best way to handle projectile shooting for a 2d top down game using Netcode for Gameobjects? I'm using rigidbodies on the projectiles but they are lagging, for the client they despawn way before they visually hit the enemy
I thought about shooting a dummy projectile locally, but I don't know how to "connect" it to the server side bullet so it gets destroyed when the server bullet hits something, also I don't know how to hide the server bullet for the local player
The server projectile wouldn't have any visuals to it. With this method they don't even need to be network objects really. Since its all local. You would need to send an rpc when the server one collides with anything.
If the server object has no visuals, how will other players see eachothers projectiles?
Just by calling a ClientRPC that someone shot a bullet and spawn it locally for the others aswell?
I want to make players faster when they are close to eachother, why does this script only work on the host?
The other player's speed stays normal while the host gets faster
basically yea. you could also use OnNetworkSpawn for that invisible projectile
I got it working for now, do you know what the problem on the image is?
only the host/server can change other clients like that. You would probably need to send a clientRPC to change the speed of the other players
I changed it to this and it still only works on the host
I'm so confused rn
Oh, Looks like thats on your player. I would have a separate Player Manager that can control the speed of everyone.
I can try that but why does that script not work?
Only the host/server can call client RPCs. The other clients would have to call a serverRPC that would call a client rpc
public override void OnNetworkSpawn()
{
if (IsServer)
{
var rpcParams = new ClientRpcParams
{
Send = new ClientRpcSendParams
{
TargetClientIds = new[] { MatchManager.PlayerB.ClientId }
}
};
FlipClientRpc(rpcParams);
}
}
[ClientRpc]
private void FlipClientRpc(ClientRpcParams clientRpcParams = default)
{
if (IsOwner) transform.Rotate(0, 0, 180f); //player does own
}
can someone explain why transform.Rotate() doesnt work? I get an error saying "Deferred messages were received for a trigger of type OnSpawn with key 16, but that trigger was not received within within 1 second(s)." if i try to rotate from the clients editor it works fine
i also tried calling Rotate from OnNetworkSpawn as client and nothing happens
so i moved the clientrpc call to start and it works but im still getting the error
Is there a JSON-RPC library out there for Unity?
Ok so I have this system here which moves the player cs private void FixedUpdate() { if (!IsOwner) return; PhysicsServerRpc(); } [ServerRpc(RequireOwnership = false)] void PhysicsServerRpc() { rb.AddForcAtPosition(Force, pos); }So the issue is that the host can move its gameObject, but the client can't. The gameObject has a network object a network transform and a network rigidbody thingy on it.
where is Force and pos calculated?
pos is just transform.position and force is a constant value
Do you have a network transform, or did u use some client network transform?
network transform
just curious is there any reason u are using RequireOwnership = false, when only the owner should be calling that rpc? I would probably still recode this to have the host run the movement code, but the owner sets a network variable to say what their input is
Or maybe show the full script, because i think there might be some other code causing this issue then thats not being shown
no not really, I just did it anyways
I can tomorrow now I gotta sleep
briefly looking around it seems theres several methods for hooking up multiplayer, i am a pretty noob dev, looking to hook up basic multiplayer for pvp and coop game play 2-4 ppl any suggestions on assets that would simplify this?
check the pinned message here for Resources
So I am confused how I should do input?, So I managed to sink up the moving gameObjects using network transform and server rpc's. But now that I wan't to make the player control the gameObjects using this: ```cs
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");
I fixed the sinking up ther movement properly now, and yes it was becaues of something else in my code thanks^^ Now I just gotta get input working
I use network variables for input, then the host moves everyone based on these variables.
for example
NetworkVariable<Vector3> movement = new(writePerm: NetworkVariableWritePermission.Owner);
NetworkVariable<bool> jumpMovement = new(writePerm: NetworkVariableWritePermission.Owner);
and where how do I set the movement variable?
simply like this? cs movement.x = Input.GetAxis("Horizontal"); movement.y = Input.GetAxis("Vertical");
You set networkvariables slightly differently, and u want to make sure only the owner is trying to set them
you should experiment with network variables first to understand how they work, the doc has great examples
Also you would have to provide it an entire new value, u cannot edit the x or y
movement.Value = new(x, y, z);
ye I noticed
and inputs working now, wooo^^, thanks mate
np
hey can I ask you one small other question is there any obvious reason why my mutliplayer doesn't work when trying to play with people on another internet
Hello guys, I just have a problem with NetManager script (2022.3.3f1, NetCode for GameObjects 1.5.1) I can't for the life of me add the player prefab in the network prefabs list. It's a known issue?
just ask the question, either here or netcode discord. someone will answer, im still new to netcode
you need to add that player prefab into a "network prefab list" then add that list asset into that slot on the network manager.
one should be created for u at the assets folder by default, but if not you can still create your own
I understand that I have to add the playerprefab into the network prefab list in the network manager, I cannot do that for some reason.
the network prefab list is an asset that you create or use the default created one, you do not plug the player prefab directly into the network manager
i plug this asset into the NetworkManager
hey is there any obvious reason why my mutliplayer doesn't work when trying to play with people on another internet
Make sure the player prefab has a network object component
I resolved it by using NetCode for GameObject 1.2.0
Hello freinds,
I'm looking into the netcode for game objects stuff and I'm looking at messing around with some client only objects but I've ran into this:
Where despite IsOwner being false it still enters the code block, am I missing something here ?
Nevermind it eventually decided to read it correctly 👻
Timing is different for in scene object. Start will run before the objects actually spawn
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:
How can I despawn an object on collision with a player? I can't just destroy it via GetComponent<NetworkObject>().destroy because only the server can do this, so how do I pass a gameonject as a serverRPC parameter?
I use this script that is attached on the player, but it only works for the host player gameobject and I cant figure out why
When an enemy collides with another player other than the host it seems like the OnCollisionEnter wont even get called
How would I be able to use a dedicated server to host my game? Like how do I set it up and is there any third party services used such as mirror
it's a little late, but you could have it in your enemy script
//enemy script
[ServerRpc(RequireOwnership = false)]
public void enemyDestroyServerRpc() {
Destroy(this); //or whatever you want to use to destroy
}
//in the playerscript
...
enemy.enemyDestroyServerRpc();
this way you don't have to pass a gameobject, since you are executing it on the gameobject you want to destroy
Not too late, I've given up yesterday haha, I'll try that later :D
Alright so I've tried it, and it works again only for the host, this time I've implemented debug logs and for the clients it doesn't even call the "OnCollisionEnter called"
I don't get why OnCollisionEnter is only called on the Host, I've tried moving the collision logic to the enemy (Server Side) but that also only works for the host
And you have a debug console on/in the client? Otherwise I couldn't explain why it wouldn't call collisionentered
I use the game build as the host and unity's editor as client
Hmm that is odd. Depending on what you are doing you could try using a triggercollidrr instead
That is what I mostly do, my weapons have trigger collider which I activate and deactivate depending on the state of the attack, it works for me on clients and the host
If you are using Network Rigidbody, then only the host/server will get collisions. Triggers will still work on both
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/#networkrigidbody
There are many different ways to do physics in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.
Oh than that's the case, I already thought of that and I thought putting the logic on the enemy which is only calculated on the server would fix that
i am using netcode, i have a tool network prefab and a ragdoll (also a network prefab, with multiple rigidbodies). How am i supposed to parent the tool to the hand of the ragdoll ? (it doesn't allow me because i cannot parent a networkobject under a non-networkobject). (but i also can't make the hands networkobject, because then the prefab would have nested network objects)
Had a similar issue, the awnser is you don't. Why would you want that in the first place, have the object as a local gameobject and spawn them on each client, via a script you can call a toolmanager for example. Via a networkvariable you can also ensure, that late joiners will see the spawned tool
Everything else would result in a nasty solution. I even tried havig a point on the hand which the objekt tracks, but that results in latency problems, have it local and you are good to go
thanks
Hey guys where should I start to learn networking I got pointed over here but I'm ngl I don't understand what you guys are talking about 😓 should I use fishnet?
If I were you I would use NGO or Mirror. NGO is the official unity one and has good documentations, as long as you stick with it. Codemonkey has great videos on how to start and the docs are great as well
If you want to go with third party go with mirror it is used a lot, has a big community and a lot of ressources. Afaik are Mirror and NGO similar enough to learn either one and just transfer the conecepts (the keywords will be different tho)
So use Mirror if you want great ressources or NGO if you'd like to use the unity one and have great ressources but not as many
One NGO issue is that you only can use ressources from 2021+ but you will find older deprecated awnsers
I've never really worked with mirror tho
I read NGO is built for small scale multiplayer, but technically it can handle a lot of players too.
So, what is the worst that could happen if 200+ players join at the same time to the server with NGO?
that depends on how complicated your game is, but 200+ moving networkobjects will result in massive latency
but if you are thinking on 200+ players on one server you will be better off writing your own solution, which can handle load balencing, anyway
I am super new to unity networking.. I want something like this, A player will be in a room but in VR, another player will change the environment or interact from a computer. How do I achieve this.... from where do I start?
So, A player will be in a room (or scene) where he will be a in VR mode and look around. Another player will be on a computer who will change the walls and paintings of that same room. The player who is in VR will be able to see the changes
That is kind of tricky, if you are new.
So first you need someway to decide beforehand who id the vr/desktop player. You need to give them a different player prefab or have the same with some internal logic to switch. After that it mostly sounds like spawning networkobjects. You may need a few networkvariabled but nothing too fancy.
How about implementing the core gameplay first. So two players on desktop which can manipulate the walls, you can achieve that part with the docs I think
And think about the vr part later, when you allready have somekind of structure. For example some kind of logic which changes the player prefab when in vr
Don't think about the whole thing just yet. Start by solving a small problem, like getting a multiplayer game run at all -> having a player to spawn/manipulate objects -> snyc it properly -> vr implementation
With PC VR you technically don't even need networking for this to work.
If the players are not in the same location then networking will be needed. It's still fairly straightforward but yea learn networking bits first. When you can work on connecting it with VR.
I have an issue trying to implement item data synchronization. I have an ItemBase class, than i have some other classes that inherit from it. Firstly the player has a networkvariable of type FixedString64 that is basically the name of the class derived from the ItemBase. Than i have an ItemManager singleton, which contains links between the prefabs for the items and the FixedString64 type name. Some items have consumption property etc. I also need to synchronize these. I tried using INetworkSerializeable and i just cannot, because there is no struct inheritance and i cant use a base struct type for the player item variable. I thought of jsonserializing some properties in a FixedString, but i cannot find another workaround outside that and making a struct with all the possible properties for the items.
If the items are not procedurally generated, you can just send an item index to your item manager to get the consumption data.
the item manager only holds the prefabs for the items
not the consumption data, that needs to be synced
I see. I use scriptable objects for my item managers
the items are also mono, not networkbehaviours, so i cannot use networkvariable
Do networkvariables sync before the execution of OnNetworkSpawn()?
For instance, before P2 joins, P1 made the NetworkVariable integer value to 1. When P2 joins, will they see the value already changed to 1?
it should be synced before network spawn
How do I make a networked equivalent of Time.deltaTime?
Simply putting NetworkManager.LocalTime.TimeAsFloat seems to just blast things away when I try to move them by code
it's like they're super fast
don't know what you are trying to, but why not just use the delta time of the host? I don't know if there is something similar, it wouldn't make much sense, since delta time is the time between frames and that is not global, the host could play on 60fps while a client may be playing with 240fps, they would have different delta times. If you use the host one it wouldn't matter tho, since if you do the math for one second of movement, the deltatime falls out
it works because of what you are trying to say by mutliplying with deltaTime, "i want to move k units in the directions x, y, z per second"
Oh sorry I forgot to tell
I'm working on a tick-based character controller
when I multiplied everything by Time.deltaTime the speeds weren't consistent on different frames per second
I'm using a client autoritive network transform and just multiply with the local deltatime on the client. Everything else was too much latency for my taste, maybe someone else can help you.
And yes you multipy by Time.deltaTime so it is not different with different fps
The network time system on the network manager has a delta time that represents the time of one tick you can use.
i have a problem with photon networking, when i get a list of all the players using PhotonNetwork.PlayerList() it sends back the player but then when i get the UserID of the player most of the time it returns null and other times it only returns the master client, does anyone have a fix?
Guys, what does exactly is NetworkBehaviourId? Is it the same thing as NetworkObjectId? Ultimately, my question is, if i want to have the server tell the client "this is the NetworkBehaviour", how should i do it?
You would use NetworkBehaviourReference
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#networkbehaviourreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
@sharp axle Ooh thank-you i missed that, exactly what i need !
Does anyone know why unity would be unable to connect to 000webhost from a different location? it works fine at home, but if I would go to, for example, the library, unity doesn't want to connect. if I put the link straight into google it works though.
(I know this isn't the exact place for this question, but I don't know where else to ask.)
idk what to do. yes the player has network object. whats wrong?
Don't have NetworkObject components in child gameobjects of a NetworkObject gameobject
worked, thanks
can i open and close this url by using UI button in uinty
or open url in unity but close from web
Forgot to mention but the error that pops up is cannot resolve destination host.
ive recently started using coherence networking and i get the issue where i have two players in the same lobby, but their character controllers are swapped (player 1 controls player 2 and vice versa). does anyone know how to fix this?
ive come across this issue while using other networking software as well, but im stumped on how to fix this issue in coherence
I'm getting the strangest ClientRpc bug where a few of my functions will only ever execute on the host and never any connected clients. Its consistently a select few but I can't tell any difference in the code compared to other ClientRpc calls
First debug log image is host, second debug log image is connected client
Where are you calling it from?
I'm calling it from the host
its inside a NetworkBehavoir object as well, same object as all my other ClientRpc functions
whats even more strange is that the first time the function is called (spawning the player the first time), it actually does fire on the client, but any time its called again for respawning it doesn't happen
The function is only ever called from that one line of code though
so maybe its like..... hung or something? The client isn't frozen its executing everything else fine but idk if this could be something about having only one function running at a time
Is the clientRPC actually getting called the 2nd time? If it's called the message is getting sent to all clients
Yes because the debug log happens on the host the second time
Is this on the player? The object is probably disabled on the client.
No, this is on a central game manager object
its still calling all other ClientRPCs, like the Damage one which you can see in the images debug logs on both sides
Dunno. Check the network Profiler to see the rpcs getting sent and received
There's a problem with my spawn system
Left side = host
Right side = client
Client's body is doubled and the movable body isn't visible to host's POV
public override void OnNetworkSpawn() {
base.OnNetworkSpawn();
GameManager.RegisterPlayer(GetComponent<NetworkObject>().OwnerClientId.ToString(), this);
SpawnPlayerServerRpc();
}
[ServerRpc(RequireOwnership = false)] private void SpawnPlayerServerRpc()
{
if (!IsServer) return;
if (spawned.Value == true) return;
spawned.Value = true;
SpawnPlayerClientRpc();
}
[ClientRpc] private void SpawnPlayerClientRpc()
{
body = Instantiate(bodyPrefab, Vector3.zero, Quaternion.identity).GetComponent<PlayerNetwork>();
if (IsOwner) SetupLocalPlayer();
RequestSpawnServerRpc();
}
[ServerRpc(RequireOwnership = false)] private void RequestSpawnServerRpc()
{
body.GetComponent<NetworkObject>().SpawnAsPlayerObject(GetComponent<NetworkObject>().OwnerClientId, true);
}
adding if (IsClient) return; to RequestSpawnServerRpc() solves the duplication but now they can't see each other because the networkmanager can't spawn the networkobject because it doesn't recognize the hash
How my planned architecture should work:
- NetworkManager spawns empty player instance prefab that has the
PlayerInstancescript (the one that spawns the actual body) - Inputs and local player initialization happens at the player instance's
PlayerInstancescript
Why separate inputs and the bodies from their instances? I made a "dynamic" object controlling system that uses an interface calledIControllableso whatever is inPlayerInstance'scontrolledObjectshall be controlled by the local player. This is so I can make it easier to implement vehicles later on. - Actual bodies of the players are mere "puppets" and are controlled by those instances
PlayerNetworkhandles the synchronization of the bodies
PlayerNetwork works fine so I don't have to send it, the issue comes from this
Help would be immensely appreciated, I've been scratching my head over this for a day
hello is there problem here ? to load scene to all players photon.pun
if (PhotonNetwork.IsMasterClient)
{
string MapName = DropDownMap.options[DropDownMap.value].text + "Online";
PhotonNetwork.LoadLevel(MapName);
}
edit ( i should've called this line "PhotonNetwork.AutomaticallySyncScene = true;")
can anyone tell me what is the better networking system photon or mirror or if any one wanna suggest something i wanna make arcade style car game
can anyone help me out? Ive been working on an android app that is pretty much all just UI, and i was just working on some scripts and now, for whatever reason, i cant click anything in-game
i think it might be related to multiplayer but i literally have no idea what's causing the issue, what should i do?
kinda freaking out :,)
like everything was fine and then, next thing, im compiling the game for the 1000th time and now its like the game isn't even listening to any inputs
You should roll back you source control to the last working build.
There is probably a panel or something on top of everything else that is blocking inputs
They are different products with different feature sets there isn't just a better one. Also Photon has many products, Fusion, Quantum, PUN etc. I'm from Photon so my oppinion will be biased. I suggest you get familiar with the differences between the solution and then decide what's best for you.
I'm making a MOBA game and ran into a problem that the client when attacking creates a lot of projectiles without taking into account the attack cooldown and i cant understand why. On host everything works fine. I using Netcode For GameObjects.
Full code (if it can help)
You should check for CanStartAttack on the server and handle to cooldown there. Not only will that likely solve your issue it will also protect you from cheaters spamming an attack RPC and ignoring the cooldown.
you mean "mark" MoveAndAttack as ServerRpc method?
I guess there is a fundamental question on whether you want server or client authority.
Most MOBAs (LoL, DOTA) use server authority. So the only thing the client does is send the inputs (where to move, what attacks) to the server and the server runs the full gameplay code
Hello, im making a turn based 2 player game, need help/suggestion regarding pause mechanic.
I'm using photon pun 2 for networking
Game needs to be paused for both players when
A) either player has weak internet connection
B) either player has minimized the game/on application lost focus
Issues I'm struggling with
A) how do I know if other player has weak connection
B) how do I check if the other player has regained stable connection? Can't recieve RPC callbacks if game has timescale=0 using pause mode which I realised too late. So that brings me to my third point
C) how do I pause the game on the go when either condition is satisfied, like in middle of a coroutine and tweens
I'm working on a 3d multiplayer game using Photon Fusion, but the rotations aren't being shared even though my player has a Networking Rigidbody, anyone know why that could be?
It means you are not allowed to call that function. Don't know what networking solution you use, so search up ownership and autority for your networking solution
Hey guys, I'm trying to get some netcode working for guns, does anyone know how to send a list of floats (for timing the shots between ticks) from client to the server?
i dont see the gun from my opponent.
after removing the network object from my gun. i dont get this warning but dont see the gun?
You can't spawn a networkobject as a child from another networkobject
i saw that thanks. but im not seeing the gun
There are networklists if that helps
Remove the network obj from the gun itself, should be fine if you give it a net transform
I found a work around, basically I coded a little decoder doohickey that just converts a string into a list of floats, but now I have another problem, why is Update called once per frame on the owners side but only once every tick on everyone elses 🙄
(I mean Update in network behaviour)
Oh you removed it than it only spawns localy, probably on the other client.
You can have the parent object to be a networkobject and handle the spawning in clientrpcs on every client locally, the transform can be synced as well this way
i added network transform. still not seeing the gun from opponend. and a new "problem" appeared. the gun on player 2 is slowly following the own player. while player 1 is normal
Is your movement client authoritative?
Oh yea that is the latency problem. It needs to be client authoritive in order to work properly
Should only be an issue if their movement is client authoritative and the gun is now server authoritative
Does anyone know how to call a function as the owner once every tick update and NOT every frame update?
sorry I really don't know networking
Can't help you never experimented with that sorry. Never even noticed a difference
damn. 😔
u mean the playercontroller if theres Authority?
Do your players have client network transforms and update their own location
Or do they have network transforms and the host moves everything
True. The movement of weapons is based on animations most of the time anyway, therefore just syncing the animations and let them handle the movement is one of the best approaches in my opinion. It works for my game atleast, it is third person tho
Then your gun should be client network transform as well
ok the problem is solved. still not seeing the gun from opponent lol
If its spawned in with the player prefab it should be there, how are u spawning it in?
On mobile it's hard for me to see your setup from the screenshots tbh
it just spawns after clicking host or client. i dont have spawnpoints for player
yes i spawn playerprefab
That should be fine then since it's under the player prefab
It would spawn the same any other object
Although I wouldnt have it under the cam
under sphere?
Depends what the sphere is, but sure
sphere is just sphere nothing else
Your camera may act weird in multiplayer, so you may have to disable it for other players
Isn't the cam disabled on the other players? Which would make it impossible to see it?
Not by default, you have to disable it yourself
I thought he did that otherwise it makes sense he can't see it because he has the same perspective on client and host
The perspective mightve been fine still
after puting the gun under sphere. i see the gun from opponent. but when i look up and down. the gun doesnt follow it
They should really add the camera thing in the getting started part in the docs
It is so easy to miss and causes a lot of problems
I believe it's like one person working on the docs, but honestly they dont need to add it. Not every game uses multiple cameras
You can simply handle it via a script, just setting the rotation like the camera rotation
the gun via script?
What are u trying to do?
For real? I thought is was a whole team, huge respect to that person.
Don't a lot of multiplayer games have the camera in the player prefab?
or in playercontroller
Depends where you want to place it, I would put it in the player controller, since it is not part of the logic for the gun but controlling the player
Just set the gun rotation to the camera rotation. That what you did before when having it as a child of the camera
not like one literally, (at least I think), but you can see who made a page on the documentation at the bottom. there arent too many different names
basically, I am storing a couple of floats between ticks to synchronise the timing of a gun firing between clients
basically
I store a list of floats
these represent different time intervals between ticks when a gun was fired
and then uhm
if its a network list it will sync by itself
yeah on the other client it lerps between them basically
I made a system to store it in a string
just use the given functionality, store it in a network list or variable then
but I need to clear the string once every tick update on the owners side not the server side, but in networkbehaviour update is called once per frame and NOT per tick (on the owners side)
you cannot store a string in a networkVariable, itll have to be like FixedStringXBytes
god damnit
im unsure why you would be doing this honestly, the owner and server arent 100% synch'd in real time
idk its hard to explain like
I want the network code to work well even at a very low tickrate like 10TPS
so I store a bunch of floats which are basically timestamps between ticks to know when to fire the gun on the other clients side
idk I didn't find another way to sync gunshots online
so this is the thing I came up with
its likely you really just want networkvariable or list, which will update when the value is changed and also send an event
I swear I tried using a list before and it gave me compile errors its like a separate thing a network list right?
public Transform weaponTransform;
(under Update)
weaponTransform.rotation = Quaternion.Euler(0f, kameraTransform.eulerAngles.y, 0f);
weaponTransform.position = kameraTransform.position;
after adding this the gun is far away and rotated
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/index.html
scroll down for network list
but also you may just want client side prediction then for the player to shoot when they think they should, and the server correcting. Im not entirely sure though, i havent done a shooting game.
I honestly do not know why that happens, the camera transform shouldn't be that far away
ill ask it in beginner code channel. thanks!
ok thanks I'm gonna try figure it out I've been tryna do this for so long now 💀
What happens if you leave out the position?
it follows me. but still not vertical (looking up and down)
But you set the camera transform and it only executes locally?
You can also try Camera.main.transform, which gives you the transform of the active camera
you mean adding "main" between camera.transform?
"Camera" is the class
"Camera.main" is the reference of the current active camera
And "Camera.main.transform" gives you the transform of the camera
now i get this
Can you send the script? I know it works for a friend in unity 2021.3
https://gdl.space/ifocusidem.cs
sry for the comments and the name (german)
I'm german as well
You have: camera.main.Transform.position
It needs to be:
Camera.main.transform.position
still doenst work but new errors nice
Ok well than nvm
Thought it just uses the main camera doesn't seem like it. I honestly would have to experiment as well
Couldn't you just do
weaponTransform.localRotation = Quaternion.Euler(blickNachOben, 0f, 0f);
In line 70, the sameway you set the camera rotation in line 69
Oh the vertical axis is line 65 not line 69
shows this now
is that safe?
It tells you that the code in line 89 isn't supported anymore, so probably just comment it out
Hey guys I'm still having this problem, as the owner of a network behaviour, how can I call a function after every tick?
like how do I as the owner of a network behaviour keep track of ticks?
You can subscribe to NetworkManager.NetworkTickSystem.Tick
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networktime-ticks/#network-ticks
LocalTime and ServerTime
tysm man I appreciate u for that this is exactly what I needed
so theres this object in my scene that i wanna deactivate im using netcode the servers already in the scene its not spawned by anyone so ig the server owns it i think only the server can disable it if someone else tries to do it it doesnt work is there a way i could somehow request the server to delete it and then update it for all players?
I'm using the Lobby Service and I have this code to get a list of lobbies:
public async Task<Lobby[]> ListLobbies()
{
Debug.Log("Gonna List lobbies");
try
{
QueryLobbiesOptions options = new QueryLobbiesOptions
{
Filters = new List<QueryFilter>{
new QueryFilter(QueryFilter.FieldOptions.AvailableSlots, "0", QueryFilter.OpOptions.GT)
},
Order = new List<QueryOrder>{
new QueryOrder(false, QueryOrder.FieldOptions.AvailableSlots),
}
};
Debug.Log("Options instantiated");
QueryResponse queryResponse = await Lobbies.Instance.QueryLobbiesAsync(options);
Debug.Log("Got lobbies list with size " + queryResponse.Results.Count);
return queryResponse.Results.ToArray();
}
catch (LobbyServiceException ex)
{
Debug.LogError("Failed at Listing Lobbies + " + ex);
return null;
}
}
For some reason, Unity itself is crashing at QueryResponse queryResponse = await Lobbies.Instance.QueryLobbiesAsync(options); when there are available lobbies
You can call a serverRPC for this
Any suggestions appreciated
I am making a basic FPS game for learning multiplayer
I am facing an issue whenever other person(client) hit and kill the host player
relay server turn off game for all
how can I fix this issue
like how can I migrate host
or is it a good approach to destroy a player completely or just have to despawn it?
Don't you just reset the health and change the position of the player while respawning? I always thought that is how it gets done
Destroying the player should not kill the connection under any circumstances. There is something else going on there
Yes!
I did something similar
I wrote a script and turn off necessary components and on respawn I turn on those components
serverrpc only disabled it for the server i used a serverrpc then called the client rpc to update it for every player it worked thx doe
also does anyone know how can i load the main menu for every player on game end or disconnect?
any idea why my POST request is not working?:
IEnumerator SendAPIPOST(string jsonOBJ)
{
string postData = jsonOBJ;
using (UnityWebRequest www = UnityWebRequest.Post("https://localhost:7248/api/values", postData))
{
www.SetRequestHeader("Content-Type", "text/json");
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
{
string responseBody = www.downloadHandler.text;
Debug.Log(responseBody);
}
else
{
Debug.Log("Request failed with error: " + www.error);
}
}
}
API:
[HttpPost]
[Consumes("text/json; charset=utf-8")]
public async Task<ActionResult<string>> Post([FromBody] MyDataModel data)
{
if (data != null)
{
string response = $"Received: Name - {data.Name}, Age - {data.Age}";
return response;
}
else
{
return BadRequest("Invalid data received");
}
}
whatever i do, i get the "HTTP/1.1 415 Unsupported Media Type" error in unity
Hey guys! I'm new to Unity but experienced in C#. I'm using Netcode for Game Objects, Lobbies, and Relay to network a simple turn-based game.
ServerRPCs receive and validate player actions and update a NetworkVariable<GameState> to sync clients. GameState implements INetworkSerializable, and has complex logic in NetworkSerialize - it's sort of a heterogenous circular linked list of structs.
This is not a lot of code and I feel I'm on a good track - but the process of starting two players, connecting, attaching debuggers, Debug.Log-ing etc is extremely tedious, and doesn't lend itself to detailed experimenting.
So I have a few questions, and welcome any guidance:
- Are there are any good resources on testing netcode? Anything with a faster feedback loop than building & running multiple players?
- For testing INetworkSerializable specifically, is it possible to get a BufferSerializer instance realistic enough to use in a "serialize -> deserialize -> assert" test? I can't instantiate one because the constructor that takes an IReaderWriter is internal, and I can't extend the struct because it's sealed. I could implement IReaderWriter myself, but it's large, and at that point I lose confidence that the test behavior will match runtime.
- Is there a better place to ask in-depth questions like this? The official forums seem kind of dead, but maybe stack overflow, GitHub issues...?
Thanks for reading and for any help you can provide! (originally asked in #archived-code-advanced)
- parrel sync is pretty good, there is also the unity multiplayer play thing but havent used it.
- not entirely sure what you want to test with INetworkSerializable but maybe you can subscribe something to a network variable
GameStateVariableName.OnValueChanged += SomeMethod;
method
void SomeMethod(GameState oldValue, GameState newValue) - The Unity Multiplayer Networking discord in the pins has more activity than here. Though overall, since theres many things to use like mirror, pun2, and ngo, the community is probably spread thin
Thanks! I'll give parrelsync and multiplayer play mode a try. your suggestion for #2 is what I'm trying to do, and it works when running multiple players and testing manually, but I was hoping for something I could do from a unit test
I was trying to think as well but the easiest thing would probably be taking the variable from the method and passing that into a unit test somewhere. Only problem really is that you need something to compare it to
why doesnt it update when helath is changed?
Theres a photon discord linked in the pins
My player keeps on teleporting to walls and sticking in corners until I click on it in heirarchy/inspector, then it works fine
any reason why this might be happening? (player is physics based) (Netcode for game objects)
still need help here, if possible. I know it`s not strictly photon, but idunno where else to go.
in unity mirror networking how can i assign authority to non player object?
anyone know if this code would work? im kinda new to this
I'm trying to give player "roles" in my game.
{
// Add the connected client to the list
NetworkClient client = NetworkManager.Singleton.ConnectedClientsList[clientId];
connectedClients.Add(client);
// Check if the number of connected clients is equal to or greater than the desired number of clients to assign roles to
if (connectedClients.Count >= numberOfClients)
{
// Shuffle the connected clients list
ShuffleClientsList();
// Assign roles to the selected clients
AssignRoles();
}
}
// Called when a client disconnects
private void OnClientDisconnected(ulong clientId)
{
// Remove the disconnected client from the list
NetworkClient client = NetworkManager.Singleton.ConnectedClientsList[clientId];
connectedClients.Remove(client);
}```
How can I get an object that was spawned at StartHost or StartClient?
anyone have any idea what could be causing this error when trying to connect to steamworks?
k_ESteamNetworkingConnectionState_ProblemDetectedLocally
google tells me it usually has something to do with a version mismatch, so I made sure both clients are running the exact same build
a few comments also made me think it's an error you get when you try to connect both a client and a host on the same network, so I hotspotted my phone to my laptop to try that instead. no success
it seems its a super obscure error code that doesnt have much documentation
full log here
https://pastebin.com/9AubPMu1
why do my bullets dissaper instantly insted of waiting till the time is done?
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.
ps:i m not getting response from photon disc pls help
how do i get steam profile picture with steamworks?
Hi, I need to associate an HUD with a character. To do this I use my method (which returns the Player type) to return a local player object.
public static Player OwnPlayer()
{
return Singleton.LocalClient.PlayerObject.GetComponent<Player>();
}
In Player, I Instantiate the character and write it to a variable. In the Player panel script (when connected), I write the player to a variable and pull the character from there to display his data on the screen.
private void OnPlayerConnected(ulong playerID)
{
if (player != null) return;
player = NetworkOwnManager.OwnPlayer();
Debug.Log("Finded: " + player);
}
On the server (host) everything works fine, but on the clients the link to the spawned character comes out null. Did I do something wrong?
Player class: https://pastebin.com/zkK3SHFS
yeah, p2p cuts out the middleman, which would result in lower latency. Does lag compensation refer to a specific method?
no theres multiple methods for lag compensation
for grenades you can most likely look up rocket / bullet lag compensation methods
okay, thanks a bunch for your time. I now have a solid idea of how to do this, just have to figure out the lag compenstaion part.
but p2p is a communication type, yes a side effect is lower response for things like that but its not the main purpose of p2p
ah i see
truthfully, 50- 100 ms of latency would be acceptable in my case
is that what i can expect from server authortative?
depends totally on where your server and client are
if they are in the same room expect <10ms
if they are in asia and us >200ms
ok, thanks a bunch
one method that you can use:
- Sync a timestamp on client and server
- Server tells client the grenade was thrown at timestamp x
- Client simulates the flying curve with the offset of the current time to the set timestamp x (like skip the ms that were missed)
instead of the synced timestamp you can use the ping if your networking library tells you that and check when the packet arrived, move timestamp back by the ping, a bit more unprecise but possible
so, since the client would be ahead of the server, you're moving the client's grenade back to match the server?
lets assume 50ms ping and 0 processing time
Client that throws grenade: timestamp 0, animation runs normally
Server gets the packet after 50ms: starts the animation 50ms in and tells clients a grenade was thrown 50ms ago
All other clients get the packet after 100ms: Starts the animation 50ms (what the server said) + ping ms in
makes sense I think
also the client that throws originally is a prediction, if the server has any other data the client should correct with a rollback, but thats more advanced 😄
oh you mean, server side reconcilliation?
dont know that term 😄
That was my plan for covering the physical movement of the players
(last question) I don't want to waste any more of your time, but what do you mean when you say starts the animation 50 ms (what the server said) ?
the server knows it received the package after 50ms
so it tells the clients "i got the grenade package 50ms ago, please offset the grenade throw by that + your ping"
oh okay, thanks!
so the pro of this approach is that the grenade is essentially in sync in every client's position
yep, but its a bit complicated 😄
also what plays in your favour would be a granade throw animation
so the granade is not actually flying while the clients sync up and you dont skip airtime
smart
Help-me for Unity Netcode for Entities!
I would implement multiplayer before you build to many systems/features. Preferable if you start from beginning but sometimes you might want to build a prototype and then add multiplayer support to reduce cognitive load. Esp if your prototype/feature is not working out and you want to scrap it. Not all systems would be treated the same obviously like some things really do not have much need for multiplayer and are client side only or what not.
If your following tutorials it might be easier to build said system from tutorial and then see how you would rewrite it for multiplayer after? It’s always easiest to implement from start and keep adding network events or what not as you go. It all piles up quickly if you don’t I think.
Plan in the beginning
what do people use to make users accounts in some sort of could service and save/load whatever data I want from them admittedly I didnt look up anything yet but would like to hear whats good for others to maybe save some trouble
Unity has its own player account system that recently went into open beta. But there are others like Steam, Playfab, Lootlocker that also have things like friends list, achievements, and in game purchasing
If a client instantiates a network object, is that network object automatically instaniated for all other clients or no?
a client can't instantiate a network object or to be more specific, it can instantiate it, but not network spawn it, which is the necessary part for it to be synced so no
A workaround is handling all of that in a server rpc
Okay, so just because something is a network object doesn’t mean it is automatically synced, it just has networking functionality
I mean it can't be synced if the server doesn't know about it
Yeah, I had assumed that but I saw something that made me question it
Is there any reason to make something a network object if you won’t be directly sending any rpcs to or from it?
this is how I spawn stuff, it requires you to write 2 more classes tho
[ServerRpc(RequireOwnership = false)]
void buildServerRpc(Vector3 pos, Quaternion rot, string name) {
//Item is a class which holds a prefab and some values, ItemDict is a global Item Dictionary
Item currentItem = ItemDict.instance.getRegisteredItem(name);
GameObject toSpawn = Instantiate(currentItem.prefab, pos, rot);
toSpawn.GetComponent<NetworkObject>().Spawn();
}
syncing positions with a network transfrom for example
This looks kind of like what I have right now
Is it okay to not use a network transform and instead have the server update positions?
it depends on what you are trying to achieve, but that should be fine for most cases
the network transfrom is just a shortcut
Okay, thanks for the help!
no problem
Oh sorry I do have one last question. In your spawn approach, does the same gameObject on two different clients scene have the same reference or the same NetworkObjectid?
I never tested it, but it should be, I mean I'm just spawning on the server and let the NetworkObject handle the rest
I never really had to mess arround with objectids
Yo! Just wanna know more about networking and multiplayer. Do you need steam to do multiplayer? If not what is the difference between steam multiplayer and some other multiplayer?
to answer your question you don't need steam
more detailed:
The kind of multiplayer
The first quesion you need to ask is what kinda of mutliplayer you want, centralized on a server (dedicated) or decentralized with players creating their own servers/lobbies (p2p)
There is a little more too it, but lets leave it at that for now, in this state you also need to decide what kind of game that is, but thats another topic
I will talk more about a lobby system now
getting it to run locally
The next thing you've got to do is implement your prefered networking solution in your game, since you are on a unity discord I will provide a link to unitys own networking solution
https://docs-multiplayer.unity3d.com/netcode/current/about/
When you get that working you get to a point where you can join the host in lan (local area network, for most people this will simply be their home network, so everything below your router)
making it publicly availabe
The first and simplist option is too simply go to your router and open the port your game uses, but that's less than ideal, if your focus is that your customers can host lobbies, that was okay maybe 20 years ago, but it is not nowadays
The second option is VPNs like hamachi, again it was okay a long time ago, but not anymore
The third option is the most widely used in commercial/indie games, a relay server
relay servers
relay servers are what allows you to not focus on server hosting, while allowing the players not having to engage with technology
this is the point where SteamMatchmaking, Epic Games, Unitys Relay service and so many more come in, simply implement their protocol in your game which is usually simple, there are great tutorials out there for this and you are good to go
Alternatives
-Server hosting, there is always the option to host yourslef
-A server build publibly avialable, so players can host on dedicated servers
Learn more about the available APIs for Unity Multiplayer Networking, including Netcode for GameObjects and Transport.
scratched the edge of discords message length on that one
Steamworks docs, if you decide to go that way: https://partner.steamgames.com/doc/features/multiplayer
A good video on how to implement it, with ngo: https://www.youtube.com/watch?v=9CYsQ2Rsr2c
Advatage/Disadvantage of steamworks
There are no running costs involved, since you pay upfront (100$) to even be allowed to release the game on steam and they take a 30% cut of the game sales
If this is a pro or con depends on your view, it was well worth it to me
You can however test with AppID 480, so you can checkout if this is worth it you, I myself developed for 50hours with it, before finally buying an appid
hope this answers your questions
That answered all my questions and questions that I didn't ask but wanted to know. Thanks!
What is the best net to use. Like netcode, photon, Mirror, Fishnet etc. Which one is really good for a game where all players play in the same world
It depends on how many players you'd need dedicated servers if its alot of players
what about the region servers? How do they work? Does every region has one server for each of them?
like in general region servers?
or a special netcode like photon
region servers
well you host the servers how you would like it too
if youd like to host only in europe for instance then thats fine
people from north america could join
but they would be getting high ping
how would you host?
well through a server
you can even host it from your computer
but that wouldnt be stable if you have too many players
aight
so on to this
what's the best one to use
most people use netcode as much as I know
as i said it depends on how many players. if your going to make a big game with alot of players your own netcode would be better
small game id recommend photon
photon is the best one in your list there
aight thanks
hello
how can i do convert string to csteamid?
i want to do join with id or code system
Csteamid is an ulong afaik
how can i normalize it like a 4-letter code
more friendly because in this case id is like 10-15 letter
with steam alone? you can't
do you have access to the steamworks community?
https://steamcommunity.com/groups/steamworks/discussions/5/3033726413410711157/
There are however somethings you can do, set the name of the lobby as a code, having a simple server running somewhere, which gets a lobby id and returns a 4 digit code, a simple hashing function, but be aware on how to handle collisions, but these doe seem lilke they are not worth it
you could also try, using a different numbering system, the CSteamID is in base10 I think, I could test a quick programm to convert to a custom numbering system with 32 digits
https://pastebin.com/4HdWxGgn
maybe this helps, this is a custom base64 system, which cuts down your lobby code to 4 letters. Because it seems like a lot of the CSteamID is just always the same, I don't know tho, you have to test it
This is python, for easy testing, the same concept should apply to csharp
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.
Need to ask. Can multiplay unity gaming services be used for an open world server where all players are in the same world? As much as I read it's mostly for matchmaking like battle royale games. Correct me if I'm wrong
Currently there is a default allocation time limit of one hour. It's not really meant for persistent world games at the moment. They are actively working on that use case however.
What's best to use then?
If I'm right UNet is best for above 100 players in one server but what is the best place to host the dedicated server?
UNet is deprecated, and has been deprecated for years. The new Unity solution is Netcode for GameObjects
Oh I thought UNet and netcode was the same thing lol
Another question. As much as I know there are 2 netcodes: entities and gameobject. Gameobjects netcodes is for simpler game and entities is for more pvp games where you need to predict an attack. Should I use both in my project or only have one installed?
Erm no
GameObjects is for GameObject architecture, Netcode for Entities is for DOTS
Rent your own server on Aws or Azure
!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.
For sake of the question, will "Time to detonate!" Debug always be reached before the NetWorkManager.Destroy line from the client's pov? https://hastebin.com/share/wexiwivero.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Assuming detonateServerRpc is called first
Because the way I see it is that detonateServeRpc is called, it sends the Client Rpc which has x latency, then completes the NetworkManager.Destroy statement which also takes x latency to appear on the client? However, im not sure if in practice, the latencies for these two things are always identical?
In theory the clientRPC should precede the Despawn but it's not guaranteed. In all likelihood they will get sent in the same packet since they called on the same frame.
so is there some sort of thing I can do to ensure that one thing happens before the other in terms of networking?
If you really need to guarantee it, you can have the clientRPC send a serverRPC back to acknowledge it before despawning the objects
hm okay, maybe in that case i'll just have the clients despawn the object on their end since I don't want to have to wait until every client recieves the packet
Ty Btw
guys what are the difference between UDP and TCP
im new at server programming
what do i need to use in my 1v1 Football game
Check the resources link here for a ton of great articles
#archived-networking message
The following are essential, high-level terms used in multiplayer networking and Netcode for GameObjects:
UDP is sending a package and not caring if the reciever recieves it
TCP is sending a package and the reciever sends one back to acknowledge the transfer, if that didn't happen the package gets send again
For gamedev you mostly use udp, that is because once a package would be retransmitted it is most often outdated (like a position transmission on a walking player)
thank youu
Hey, guys I want to ask, is better to use Dedicated server in Unity or just make own Dedicated Server in Java or something with Sockets UDP ?
that depends on what you want, if you want to build a mmo and you need a lot of control over traffic, to get the most out of it, I would write a complete own solution in c or c++, which can handle loadbalencing and so much more, for other games, which don't need that much of control, try to go with the provided solution and see if it works, there also will be a lot more help in the developing process, if you use a public solution
I'm so sad because switched between dedicated server and windows is so slow
And that's the reason why I'm asking
it always compile stuff.................. and that's so boring
waste of time
the question you need to ask is, if it is faster to write and manage your own networking solution
I definetly want to try that one day, but having enough todo atm
I have done my own network solution in dedicated server
Thats thing but I also need to manage rigidbody on server side
and that's problem I don't know to to make on custom solution
I can't calculate stuff on client side
how do I disable ''reload script assemblies''
is it possible? it takes so long for no reason my godness
there's literally nothing in the project and it takes minutes to make changes on single line edit
why they dont compile just files that was changed, so shit
You can change this in the project settings
https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html
Can someone tell me which netcode should I use? Netcode for gameobjects or netcode DOTS? I just read that you can't have both on because it could cause some problems. So I can't really decide what should I choose.
Are you using GameObjects or DOTS?
what is DOTS first of all. Is it like physics and stuff?
The Data Oriented Technology Stack, if you don't know it you're not using it
Ergo you're using GameObjects
Unless you've installed the Entities packages, you are using GameObjects and need to use that Netcode
does it matter or no?
It matters immensely that you use the right Netcode solution
for the example if I'll need to add entities or something in the future will it be easy to switch from objects to dots
I have no idea
I'd say start with the architecture you want, rather than rewriting the game
can you tell me the difference and uses of the netcode for gameobjects and netcode dots?
I've been researching for 2 days and still don't have the clear answer
Netcode for GameObjects is a networking solution for GameObject architecture, Netcode for Entities is a networking solution for DOTS architecture
I'm trying to decide before I move on. Cause my game is a little complicated
If you are not using the Entities package then you will be using Netcode for Gameobjects.
is it something you do in the beginning of creating a game?
I don't really understand anything about entities. This is why I'm not sure to what I should choose atm
You should absolutely not use Netcode for Entities until you are very familar with DOTS and Entities
I'm trying to learn what are DOTS and entities right now. That's why I'm asking before doing anything.
does it matter much? As I heard netcode for entities is more performant and better.
aight never mind
I'm still not sure but I believe that I should use netcode gameobjects. I figured out a little about entities DOTS
Let me give you a tipp for how to programm in general, just pick one and start. You will pretty soon find limits and capabilities. Researching for weeks over what to try out won't get you anywhere, you will learn by picking one and just start.
Since you are new to networking, have no clue what dots really is (me neither btw) and your first project won't be a big one either way (you always start with a small project, if you don't have years of experience in project planing), just pick the more beginner friendly netcode for gameobjects
If you don't like it you can just not use it after that small project, you learned what didn't work, which is very valuable.
And the concepts of how networking works should be universal anyway
I had a few small projects and I've been working on the idea for 4-5 years btw
just sayin
gotcha
It seems like, from what I read, that you don't have that experience in networked games, so writing a quick prototype (as a smaller project) in a solution you pick is a good idea
And I now notice my message sounded way meaner than I meant it to be, sorry
A lot of beginners get stuck in that loop of not deciding what to use and that is "dangerous"
I didn't see your message mean or anything
networking is new for me
tho I know that it is important for multiplayer
right now I'm just trying to learn more about it
cause the past 3 years I've been working on coding random games without networking. Just single player games
I'm pretty good at coding but network coding is a really new thing to me
I see. Well if someone asks if you need steam for multiplayer you immediatly think he is a beginner (which is in no way wrong or anything), so you start to point out mistakes you made yourself, like undecidabilty
If you are quite good at coding and have an idea of what you want from the networking solution, write a quick prototype, in the simplest form you can think of and try it out
yeah nah I just do a lot of research to know more and some page said steam got servers for games but I might've miss read it
The netcode for gameobjects docs are quite well written and should be easy to understand.
You can also look into mirror, which is slightly different, but follows more or less the same concepts, it has a lot of ressources you can learn from, espacially a lot of tutorials.
I would encourage you to watch some of them even if you use ngo, since the concepts are transferable
Codemonkey has a long tutorial for NGO that covers pretty much everything
So yeah just pick one, both are beginner friendly
Steam won't host the servers for you. But they can let player download a server version that they can run themselves.
Code Monkey and SamYam probably have the most up to date tutorial videos out there. Quite a few will be out of date. The official docs are very good. And the Netcode discord is there for more specific questions. We can help you get started if you need https://discord.gg/unity-multiplayer-network
Hello, I have an issue understanding the general way code is read when working with NGO. I've watched a couple of tutorials (namely the 1h one from code monkey and a tutorial by a guy named cuebat about implementing it with steam). I initially tried to do a little test with client authoritative movement which worked and my general idea was that when spawning a player, I should only enable it's component on the owner's side so I wrote this code ```csharp
public class OwnerComponentManager : NetworkBehaviour
{
public Cinemachine.CinemachineFreeLook cinemachineFreeLook;
private RunnerMovement runnerMovement;
private PlayerInput playerInput;
private Collider playerCollider;
private void Awake()
{
playerInput = GetComponent<PlayerInput>();
playerCollider = GetComponent<Collider>();
runnerMovement = GetComponent<RunnerMovement>();
}
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
enabled = IsClient;
if (IsServer)
{
transform.position = new Vector3(0f, 20f, 0f);
}
if (!IsOwner)
{
enabled = false;
return;
}
// player input is only enabled on owning players
playerCollider.enabled = true;
playerInput.enabled = true;
runnerMovement.enabled = true;
cinemachineFreeLook.Priority = 10;
}
}``` which worked. But now that I'm trying to move everything to be server authoritative it doesn't seem to work for the clients, it only works on the host. When I enabled the components manually from the editor for my clients they finally were able to have collisions, move around, etc... So I'm wondering what I'm getting wrong.
sorry if this is a huge message idk what the discord etiquette is
Hello I have an issue understanding the
is this channel fitting for questions about web api and unity web requests or this is exclusively multiplayer-gameplay related?
[Command(requiresAuthority = false)]
public void CmdSelect(int characterIndex , NetworkConnectionToClient sender = null)
{
GameObject characterInstance = Instantiate(characters[characterIndex].CharacterPrefab);
NetworkServer.Spawn(characterInstance, sender);
characterInstance.GetComponent<EnemyController>().target = characters[characterIndex].CharacterPrefab.transform;
}
I have a multiplayer game with 2 characters, when they are connected to the game, I want both of them to be defined as targets in the enemycontroller script, how can I do this? This code is not working
You can define characterInstances layer to be a layer of your choice and then with that u can define it as a target
for instance characterInstance.layer = Layer of your choice;
characterInstance.GetComponent<EnemyController>().target = characters[characterIndex].CharacterPrefab.transform;
Thanks that's the problem ,the component is not actually in a character instance.
Hi, can someone tell me if photonView.find() is slow or does it use some caching? I have a lot of PunRPC calls that will use photonView id to find correct object on the client.
I got it working with an invite code of 6 letters now btw
Still need to work on it a bit, but if you are interessted I can notify you and I plan to release that one script opensource, since it involves some byte magic I don't understand myself, but chatgpt helped me
Will make a thread out of this and post a video in it
IEnumerator getRequest(string url)
{
UnityWebRequest uwr = UnityWebRequest.Get(url);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}````how do i make this work for a http server?
What exactly do you mean? This is a http get request
unity wont allow me, only if i use a https server
im trying to not buy a domain and an ssl certificate
hi everyone, im trying to make 2d multiplayer game and I have InputField where player can write something and it will appear above player head in a speech bubble but it doesnt let me send message, I can write it down but when I click LeftShift as I put in the script it wont send that text, it just stays in inputfield. This is script: https://hastebin.com/share/okulizexov.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Question. Should I assign all the values and transforms and stuff through script and only through script?
I got cameras for difference players and for some reason the host is taking the camera from the client
Is it cause I'm assigning the stuff through inspector?
oh and another question. I got a parent that holds all the player stuff and I have the network object on the parent. Should I do that or should I just give the network objects to all player objects.
I don't really understand this warning.
Not happening because its assigned in the inspector, you should disable cameras for players if they arent the owner
Should be fine for just the parent to have it
Have u assigned a prefab list in the network manager? On NGO1.4.0 there was a bug causing this warning to show even if you had it. It's fixed on 1.5.1 though
Probably didn't
I'll do this tomorrow since I'm out but thanks for the help
So are you saying that I need to assign everything in the scripts?
Oh and I assigned the cameras through script and it still has the same problem
It might be cause I didn't assign the prefab list in the network manager
No u dont need to, it wont affect anything if you assign through inspector or script. The issue is that the other cameras are enabled.
Specifically when I had cam+cinemachine, my players cam would look at the new person who joined. You just have to disable the cameras if you arent the owner of the player
Like some new player joins -> disable their camera for me.
Yeah I'm having the same issue. I'm using cinemachine I did if (!isOwner) cam.enabled = false; and it still didn't do the job. Plus my client doesn't update the host movement and host doesn't update clients movement
And the prefabs are assigned. The player and the network prefab
The !isOwner disabled the host camera for both the host and client. And the client camera is enabled for both
Don't know the cause
Have u followed a tutorial? Codemonkey has a good introduction tutorial to just get movement and animations somewhat working
I would add debugs, maybe you are doing this before the ownership is declared. Like
Debug.Log(ownerClientId + "is the owner") ;
On mobile, might have a typo in there
although I'm not sure if using ClientNetworkTransform is a bad thing
like what are the cons of using it?
why or why not use it
If you want server authority, then you cant really use ClientNetworkTransform. the issue u were having in #💻┃code-beginner was likely because the server was trying to run the entire code of gathering the input and moving the player. You can have the player update its input via Rpc or network variables, then the host moves everyone based on that
ClientNetworkTransform is nice if you want everyone to move themselves and have no concern about hackers ruining multiplayer experience
although i had some issues with it and rigidbodies, since syncing them is kinda really annoying.
I tried doing this
[ServerRpc]
private void MovePlayerServerRpc()
{
// Move horizontally
body.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * speed, body.velocity.y);
}
void Update()
{
if (!IsOwner || !Application.isFocused) return;
MovePlayerServerRpc();
// Hang time
if (isGrounded()) {
hangCounter = hangTime;
} else {
hangCounter -= Time.deltaTime;
}
// Jump buffer
if (Input.GetButtonDown("Jump")) {
jumpBufferCounter = jumpBufferLength;
} else {
jumpBufferCounter -= Time.deltaTime;
}
// Jumping
if (jumpBufferCounter >= 0 && hangCounter > 0f) {
body.velocity = new Vector2(body.velocity.x, jumpForce);
jumpBufferCounter = 0;
}
if (Input.GetButtonUp("Jump") && body.velocity.y > 0) {
body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
}
}
but it didn't work either.
I get why it wouldn't work for the jump but the left & right movement didnt work either
in your rpc add a debug
Debug.Log($"Player {OwnerClientID} moving {Input.GetAxisRaw("Horizontal")}");
and you'll see what the issue comes down to
yea the ID of whoever owns this object
with parrel sync you can run multiple editors and see it like that. there is also a multiplayer tool for like newer versions of unity
I have a package called Multiplayer Tools
idk what it is for tbh tho
rn I'm just rebuilding the game everytime
otherwise yes theres a file somewhere, but ive never directly opened it. I just made a custom text area to display all logs for myself on screen.
You should be able to run the host in the editor, and the client on the build and see the logs on the editor. Since this one is a server rpc, the server will print it
but I think I have used parrel sync b4 in some tutorial I followed
owh I did the oppsitie cuz I thought it wouldn't work the other way around
lemme try that
there is Multiplayer Play Mode and ParrelSync, ive only used parrel sync though
"There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene."
how do I remove this
it's taking up the console and I can't see my logs
likely because of the 2 cameras, temporary solution is to disable the audio listener on one camera if you want to just see the other logs now
the real solution is to disable the other players camera when they join, since you really dont need to see theirs
yea
yea, itd be like on my game i disable your camera but keep mine on. You disable mine but keep yours on
owh I get it
Player 1 moving 0
UnityEngine.Debug:Log (object)
that's what I'm seeing
althought should I go back to using the Network Transform cuz I'm using the client one for the moment
probably
lol
because your server doesnt know about the clients input, so this is where u would probably use a network variable or rpc to update the clients input
thats up to you and what you want in your game
nvm same output
client network transform has its flaws, like you cannot really prevent hackers. But its more responsive
since the client doesnt have to wait for the server to move them
so when I use Input.GetAxisRaw(...) thats what my server can't figure out?
how would I go about fixing that exactly? 😅
i use a network variable to update what the clients input is, then move based on that on the host
so just pass the input to the server rpc then?
as an argument
and use that when updating the velocity
well you would either pass the value, or use a network variable
what is the difference?
but you'll really need to experiment with how these work to understand them, it is a weird concept at first
I thought they're the same ngl
network variables only update on change, and everyone is notified of this change. you can set the networkvariable so only the owner can update it
a network variable just seemed like more work so I used a server rpc
lol
yeah on the network variable u can set who reads and writes to the variable
i think in CodeMonkey's tutorial, he goes over network variables slightly. Maybe look at that or experiment yourself to see how they work
yeah he did
I've also used them b4 but I didn't fully understand them at the time
[ServerRpc]
private void MovePlayerServerRpc(float horizontalInput, bool verticalInput)
{
// Move horizontally
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
// Hang time
if (isGrounded()) {
hangCounter = hangTime;
} else {
hangCounter -= Time.deltaTime;
}
// Jump buffer
if (verticalInput) {
jumpBufferCounter = jumpBufferLength;
} else {
jumpBufferCounter -= Time.deltaTime;
}
// Jumping
if (jumpBufferCounter >= 0 && hangCounter > 0f) {
body.velocity = new Vector2(body.velocity.x, jumpForce);
jumpBufferCounter = 0;
}
if (verticalInput && body.velocity.y > 0) {
body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
}
Debug.Log($"Player {OwnerClientId} moving {Input.GetAxisRaw("Horizontal")}");
}
void Update()
{
if (!IsOwner || !Application.isFocused) return;
MovePlayerServerRpc(Input.GetAxisRaw("Horizontal"), Input.GetButtonDown("Jump"));
}
rn this is what I came up with
There is an important difference. RPCs are a onetime event, networkvariables sync even with late joining clients
So it's best to use rpcs for things that need to be synced once, like shooting a gun
And Variables for things which are there to stay, like names
this is making both the host and the client move the client, and the jump isn't working.... hmm
Try if IsLocalPlayer that is what I use, it is a bool, if the object is the clients player object
so since movement is probably constently changing I should use a network variable?
void Update()
{
if (!IsOwner || !IsLocalPlayer || !Application.isFocused) return;
MovePlayerServerRpc(Input.GetAxisRaw("Horizontal"), Input.GetButtonDown("Jump"));
}
like so?
You can, you can also use a NetworkTransform, which handles everything for you. But per default this is server authoritive, so clients can't change it, the docs mention how to make it client authoritive
I am using a NetworkTransform
I don't want to make it client authoritive that's what I was struggling with
cuz just switching networktransform to the clientnetworktransform fixes the issue
but I didn't wanna use it
I managed to get the horizontal movement to work but the vertical movement is not working on either now
[ServerRpc]
private void MovePlayerServerRpc(float horizontalInput, bool verticalInput)
{
// Move horizontally
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
// Hang time
if (isGrounded()) {
hangCounter = hangTime;
} else {
hangCounter -= Time.deltaTime;
}
// Jump buffer
if (verticalInput) {
jumpBufferCounter = jumpBufferLength;
} else {
jumpBufferCounter -= Time.deltaTime;
}
// Jumping
if (jumpBufferCounter >= 0 && hangCounter > 0f) {
body.velocity = new Vector2(body.velocity.x, jumpForce);
jumpBufferCounter = 0;
}
if (verticalInput && body.velocity.y > 0) {
body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
}
Debug.Log($"Player {OwnerClientId} horizontal {horizontalInput} vertical {verticalInput} isGrounded {isGrounded()}");
}
verticalInput is always false for some reason
isGrounded() is working cuz its displaying True
Oh I see, well than you need to handle everything in serverrpcs. But you will need to write client side movement prediction, the latency would make it horrible to play
Lets assume a ping of 16ms, which is a good ping
Client --16ms-> Server --16ms-> Client = Latency of 32ms just in networking not even processing
60fps->one frame is 16ms, so your network traffic alone will take twice as long as a frame rendering in the best case
So this makes everything a lot more complicated
void Update()
{
if (!IsOwner || !IsLocalPlayer || !Application.isFocused) return;
MovePlayerServerRpc(Input.GetAxisRaw("Horizontal"), Input.GetButtonDown("Jump"));
}
"client side movement prediction" hmm
that does sound complicated
but better safe than sorry imo
I feel like its easy to abuse the client authorative movement
Than Input.GetButtonDown("Jump") is probably not working, try to debug it, maybe using a different key for testing or just passing constant true, to check if the issue lies in the server rpc
I passed true to the verticalInput and somehow its always jumping when I move to the right
if your game is just between friends and doesnt have some online leaderboard/trading system then it really doesnt matter. As long as its not between random people
if I press the jump button nothing happens, and its normal when I move to the left
but once I press right
it moves to the right as well as jumps at the same time
like a diognal motion
diagonal*
thats very weird ngl
That depends on what you are working. My casual coop survival game, simply doesn't need the intervention of a server for moving. Client authorative movement makes sense in that case, in a competetive setting, it makes sense to not use it.
You can also do a mix, use client authorative, but check for every movement update, if that makes sense on the server, if not force reset it
I know but its intended for random ppl and its like a community driven game, so I can't really give ppl any chances at abusing my code, cuz they'll probably
wouldn't that be the same as predicting the client's movement tho?
is this last part just client side prediction and server reconciliation? or is there a way for the server to update other people using client network transform
im also trying to look at another method of getting rid of the input lag in my game, but my game is very physics based and the clients dont really know what to do when coming across a rigidbody they can push
Yea, but a bit simpler, since you are just checking if the movement was allowed, which in a highly competitve game, could surely be abused somehow.
In mathematics it is easier to verify that a solution is correct than actually calculating the solution from scratch, thats why this could be one approach which makes it easy to have both instant client side movement and a system which isn't as abusable as client authorative movement
do u think its the hangCounter that's causing the issue, also I figured a new thing where when the client is jumping it goes down very very slowly and if I go to the left it goes down faster, I somehow implemented diagonal movement.
Player 1 vertical True isGrounded False jumpBuffer 0 hangCounter 0.05445842
[ServerRpc]
private void MovePlayerServerRpc(float horizontalInput, bool verticalInput)
{
// Move horizontally
body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
// Hang time
if (isGrounded()) {
hangCounter = hangTime;
} else {
hangCounter -= Time.deltaTime;
}
// Jump buffer
if (verticalInput) {
jumpBufferCounter = jumpBufferLength;
} else {
jumpBufferCounter -= Time.deltaTime;
}
// Jumping
if (jumpBufferCounter >= 0 && hangCounter > 0f) {
body.velocity = new Vector2(body.velocity.x, jumpForce);
jumpBufferCounter = 0;
}
if (verticalInput && body.velocity.y > 0) {
body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
}
Debug.Log($"Player {OwnerClientId} vertical {verticalInput} isGrounded {isGrounded()} jumpBuffer {jumpBufferLength} hangCounter {hangCounter}");
}
I think its the jumpBufferCounter cuz its always 0 for some reason
okay I fixed it
but now I got another issue lol
when I connect a client, the camera switches to the client's for both the host and the client
I think this is what u were talking about having to disable the camera
ah yes, you need to disable the camera for everyone and just enable the camera for the client
well
ugh
how?
I get how to get the player's camera
but how do I disable everyones?
do I make it disabled by default
and when its created enable it?
disable it in the prefab and enable it on Start, with .SetActive(true), if IsLocalPlayer is true
you can also just do .SetActive(IsLocalPlayer)
IsLocalPlayer, beacause you want to check if that object is the clients playerobject
if it works just do both
ur right
cuz if its not a local player
there shouldn't be an issue
unless he's running 2 instances of the game
so yeah prob both?
if the player would be running 2 instances, it would be handled as 2 different clients
just try out what works for you
[SerializedField] private Camera playerCamera;
playerCamera.SetActive(IsLocalPlayer && IsOwner);
I'm trying this but its not working any ideas why?
the SetActive is not a member
private GameObject playerCamera
also I'm doing it on OnNetworkSpawn not Awake
you want to enable and disable the gameobject
owh cuz Camera is a component not a GameObject right?
yes
makes sense
[SerializeField] private GameObject playerCamera;
void Start()
{
body = GetComponent<Rigidbody2D>();
playerCollider = GetComponent<CapsuleCollider2D>();
}
override public void OnNetworkSpawn()
{
base.OnNetworkSpawn();
playerCamera.SetActive(IsLocalPlayer && IsOwner);
}
hmm...
it is public override or does it not matter?
public override I think, what does the errorlog in unity say?
never mind
I disabled the component
instead of the camera itself
by default
like the gameobect
j*
okay its working now
thanks so much
good, you got this
ty ❤️
once last question, when building if I'm on a mac, is it possibile to build to to windows and linux too or am I limited to a mac?
cuz rn mac is the only building option I see
you can, but you can't execute the build
and I know how shitty apple is with this kinda stuff
owh good
you need to install it with add modules, I'm on windows, so I marked mac and linux
I'm following the 'getting started' tutorial for ngo, and I'm stuck on After the client and server spawn, a log displays in the Console of the client and server sending RPC messages to each other. I know this part probably works, but I would like to see it. Executing the built exe just immediately exits because I'm guessing under the hood its spinning off another task or something, so I get no stdout in the termainl, and there's no log in game.
Debug.Log is for printing stuff in the unity console, if you want one in game, you have to write your own or search for assets
I know its bad to stick closely to tutorials, but they should put a note for that right?
They pretty much explicitly say you'll be able to see the output somehow, no custom work required
I think they are expecting you to be familiar enough with unity to know that, because you usually don't start with mutliplayer games if you have no experience in single player games
I have experience working with unity, I'm not an expert but I would've thought there would be a way to pipe Debug.Log to stdout atleast for development builds
maybe I can play with the profiler settings or something
I also assume its harder to access two instance's simultaneously because Unity Editor will only accept one
It should go to a file, although I've never opened it so not entirely sure where. I just print logs to a scrollable text area on screen
Cheaper than buying a whole console I dont need
I think I found a asset on the store which will work for now, I looked at the logs and it did show something like 'Packet Recieved' but it just described like packet size and timestamp, not the content as readable data. It's much more than I needed. Thank you tho
I did if(!isOwner) in start in update and in fixed update. That probably is the reason. I thought I had to do that so that no other player would get the values from another player
Hey I am using Unity TPSBR photon fusion template and it does not use asmdef-s and it is slow. I tried to create my own to make project lighter but there are 300+ errors now. How to refactor project such that there are many scripts and libraries, over 50+ asmdefs but main project does not use asmdef and I want to add it?
Hello, I am creating a multiplayer game with morror and I would like to make a skin change system, this is where a problem comes to me when I change the color of a material it changes on both players. Would you have a solution?
try using if(!isOwner) idk if that is gonna work
ok so the if(!isOwner) worked. It disabled the right cameras but the position of the camera changed on the clients cinemachine. Do I have to disable the cinemachine too on if(!isOwner)?
I disabled both cam and cinemachine on mine, no reason to really have them on for other players
ok
hi everyone, im trying to make 2d multiplayer game and I have InputField where player can write something and it will appear above player head in a speech bubble but it doesnt let me send message, I can write it down but when I click LeftShift as I put in the script it wont send that text, it just stays in inputfield. This is script: https://hastebin.com/share/okulizexov.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Client or host position isn't updated for neither of them. Do I need to have the client network transform on every single object that changes the position? Right now I have it on the parent which is always on 0 position.
yep it seems like it.
How do I fix the late movement when the player 1 moves but the player 2 sees the player 1 move a little later
nvm it's good
Pls someone
did you try debugging?
No cause i dont know where to put debugs
look where it doesn't run the code. And figure out why. Try doing Debug.Log("Work here!"); in this
if it works then everything should be fine in there
if it doesn't, try debugging before this
Okay i will try that rn
if that doesn't send the message go debug before the if statement again till it works and then look for the problem where it stops working
you might've made a mistake with the DisableSend bool. It could be always false
I think DisableSend = false; should be true
I might be wrong
I will try that
sorry, in here
yea
also this is script made in tutorial btw
and here in tutorial it goes !DisableSemd && ChatInputField.isFocused
but it showed error here so i just changed it and it doesnt show error
strange
yes
but in tutorial it doesnt show error
and i double checked everything i have everything like in tutorial
what about in the inspector? (Thought I doubt there should be a problem)
ah never mind
tell me what runs and what doesn't
expected
try putting it on DisableSend instead of !DisableSend and play again
and tell me what runs and what doesn't
makes sense
the DisableSend = true;
that's the only time it turns to true that means if(DisableSend && ...) doesn't run cause DisableSend is always false
but if you do !DisableSend it should work but it throws an error and it doesn't really make any sense
still only this
omg i had that written on wrong object that was the problem
thankss
but before u go
can u help me so player cant walk while i type
cause it can move left and right
when i write
using UnityEngine;
public class PlayerController : NetworkBehaviour
{
[SerializeField] private MultiRotationConstraint bodyAim;
[SerializeField] private Animator animator;
[SyncVar(hook = nameof(OnWeightChanged))]
private float syncWeight;
private bool rangerAiming;
private void Update()
{
if (!hasAuthority)
return;
if (Input.GetMouseButtonDown(1))
{
if (!rangerAiming)
{
RangerAim(1f);
}
else
{
StopRangerAim();
}
}
}
private void RangerAim(float aimWeight)
{
CmdRangerAim(aimWeight);
}
private void StopRangerAim()
{
CmdRangerAim(0f);
}
[Command]
private void CmdRangerAim(float weight)
{
syncWeight = weight;
RpcSyncRangerAim(weight);
}
[ClientRpc]
private void RpcSyncRangerAim(float weight)
{
if (bodyAim != null)
{
bodyAim.weight = weight;
}
if (animator != null)
{
animator.SetBool("ArrowAim", weight > 0f);
}
rangerAiming = weight > 0f;
}
private void OnWeightChanged(float oldValue, float newValue)
{
if (!isLocalPlayer)
{
if (bodyAim != null)
{
bodyAim.weight = newValue;
}
if (animator != null)
{
animator.SetBool("ArrowAim", newValue > 0f);
}
rangerAiming = newValue > 0f;
}
}
}
The bodyaim.weight value is not 1 on the client side, it goes up to 0.7-0.8 values, how can I solve this?
kk give me the full new script