#archived-networking
1 messages · Page 3 of 1
and the video is 7 years old 😂
string _netID = GetComponent<NetworkIdentity>().netId.ToString();
is that correct?
Can someone help me with unity playfab guilds/clans system? Need help.
I would assume so
is there someone avaliable? I have this issue:
nvm the ClientScene got changed on mirrors documentation
Hello, so I have been learning unity for the past 6th months, and I wanted to create a multiplayer open world game. I am at the point where I have made a basic player character and I need to create enemies.
If someone would give me advice, show me how you learned, or show me their code so that I could learn from that that would be much appreciated!
I can share my project files/provide more detail on my project if that helps. I have also done research on how normal single player enemies work and tried that, unfortunately, I couldn't figure it out.
Feel free to DM me or reply to this message! Thanks!
A: I am currently learning from tutorials I look for depending on the things I need, and try to absorb the information of how the code works and what it does, for me to reuse that information later, and also a huge help from this server
B: My advice is to stay consistent
C:If you want multiplayer, there are some tutorials on youtube on how to make multiplayer.
D: If you want to make enemies I would recommend you to start by making a basic AI that follows the player
My client rpc method is not working and is only called on th host client. The method has the [ClientRpc] attribute, it has the ClientRpc suffix, it is called within a NetworkBehavior and the NetworkBehavior has a NetworkObject on the same gameobject. Is there anything I am missing?
Hi All,
I am currently making a game in Unity that utilizes the Google BigQuery SDK (installed via nuget within my Unity project). I was able to get the game to successfully run the API calls and get the appropriate responses for my MacOS build (tested on TestFlight and works great). However, the same API calls don't seem to work when I build my game for WebGL or Windows. Does anyone have any idea why this may be the case? Is there a certain WebGL or Windows build setting I need to enable for this to work?
Thanks in advance!
the best library is the one that closely matches the needs of your project
can you give me an example
if you need an authoritative server you can't use Photon PUN
if you need a lot of handholding during development pick one with a good community or paid support
if you need the library to be stable and still supported in 5-10 years, pick one that is backed by a large, successful and well funded company that is committed to supporting it
if you want to make an MMO, don't
is there a way to open multiple test games inside unity without having to keep building it?
There's ParrelSync which makes a copy of the project folder which it keeps synchronised, and runs that in a second unity instance, but I have not tried it in Unity 2021. In some versions you have to turn off directory monitoring.
hello guys,
Im making a multiplayer game and would like to add IP:Port connection, I didn't find anything online. I'm using Netcode V1.0.0
I'm using the default code provided by unity, here is it :
startHostButton.onClick.AddListener(()=>
{
if(NetworkManager.Singleton.StartHost())
{
Debug.unityLogger.Log("Host started...");
}
else
{
Debug.unityLogger.Log("Host could not be started...");
};
});
startClientButton.onClick.AddListener(()=>
{
if(NetworkManager.Singleton.StartClient())
{
Debug.unityLogger.Log("Client started...");
}
else
{
Debug.unityLogger.Log("Client could not be started...");
};
});```
thanks you !
What is the best way to sync audio? my fire pistol runs on the client, which plays the sound locally, but i want other players audio listeners to pick it up so they can hear other people shooting too
Hello everyone, I have a strange issue. I'm using Netcode for gameobject and I'm trying to quick join a lobby, if there is any, or alternatively create a new one automatically.
public async void FindLobbyAsync()
{
try
{
QuickJoinLobbyOptions options = new QuickJoinLobbyOptions();
Lobby lobby = await LobbyService.Instance.QuickJoinLobbyAsync(options);
Debug.Log("Lobby found");
}
catch (LobbyServiceException)
{
Debug.Log("Lobby NOT found. Creating a new one.");
await LobbyService.Instance.CreateLobbyAsync("New lobby", 8);
Debug.Log("Lobby created.");
}
}
Now the strange thing is that if there is no lobby, the system throws an unhandled exception (NoOpenLobbies), but enter the catch block anyway.
So, the first question is ... did it catch the exception or not?
Trying to make a door. Works fine overall, but when the door is opened on one client (default is closed) before another client joins, the new client still sees the door closed. Door opens by rotating a transform (NetworkTransform attached with syncing y rotation selected). When the new client joins I print out the networkvariable's value and the door transform's rotation, which are both correct. The transform just isn't actually rotated that way on the new client. Door script: https://pastebin.com/kBPi0BtL, character calls Interact() to open and close the door. What am I doing wrong?
I did not use netcode over a year (used fishnet for the time until release)
but usually all transport data are saved under a specific transport object,
you can try this one:
https://docs-multiplayer.unity3d.com/transport/2.0.0/api/Unity.Networking.Transport.NetworkEndPoint/index.html#port
(add using unity.networking.transport) and for local network (same router) use Ipv4 adress and port
Inherited Members
can you try open the door with the second client (after it's opened for the first one) and report what happens?
Door stays closed on second client, closes on first client. Trying again then opens the door on both clients
I'm guessing that unity only debug.logs the error but the rest of the code continues to work.
I did not use this system before but there is probably a way to handle LobbyService.Instance.QuickJoinLobbyAsync(options);.
second client opening the door does not affect the first client?
It does. When in unsynced state (door open on 1st client, closed on 2nd client), trying to open the door on the second client closes it on the first client, nothing happens on the second client
Sorry, to be clear, the first client is actually the host, if it matters
hey folks, I'm new and I have troubles with my animations in multiplay. maybe someone can help me?
how do I implement it ?
how do I use endPoint ?
startClientButton.onClick.AddListener(()=>
{
NetworkEndPoint.TryParse(Ip,port, out NetworkEndPoint endPoint, NetworkFamily.Ipv4);
if(NetworkManager.Singleton.StartClient())
{
Debug.unityLogger.Log("Client started...");
}
else
{
Debug.unityLogger.Log("Client could not be started...");
};
});```
Got it working by removing the NetworkTransform from the door - I think the changing the rotation through DoorState and the NetworkTransform were fighting each other.
how can i send an audio source, to the server and then to all the players without having to do a whole function for each sound?
Try:
NetworkManager.Singleton.GetComponent<UnityTransport>().SetConnectionData(
"127.0.0.1", // The IP address is a string
(ushort)12345 // The port number is an unsigned short
);```
such as when my player shoots, i want everyone to hear it, not just him
Probably, I'm guessing DoorState is a script you wrote that affects the rotation of the door?
DoorState is a NetworkVariable in the script I linked. Value decides on how the transform should be rotated
I would recommend checking the boss room example and see what they did there.
on my own project I would start the vfx locally, so when a different player shoots you can trigger an event that plays the audio,
as when the player shoots everyone who see that he shoots will also have the audio triggered locally.
yea, that's probably it :)
Cheers mate ill have a look, been stuck on this for ages now haha
it seems to work, It's working if I use the ip 127.0.0.1, but it doesnt work if I put my lan address (192.168.1.45), It might be the windows firewall... I don't have any popup saying that windows blocked this connection
I even tried using my external ip, and setup port forwarding on my router but nothing
I might be dumb but just to make sure, you got the address from running an IpConfig and copying the IPV4, right?
yeah this one
alright, copy that to the other computer and make sure you are on the exact same port.
a problem that could cause this is from the firewall, I would disable it temporarily just to check as it can be the issue.
hey guys, if you have time maybe you can help me with my issue... I got a simple 2d movement and animation. but my client stuck in the position and cant move, but my host can...
I disabled the firewall from my main machine but still nothing, Imma try with a different computer but I don't think it will work
weird.
if this doesn't work I believe you can also change the IP and Port from the network manager through Unity itself,
try disabling the script you wrote that overwrites that and see if it works different if you set it yourself.
did you make sure the second client is the owner of it's own player object?
protected override bool OnIsServerAuthoritative()
{
return false;
}
this is from a video and they said if u attach this to ur player prefab, it should work
@summer anchor if you need help feel free to ping me here, not in dms :)
and there are no dumb questions, there are dumb answers and I will try my best to not provide them here
you can download the boss room through the guide here:
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom/index.html
Learn more about installing and running the Boss Room game sample.
it's working, and I even have a popup from the firewall to ask me if I wanna allow connection
Alright,
Than I'm guessing you have a problem with converting inputfields/any input method to string/int.
Sorry, i get the error to install git on my system
did you make sure to attach textMeshPro components instead of Unity.UI ones?
make sure there are no spaces or empty strings
and try to debug.log the string.count of the adress and port and count the adress digits yourself to make sure everything is correct.
try installing git from here: https://git-scm.com/
How do you know if my client is the owner?
if (IsOwner)
{
Debug.Log("I am the Owner" + gameObject.name);
}
If override the value of the ip like this :
NetworkManager.Singleton.GetComponent<UnityTransport>().SetConnectionData(
(string)"192.168.1.45", // The IP address is a string
(ushort)7777 // The port number is an unsigned short
);```
it doesn't work
weird, can you check what it says in the network manager?
(in runtime, after changing the value)
yeah I'm the owner
I just have this
"Ip" is the input field but since the value is override it doesn't matter
log level is set to developer
this is on the second client, right?
try adding debug.log("Test x"); to the PlayerInputs(); function.
see if the second player enters it or if the first one does as well.
also debug.log the movement values and see where it fails
so the new value is empty?
sorry,
@pallid hollow can you try this instead?
NetworkManager.Singleton.GetComponent<UnityTransport>().SetConnectionData(
"127.0.0.1", // The IP address is a string
(ushort)12345, // The port number is an unsigned short
"0.0.0.0" // The server listen address is a string.
);
This is from the documentation on the NetworkManager:
https://docs-multiplayer.unity3d.com/netcode/current/components/networkmanager/index.html
The NetworkManager is a required Netcode for GameObjects (Netcode) component that contains all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
yes, i build and run the game, and start host and in my editor i started the client.
now I debug.log the x and the y value of my vector and when i press the arrow keys the value changed from 0 to 1 and 0 to -1, but my player stands still and doesnt move... but i see the animation
it says the values are 0 here.
does the animation play in the right direction?
yeah because i can't make a screenshot while i'm moving^^ yeah and the animation play in the right direction
on my host everything works fine
just on my client the player animation works, but my player doesn't move
can you show me the networkTransform component?
Yonatan, do you know where exactly in boss room i should be looking? struggling to find and code that relates to sounds
besides local sounds
I never seen something like this before happen naturally,
I am guessing 2 things:
-
you have a script that makes the player get stuck at a set position (probably 0,0,0):
so the player is indeed moving but you are updating his position to 0,0,0.
you can check that but going to the second client in editor and than moving the player manually with the move tool. -
the movement is server authorative, which means the client needs to send the server his data and the server will be the one who updates the client.
you can check if that is the case through opening the host in the editor and the player on the build.
than try to move the second player through the host in the editor and see if it updates for the second player and the host.
nope, but try looking for scripts related to audio, sound, any weapon that makes noise and try playing the game and notice when a noise is made. (not bg music as that could be played locally.)
yeah thats what im hunting for
on the plus side, im now backing my project up on github xD
Im back, this doesn't work with my lan address but does with 127.0.0.1
so nothin as changed
I don't have anything to add in the code when I start as host ?
because I'm supposing that the code you sent me only execute when I start as client
but I might be wrong
-
yeah that's the issue but in my code I don't set the players position to 0,0,0...
-
yes i can move the client and it updates to the host. so u were right, it's the issue 1.
this is my simple movescript...
the server address should always be 0.0.0.0.
the second code I sent does that and the client one is the first line of string.
if you are on the same computer than yea 127.0.0.1 should work.
if you are using 2 computers use the lan address and see if that works
it's working dude
I pasted your code on both host and client connection and it's working
working on two different computer too
thanks you so much !!!
if you run the client in the editor, and move the client through the editor, does it work?
glad I could help!
no... I can't move it... why?^^
if you drag the client with the arrow it doesn't work?
no it doesnt...
yeah i know^^
NoOpenLobbies is one of the possible reasons of the LobbyServiceException (https://docs.unity3d.com/Packages/com.unity.services.lobby@1.0/api/Unity.Services.Lobbies.LobbyServiceException.html#properties)
But there's more : https://docs.unity3d.com/Packages/com.unity.services.lobby@1.0/api/Unity.Services.Lobbies.LobbyExceptionReason.html
So yes you will catch when there's no more lobbies, but if you don't further investigate the reason response, you'll even catch ANY lobby error exception. For example someone unauthorized or already connected to a lobby, if able to launch multiple requests, could massively trigger creation of new lobbies.
And indeed your debug logs are printed in the console, so yeah your catch block is executed
Well today I learned something new.
In netcode NetworkTransform is automatically Server Authorative Movement.
Aka each client send the server their movement data, the server moves the clients locally and than sends the clients an updated situation to render.
try removing the NetworkTransform component and switch to ClientNetworkTransform.
this should make it client Authorative as the client is the one moving and sending the data to the server and reply to everyone on how to render.
Has anyone got an example of how to play audio over the network at a certain players location?
Hi. I get a wierd warning when I try to use a client rpc on unity netcode for game objects. The client rpc method does not work but rpcs in other scripts work fine. The script that is trying to run the rpc is a network behavior with a network object and the method was copied from another script where it works (it just says pong in the console). Anyone know why the rpc in this script does not work?
it worked for me, thank you!
hello, i have two players on my game, but when i put animations on them, they are both synced. Is there a way to only have one player move and the other stay still (as in, they have different animations based on player input)?
Glad I could help!
yea, but it depends on how you sync the animations.
if you are using Netcode and NetworkAnimator than you can simply play different animations (try Animation override https://docs.unity3d.com/Manual/AnimatorOverrideController.html) and Unity should Sync them differently.
yea im using netcode
ohhh i see
i'll check it out
thanks!
can you send the new function where you use the rpc?
it could be that it is attached to a networkObject that does not spawn correctly or is only instantiated for the server and not a client...
oooh. I think I might be destroying the object on the client. I think I was just being stupid
Nice.
don't forget when destroying objects you should Despawn(); them first, so later when sending Rpc's or dealing with the network they won't bug the game 😉
alright. Thanks for the tip
is it possible that a friend from another network join my multiplayergame when i install hamachi and configure unity to the hamachi ip?
Why would you even need hamachi for that? What kind of networking solution are you using?
I used Netcode for Gameobjects and UnityTransport
but if i give him my build, I need an IP address where he can connect right?
I'm not entirely familiar with netcode, but if it's anything like photo (which it should be), then you don't need to do any manipulations with IP addresses. The framework should take care of connecting both of you to a name server(or it's alternative in netcode) from which both of you should be able to create/join rooms .
my goal is to create a mmo and a dedicated server, that's why i wanted to test it with hamachi
i dont want to use photon
If the server is hosted on your network, you'll need to port forward
ok, so it could possible work with open ports and a hamachi ip right?
I have no clue what hamachi is
If you open the port, he can join via your public IP
Hamachi is for simulating local network. I've no clue why they bring it up here...
ok, are there preferences for the ports that i should use?
ok
But there's all the ports
Unless you have firewalls blocking ports, you shouldn't need to do any manipulations with the ports.
How does matchmaking in games work
Like the player has to press a button
THen the game searches for other players who also pressed it
And then puts them in the same lobby
But how does it work, after the button is pressed
Is it neccesary to create your own matchmaking server or how are matchmaking servers created
When the button is clicked the players Info about what type of match they want to play (class, skill rank, ping) is posted to a matchmaking server, the server stores it and waits for other people to post their match requests. every time a new player posts such a request the server searches the existing requests for a close match of parameters (you define what those are). Once enough matching players are found in this way a match dataset is created that all the players in it can retrieve. It contains the info for connecting to the match server
That matchmaking server usually is just a simple web api
you can code your own or use services like playfab with readymade matchmaking that you configure your needs
THank You
But, if you want to create your own matchmaking server, is it neccesary to have a server set up and is it hard to program it or is it just easier to use PLayFab
You need someone(some machine) to handle connecting clients together/to the lobbies. Otherwise how are they gonna match each other? Check every single IP address and port on the web untill they accidentally stumble on the right address?😅 That's basically the job of the server: it provides an access point known to all clients and handles connecting them to the same environment.
As for creating your own server, there's like a full fledged profession for that - backend engineer. So it's definitely not easy.
Thankfully there are complete solutions like netcode, photon, mirror, etc that do it for you.
Netcode for Gameobject: BossRoom uses a unique identifier to keep track of users reconnecting. That identifier is sent by setting NetworkManager.NetworkConfig.ConnectionData before starting the client. Am I correct saying that this data is then only available through NetworkManager.ConnectionApprovalRequest.Payload in the approval check and not elsewhere? I can not find anything else
I'm not familiar with playfab, but yeah.
But generally, are those solutions (Mirror, PlayFab) like extensions or something. I used RiptideNetorking for my game, and I finshed it, but I still have to do Matchmaking. Or how do they work?
The provide you with some kind of API for matchmaking. They only cover the back end of it of course.
Like for Playfab I found this:
"MatchmakingQueue": { "Name": "MyFirstQueue", "MinMatchSize": 2, "MaxMatchSize": 2, "ServerAllocationEnabled": false, "Rules": [ { "Type": "StringEqualityRule", "Attribute": { "Path": "Build", "Source": "User" }, "AttributeNotSpecifiedBehavior": "MatchAny", "Weight": 1, "Name": "BuildVersionRule" } ] }
But do I have to write inside of my scripts or what?
(Or does it do magic like the unity multiplayer solution)
It depends on the framework. You'll need to read their docs and how to implement matchmaking in your game. There's no magic in code.
OK
Generally a networking library like netcode/mirror/photon fusion will do nothing for matchmaking. Playfab and unity game services is a completely different type of thing, it’s a service for scaling your game, they typically include hosting servers, databases and various APIs for implementing features that are not real-time (matchmaking, shops, inventory)
Has anyone made a network audio component? sort of like the network animator that sync all the animations, after something like that but for audio
Hi.
Can we run Photon server on Unity Game Server Hosting?
Dose anyone have such experience?
Or maybe there is other way of running Photon on Unity Game Server Hosting?
unity.com gives me a server error right now, but I'm pretty sure this is an official example project of Photon Fusion + Unity Game Server Hosting: https://unity.com/demos/photon-fusion-battle-royale
Thanks @gusty fjord
I will check it later.
Lets say I have created Unity Game Server.
And for example I have 4 rooms each has 3 players. Overall 12 players playing the game at a time.
Does it mean there would be 4 running instances (servers)?
Does it run a new server for each room?
hello guys, is it worth it to use relay for a game where the one player is the host and the remaining ones are the clients?
4 players max
It depends.
We run Photon Servers on the Photon Cloud for everyone to use. If you don't need to customize this, you can use it. The Photon Servers run a lot of rooms each (but don't run Unity itself).
You usually don't run Photon Servers on services like Multiplay but you'd run those on baremetal machines.
With Fusion, you could build a Unity instance as Server and run that per session/game-instance on services like Multiplay. To do this effectively, you'd need the matchmaking to orchestrate instances running.
Usually, it's fine to start with Fusion's "Host Mode". Then some client is running a client plus a "Fusion server".
Not necessarily. It may be good for security reasons, as the Host's IP is hidden. So the host less vulnerable for attacks and has good privacy.
yea this doesnt seem too bad
since i want the game to be online as well, and not only local
how hard is it to implement a simple system?
It can be online even without a relay. The topic to look up about that would be "NAT Punch Through".
Depends on your knowledge and the tools you use.
Afaik, Steam always uses relay. Fusion and Networking for GOs have it as option.
im definitely a noob on this topic
so lets say i'd like to have my game on steam one day
if i had relay on my game, the process to have it accepted on steam would be easier?
I don't know about Steam's publishing requirements. I don't think it matters.
ah i see
okay then, ill check on the NAT punch through topic
thank you for the info!
Hey @stiff ridge
Thank you for reply.
We run Photon Servers on the Photon Cloud for everyone to use. If you don't need to customize this, you can use it.
This part is not clear to me.
As I know the Photon Cloud is kind of relay, it handles matchmaking, and data transfers to the users.
Photon Server is something that we can run on our local host and test the games, or we can put it on some hosting (non gaming hosting) and run our game on that custom host.
The Photon Servers run a lot of rooms each (but don't run Unity itself).
You mean each photon server can run several rooms on the same instance of the game? I don't understand the server scaling part.
You usually don't run Photon Servers on services like Multiplay but you'd run those on baremetal machines.
I also know so, that the Photon Server is for creating custom host on users PC.
That is why I can not understand your first sentence.
With Fusion, you could build a Unity instance as Server and run that per session/game-instance on services like Multiplay. To do this effectively, you'd need the matchmaking to orchestrate instances running.
So if I build a Unity Server instance and put it on let say Unity Game service or Multiply, each room will create an instance of the game on the host side?
If so then
1. one server multiple instances?
2. or one server per instance?
I know I miss some important things, that is why I ask those question to put all together.
Thanks.
For the unity multiplayer (Unity Relay), what happens if the free tiers are used and you have to start paying
Will unity inform you
Or will it just take money
Is there a way, when it will cost too much, and if it goes over the free tiers, the servers would stop.
Yes
Yes
Typically these services are happy to bankrupt you by way of a careless config mistake that runs 1000 servers at full throttle over night
I recommend checking your daily usage reports diligently
first feature you should implement in all your servers is automated shutdown on a timer
Just wondering if im handling everything correctly in my co op fps game.
For shooting i use this
-player casts a raycast, and sends the raycasts hit and the players name who shot it to a command
the command has a deal damage function to the player hit by the raycast. then also sends an rpc with the players name that shot and called the command.
clientrpc checks who the player is, then runs the shoot function only on that player (animations, sounds etc)
Am i running everything correctly? or will i get issues because the player wont actually see he is shooting until the server tells him he is, it seems pretty instant to me just curious if its right or not, thanks
The Photon Server is the basis for the Photon Cloud and the Photon Server SDK. It runs a base logic to distribute games across regions and then games across a number of "Game Servers", which enables us/you to scale for number of rooms running. In rooms, clients can send messages to others, store properties on the server, etc. This is called the Realtime API.
The Photon Cloud runs this logic "as is" in a default configuration. You can get the Photon Server software and run it "as is" if you like. With the SDK you can also modify it.
If needs be, you could write your own game logic with this. It is run "per room". Only one Photon Server instance is needed to run a large number of rooms and it could have some game logic. However, you can't run a Unity instance in those rooms (so no physics, etc). This is best for turn based game or games where the simulation can run without Unity (no physics, etc). Then this is very effective.
Fusion Servers are Unity instances. They should be run per match and it supports physical interactions, using the scene, navigation, etc.
Each Fusion match needs a host or server (unless you use the Shared Mode) and you could run those on any of the Unity hosting services (Photon won't host and run those instances, it just coordinates them and provides deep networking integration via Fusion).
You can run multiple instances on a single physical machine (actually, the more run per machine, the better, as this is more cost effective)...
Thank you for explaining things so deep. @stiff ridge
why is it everytime i make a new build i always have to make the animation discrete again?
it always goes back to disabled after the build
IIRC there was some ritual to unscrew the serialization on that. Try File -> Save Project?
weird
if i instantiate another player prefab it goes back to disabled
maybe i should force it to be discrete through a script
How can I send a struct with a client connection attempt? Here is an example which I think should work, but doesn't. I have a really simple struct (just 2 strings). I'm then serializing to byte[] and putting into the clients ConnectionData. However the connection just silently fails (the host never gets the connection attempt). If I remove the ConnectionData then the attempt does go through.
Does anyone have a good list of structs example for synchronizing data between server and client in NetcodeForGameobjects? I'm making a player preferences object which includes a list of player icons that persist between scenes.
Hi, i'm following the docs from unity networking and i now need to test it through the command line (https://docs-multiplayer.unity3d.com/netcode/current/tutorials/helloworld/index.html#creating-a-command-line-helper). I dont understand how i save it as binary (Save As the binary HelloWorld.) since it automatically starts with building after i press select folder
Am i doing something wrong?
okay nvm im stupid
tbh I use parrelsync for everything. Way easier than this commandline business. Tarodev has some good YouTube video tutorials for Netcode for GameObjects that uses it instead of binaries.
ohh nice
You can use the NetworkList to store list of structs and will be automatically synced across network: https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkList-1
Event based NetworkVariable container for syncing Lists
You just have to make sure the struct extends INetworkSerializable, IEquatable
Example of a struct which can be put into NetworkList: ```cs
using System;
using Unity.Netcode;
namespace Structs
{
public struct ClientPing : INetworkSerializable, IEquatable<ClientPing>
{
public ulong clientId;
public double ping;
public ClientPing(ulong _clientId, double _ping)
{
clientId = _clientId;
ping = _ping;
}
public bool Equals(ClientPing other)
{
return clientId == other.clientId;
}
public override bool Equals(object obj)
{
return obj is ClientPing other && Equals(other);
}
public override int GetHashCode()
{
return HashCode.Combine(clientId);
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsReader)
{
var reader = serializer.GetFastBufferReader();
reader.ReadValueSafe(out clientId);
reader.ReadValueSafe(out ping);
}
else
{
var writer = serializer.GetFastBufferWriter();
writer.WriteValueSafe(clientId);
writer.WriteValueSafe(ping);
}
}
}
}
Thank you. The RPC stuff is really straightforward to me, but synchronizing objects feels like suspicious black magic.
Is there any way to guarantee one OnNetworkSpawn will be triggered before another?
Thinking of just chaining listeners, but would be nice to know if there's a way to guarantee order
Like a priority indicator or something
Hey any idea why on my photos server when the game is built I can make and join a server but upon leaving the servers I make or my friend makes doesn't show up until I rebuild the entire game and send it to him again,if you require my code I don't have it rn as I'm on phone but I'm using the photon basics I copied off the net
New Unity multiplayer is so cool
Netcode for Gameobjects: I was assuming Instantiating a GameObject on the server, setting variables and then Spawning the NetworkObject would sync the variables I set before spawning to clients. It appears it doesn't, correct? Is the only way for me to do this to use NetworkVariables for this data instead? Is it guaranteed that the NetworkVariables will be synced before OnNetworkSpawn is called on the newly Spawned GameObject's NetworkBehaviours, or do I need to listen to value changes? The data I set is not supposed to change after the server set it up before Spawn.
Anyone good with reading player.log files to help me understand a crash
Only NetworkVariables will be synced automatically. I could be wrong but I don't think you can assume NetworkVariables will be synced at the time of OnNetworkspawn. If you start a host, change the some networkvariable, then join a client. The client might have the initial value at OnNetworkSpawn (not yet have the synced value). So if you want to do something at Start on the client you should run it both as a function in OnNetworkSpawn and then also run it again as a value change listener on the networkvariable.
Example: ```cs
public override void OnNetworkSpawn()
{
DoAThing();
TheNetworkVariable.OnValueChanged += (value, newValue) => DoAThing();
}
Thanks!
That way you are covered no matter what order the syncing happens in
Does anyone know of a way to listen for the NetworkManager.Singleton.StartClient(); successful connected? Currently I'm listening to OnTransportEvent, but this is pretty poor way to do it. As "connected" event gets triggered even if the Host rejects the connection at approval
Link to Photon discord is in the pinned message.
Thanks, I have removed my message.
Have a look at the Matchmaking Checklist:
https://doc.photonengine.com/en-us/pun/current/lobby-and-matchmaking/matchmaking-and-lobby#matchmaking_checklist
You could also enable the SupportLogger and look into the logs of both clients.
hello, anyone know how to spawn player after a scene loads? with newest networkmanager for netcode
hi i wanna transfer data between two clients in photon
its my ui i just want that when i wrote msg in txt field and send it.its easily shown to all clients
i scrollbar i am using prefebs which are instantiated
i made this launcher code for photon pun
it said loaderanime
and i see this
anyone please help
I know what you've bloody done
There is a Demo from PUN called Launcher, you have applied that to an object
It does have loaderAnime
But your script is not Launcher, you misspelt it
So you think you added your script, when in actuality you added the demo script which you don't want
thanks ive made a multiplayer preview
my friend cant play with me we cant connect to the server
he can make a server but i cant join
but in my pc i opened 2 clients and started server in one of them and i can join from other client
port forwarding
Howdy! ik there's like 20 different solutions for multiplayer.. Idk how to choose.
I am just making a 2d platformer rocket league-like game lol
so i really just need to keep track of the two players..
if anyone has any suggestions for a small game, plz lmk. just trynna make this for me and a friend to play (not locally). no lobbies or anything else complex
BUMP
just put the code to spawn the player in Start, in a script that's in the newly loaded scene
but it spawns him as soon as the host/client is started, and I have to start it when player presses the button
?
So have the script spawn the object when the player presses a button instead
what's the difficulty
but the scene isnt loaded yet when they press the button
you're being very unclear about the setup/what you're trying to do
hostBtn.onClick.AddListener(() =>
{
SceneManager.LoadScene("Game");
NetworkManager.Singleton.StartHost();
});
I have something like this, it's in the menu scene and I need it to load a game scene and start hosting the game, but the problem is that it spawns the player before the scene is finished loading
@hearty dock
Yeah LoadScene specifically doesn't happen right away
you need to wait until the next frame
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.
so, I should do a coroutine for this?
that's one way to wait a frame, sure
Realistically you should use asynchronous scene loading
photon is good
I am getting this error in mirror where it says "Not possible to Convert type "ulong" in "string" "
Ok cool, I’ve seen this one multiple times.. went ahead and went with this option. Ty for reply :]
How do I use gameobject.find for only objects I have ownership over in PUN 2
Find all the objects first, then iterate them and filter by ownership.
so like cam = gameobject.find("camera");
That would only find the first object with that name. You want to use the plural find functions.
so I would do gameobjectS.find
No
and thenhow do I filter by ownership
For or foreach loop, get the view component and check if it belongs to the client.
then what do I do
Find objects of type should work
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
I'd note though, that you should probably cache your components instead of finding them at runtime.
how would you do that
this doesn't work
Ughh... It's assumed that you are at least intermediate+ level coder if you're doing networking, so you should know that...😬
What doesn't?
.
That screenshot doesn't explain what doesn't work.😅
putting the photon view onto the script directly
In what sense does it not work?
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class MoveCamera : MonoBehaviourPunCallbacks
{
public PhotonView pv;
private GameObject player;
void Update()
{
if(pv.IsMine){
Camera.main.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, Camera.main.transform.position.z);
}
}
}
Does anyone has experience with Unity Transport? How does it compare to other networking solutions?
For massive multiplayer games. Can it handle the load?
hey networking folks, do you have any idea how to make a simple patcher for my multiplayer game? I mean, the game should check the game version by start and if it doesn't match, download something
Need to have some kind of backend(server) that you make a request to. For example retrieve the latest version hash/Id or something. Then check with the locally saved hash and if they don't match, initiate the download.
For a large project it's probably more straightforward to test transports by downloading them and doing a load test.
ok thank you, do you have an example for me? Just so I know how it could look like?
Example of what part exactly?
maybe unity docs or something
There's no unity docs for that. It's mostly work outside of unity. The only relevant unity part is perhaps the WebRequest API if you choose to use it instead of your own solution.
ah ok perfect, thank you
Making the request is gonna be the lesser of your problems.😅
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html
On my network architecture my game map is divided by chunks, each tick the server computes the snapshot delta for each chunk.
The same buffer is "brodcasted" to all peers inside the same chunk.
Looks like i can`t do it using Unity Networking, i need to write the buffer per peer. Is it right?
here on BeginSend i need to rebuild the buffer every time
Same for snapshot interpolation. It is ideal to compute the buffer 1 time and broadcast it to all peers
does anyone know how to make SignalR work with unity ?
I want a normal C# app to be the server
(or if you know something better you can tell me)
I basically want players to be able to communicate with the server and the server to know when a player looses connection
is this a web application?
It’s not a web app it’s a console application
you could use photon
it'll automatically create port forwarding for you, and there's in built functions that'll do what you want
Thank you! I’ll try it later today
hey im not that good at c# and i would love some help i looked on some tutorials on how to make a lobby for a game im working on its based on NetCode and i cant find how to fix the error. Any helps would be thanked🙏
its saying right there
that name doesnt exist in NetworkManager
It does tho that is what i dont understand
yea im trying to figure it out too
Delegate type called when connection has been approved. This only has to
ah
its NetworkBehaviour
not MonoBehaviour
you have to inherit from NetworkBehaviour instead
But its passwordnetwork behaviour
thats the name of your script
switch MonoBehaviour for NetworkBehaviour
And thats it?
it also inherits the MonoBehaviour classes so dont worry
i think so
give it a try
Thank you
Ye i will thanks
still didnt work
same error
got any other ideas?
hey guys what would u advice if i wanna create multiplayer for like 2-4 players not setting up servers etc or w/e just them all connection to one players client what way is best? any tutorials you would recommend or tools ?
@cerulean salmon
hmmm that's weird
did it give you a different error?
@civic flicker
dapper dino on yt he got some really good tutorials
nope
hmm thats weird
you said youre following a tutorial
maybe he did something you forgot to do?
I would take care watching any old "MLAPI" tutorials, Netcode for GameObjects has changed a fair amount
With every new connection, Netcode for GameObjects (Netcode) performs a handshake in addition to handshakes done by the transport. This ensures the NetworkConfig on the Client matches the Server's NetworkConfig. You can enable ConnectionApproval in the NetworkManager or via code by setting NetworkManager.NetworkConfig.ConnectionApproval to true.
As you can see here, the name has changed
Hello guys how are you all doing? I am making an app in Unity where I have a list of all characters from the mixamo website in the app in a scroll view and each item s the character image and its name, I finished all the design but now I need to get the characters and I dont have a lot of experience in this field all I know is I need to get a request and then maybe look in the HTML code of the characters and get each one's image and name but idk how to do that can anyone help?
rewrote the entire code still same problem
@cerulean salmoncheck this
that tutorial is probably outdated
it probably has another name yea
honestly i also used Netcode for GameObjects and it was a complete mess just to do simple stuff like synchronizing the players
i switched to photon and had it set up in 1 hour
go with photon then
Get your next game design project organized - Sign up to Milanote for free: https://milanote.com/blackthornprod0621
Udemy Multiplayer course: https://www.udemy.com/course/beginners-guide-to-multiplayer-game-development-in-unity/?couponCode=86D7C0073D7CD59B6C07
0:00 - Intro
0:3...
Is the new unity multiplayer netcode good? For using with steam and p2p
Hi guys, I'm having problems with the UI of my game. The weird thing is that the UI updates when I play the single player part of the game, but in the multiplayer section when 2 players are in the room, the UI doesn't update anymore. Please help.
what exactly does the UI do then when you have two people in the room
and does it work normally as long as there is just one player in the room but still connected to the network?
So the UI, represents the health of the player. So when both players do damage to each other it should decrease the health.
Yes, it does.
I would add a debug line to check whos playerhealth you are accessing, both in SP and MP
I did, and It's pointing at the right player
And who is it pointing at when you have 2 players
I'm trying to get the console logs coming from the other build, to see. But local is getting the right one.
Yes, I confirm each multiplayer instance is capturing the right player.
I debug, the health values, and is not refreshing, it's like the player isn't doing any damage
Are you certain that they indeed do damage to one another?
I checked before and they did, I will check again.
Yes, they are doing damage to each other, it looks like the UI is not receiving the reference.
I got an idea of what could be happening, I'm debuging the script that holds the PlayerHealth logic, and Logged this.gameobject.name and for some reason is taking the other instance reference instead of his
is it possible to call a Coroutine as a server RPC? (Unity networking for gameobjects)
You certainly can as a result of an RPC
Thats what i get:
Error: ```(0,0): error - RPC method must return void!````
Code:
void start(){
StartCoroutine(FootstepGenServerRpc());
}
[ServerRpc]
private IEnumerator FootstepGenServerRpc(){
begin:
for( ;steping; ){
GameObject step = Instantiate(Footsteps,new Vector3(transform.position.x, transform.position.y, 121f), transform.rotation);
step.GetComponent<NetworkObject>().Spawn();
yield return new WaitForSeconds(.3f);
if(!steping) break;
step = Instantiate(Footsteps2, new Vector3(transform.position.x, transform.position.y, 121f), transform.rotation);
step.GetComponent<NetworkObject>().Spawn();
yield return new WaitForSeconds(.3f);
}
if(!steping){
yield return new WaitForSeconds(.3f);
goto begin;
}
}
Have a separate RPC method that does whatever you want with the coroutine
Do you mean something like this?
void Start(){
FootstepGenServerRpc();
}
[ServerRpc]
private void FootstepGenServerRpc(){
begin:
for( ;steping; ){
GameObject step = Instantiate(Footsteps,new Vector3(transform.position.x, transform.position.y, 121f), transform.rotation);
step.GetComponent<NetworkObject>().Spawn();
StartCoroutine(WaitServerRpc());
if(!steping) break;
step = Instantiate(Footsteps2, new Vector3(transform.position.x, transform.position.y, 121f), transform.rotation);
step.GetComponent<NetworkObject>().Spawn();
StartCoroutine(WaitServerRpc());
}
if(!steping){
StartCoroutine(WaitServerRpc());
goto begin;
}
}
[ServerRpc]
private IEnumerator WaitServerRpc(){
yield return new WaitForSeconds(.3f);
}
No. Normal method for the RPC that then does whatever you want with the coroutine.
i either missunderstand you or it just doesnt work. though i think i missunderstand because i aint that good in networking. Could you be so kind and give me an example pls😅 ?
Not really sure what you are trying to do here when it comes to the coroutine. I would not assume the networking solution would manage coroutines for you
i need to spawn footsteps for all the players running around the world and because clients cant spawn network prefabs i need the server to spawn them. Now, in the footsteps function i need to wait between those steps .3 secs until i spawn the next. thats why i would need a coroutine
what are the current networking solutions that unity has? I haven't kept up on Unity in a while
As in official solutions? Netcode for Entities, Netcode for GameObjects and Transport. There also are services like Relay and Lobby.
Wait, what are those? Can you forward me to resources for these? Do people still use Mirror and stuff?
Check the pinned message. Yea you'll still likely find thirdparty stuff superior for most projects.
Photon has cool new products
alright thanks mate
So I got an issue right now. I'm instantiating 2 players into a room, both have the same health scripts. But if I Debug.Log(this.gameobject.name), is printing the name of the other player instead of his. Is there a way to prevent this?
Im Makeing a project online multiplayer and it gives the following error when I'm done writing the ui code (its useing network manager)
Here is the code aswell
Anyhelp much appreciated
I don't see how that code would print a name of some other object. Are you maybe changing the name too late for that?
So this code works for first person who joins, when second person joins.
But it doesn't show first person's color to the second person that joins.
photonView.RPC("SetColor", RpcTarget.All, new Vector3(setColor.r, setColor.g, setColor.b));
[PunRPC]
private void SetColor(Vector3 setColorVector)
{
Color setColor = new Color(setColorVector.x, setColorVector.y, setColorVector.z);
GetComponent<SpriteRenderer>().color = setColor;
}
any suggestions? 🤔
This is the code I'm using for Debug.Log it cames from PlayerHealth script, and it's attached to each Player.
By printing it, it takes the other player object name instead of his own object name
Sounds like the information is just not synced to new players. Send the colors to the joining player on join event.
I don't see how that could happen. How are the names set? You could try printing InstanceID instead.
The console log from the both builds.
You sure the other PlayerHealth is running its Update?
How do I make sure is both are running their update?
hey, I struggle to flip the character sprite on guest clients. I have followed the tutorial of Photon, which I use, but it wont do it
https://gdl.space/mijoyuceri.cpp
Try passing gameObject as the second parameter to Debug.Log
This allows you to highlight the source of the log by clicking on it
Local Build vs Android Build
Does clicking on the console messages highlight different gameobjects?
Yes, it highlight the correct gameobject.
So 2 logs back to back highlight different gameobjects?
The whole issue ive been having is passing variables between clients..
Seems like every new instance erase all previous data and re-initializes variables.
I am even trying to do
PhotonNetwork.LocalPlayer.CustomProperties["go"] = newPlayer;
PhotonNetwork.LocalPlayer.CustomProperties["color"] = color;
``` when i create player
and i set colors when new player joins
```csharp
foreach (var player in PhotonNetwork.PlayerList)
{
GameObject go = (GameObject) player.CustomProperties["go"];
go.GetComponent<SpriteRenderer>().color = (Color) player.CustomProperties["color"];
}
```but it says `go` does not exist
Seems like every new instance erase all previous data and re-initializes variables.
Clients don't have any data that isn't sent to them through some means. Also make sure you aren't confusing properties of one player with properties with some other player.
Storing gameobject references in custom properties doesn't seem right. You probably need to sync the photonView viewId and convert to gameobject yourself for this to work.
i thought photonnetwork would contain data from other clients and be able to transfer them to new ones
i'd imagine that's how multiplayer works in general
and ig i just assumed there was an easy way to do it
Don't assume that anything is transferred until you know about a feature that does it.
Multiplayer solutions can't really guess what state needs to be transferred
Here's the two console logs
Yes, both highlight different gameobjects
Now only one updates the health value, the other not, and both have to decrease their values when colliding
Only one does it.
bruhhh why didnt anyone suggest to change RpcTarget.All to RpcTarget.AllBuffered lmaooo took me a whole day to find this xd
Because assembling room state from bunch of replayed messages that get removed when the player who created them leaves feels hackier and more error prone than just explicitly sending the state on player join or using properties.
Hey Danny I manage to figure it out, my error I had to make some some changes by implementing OnPhotonSerializeView and other work around with the way the players spawn to the level. Thanks for the help
Do y'all support Photon dev here
what is better, mirror or netcode?
What is better, cats or dogs?
😂
well im super new to unity, been using mirror, just starting a new project and wondering the netcode has any benefits to it?
Research it. And compare to your experience with mirror.
(Photon) How can I synchronize text and inputfield text across clients? RPC?
many may not remember, but Mirror only exists because Unity abandoned their previous netcode 🙂
In unreal engine, There is replication for multiplayer, But in unity, Which method is officially used for multiplayer?
Netcode for GameObjects is the official Unity multiplayer package
There are other solutions like Mirror and Photon (PUN, Fusion)
Welsh do you know why fizzy steamworks doesnt work?
Watching a tutorial on how to set it up and all they did was import mirror and fizzysteamnetworks but i did and got 2 errors
Which method would you prefer for making professional games?
Not sure, I remember reading about it in the Mirror Discord though, they're good over there
which method is most popular in other words
Popularity ought to be irrelevant
You pick the solution that works for you
I personally found Mirror to be very intuitive, and it has all the features I wanted
ok thanks!
I've been wondering this for a long time.
without custom code. Every netcode project is different and no generic solution can satisfy all. If you specify what you mean by sync a input field the how to should be obvious.
So that if a user types something into an input field, the input field text updates to it across all clients.
same for text.
and how is it not obvious how to implement that?
why would it be?
I know almost nothing about Photon.
Should I use an ExitGames.Client.Photon.Hashtable?
A proven strategy is to learn the API and features of the tools you use and then use them to solve your problems.
Why would an implementation be obvious though?
because a fully specified problem is a solution
what
Have you tried looking up how to synchronise data between clients?
yes
So why didn't that help?
I'm using Unity's networking system and I have a problem where when I spawn in a client, the mouse position gets really offset. I'm trying to spawn a gameobject at the mouse, but the object is sometimes nowhere near the mouse, always at least a bit away from it
because I didn't comprehend it.
Did you try to figure out the bits you did not comprehend?
And you gave up?
no
I don't get why a Hashtable is useful here
sounds like you are asking random unrelated questions
It's their purpose
So what issues have you had with RPCs?
not getting them to work obviously.
🥄
How descriptive
I don't really know how to use them.
You just mistyped RPC in your code, that's all.
Yep
is it possible to call rpcs in other classes?
They're just methods
Because not getting it to work, obviously was exactly enough info to solve your issue.
yes but you have to call them with a string, right?
Right so make a method that calls the RPC, and call that method instead
right stupid me
Don't I have to do something like this too?
I'm confused. ```cs
PhotonView view;
void Start()
{
view = GetComponent<PhotonView>();
view.RPC("RPC_SetText", RpcTarget.AllBuffered, dict.randomLetterText);
}
[PunRPC]
void RPC_SetText(TMP_Text text)
{
text.text = text.text;
}
please don't call me even more stupid.
I know.
I wanna set more text strings than that though.
I wouldn't sync the actual Text component
no?
No
I'm syncing the text of it though.
You send the component in an RPC, can Photon even do that?
text.text = text.text sounds like saying string foo = foo;
Lets say I type a message in a chat, what do you think happens
Like here in Discord
internal static void RPC(PhotonView view, string methodName, RpcTarget target, bool encrypt, params object[] parameters)
idk
Engage your brain, this is an easy question
In simple terms, what does this chat menu do
it gets sent to you via their servers?
Discord?
What does it send?
data
It doesn't send my text field
lol
It sends my message, the string I type
Every client has this script, which references their own input field
So a client sends one of those to every other client?
Right
So what's the issue with sending a string using an RPC?
You don't need to send over the text object
My instance of the script in my client references my text field, not yours
So when you RPC me a string, it will set my text field
you're saying that I have to make a function for every single text field?
No, I have no idea what the structure of your game is
I mean technically most games involve words, so that's a largely unhelpful description
you have to come up with words.
that contain a set of random letters.
not come up with, enter.
So you give me letters, I make them into a word
Right
So the host sends everyone a string "EG" or something
Then they can all send back their string "Egg"
yeah if you're talking about the input field.
So you want an RPC to send everyone the random letters, literally just send them a string
so it would be one function for each input field then?
No
Are you suggesting every client needs their own RPC to send the data?
I guess.
Well they don't, there's probably some ID you can send with their answer
Answer as in the thing they typed yes
Well I don't know PUN, but I assume you have a way of identifying clients
Name, number idk
oh ye
Wouldn't this work? ```cs
void Start()
{
view = GetComponent<PhotonView>();
view.RPC("RPC_SetText", RpcTarget.AllBuffered, dict.randomLetterText.text);
}
[PunRPC]
void RPC_SetText(string text)
{
dict.randomLetterText.text = text;
}
if I were to call the function somewhere else (rpc).
whenever the random letters are updated for instance.
I assume that this code would sync whatever is typed in that field to all clients at the Start
Sure, give it a go
something like this: ```cs
public void CallRPC(TMP_Text textField, string text)
{
view.RPC("RPC_SetText", RpcTarget.AllBuffered, textField, text);
}
[PunRPC]
void RPC_SetText(TMP_Text textField, string text)
{
textField.text = text;
}
for implicitness.
I think you ought to get a dictionary and define that word
Because if it were even a good idea to send the text object, it'd be for explicitness
I can't figure out how exactly the script is supposed to know what text field I'm talking about.
The script has a reference to a text field right?
you said that I shouldn't.
should I?
No for fucks sake
then what?
let's say that I were to have multiple text fields.
how would the script know which one I'm talking about?
if the only parameter was a string.
Give me a few minutes
It's too early for gin, I'm writing an example instead
oh ok thanks.
public class RandomLettersOrSomeShitIdfk
{
public TMP_Text randomLetterText; //Set this in the inspector
public void CallRPC(string text) //Method to call this RPC from other classes
{
view.RPC("RPC_SendRandomLetter", RpcTarget.AllBuffered, text); //RPC call
}
[PunRPC]
private void RPC_SendRandomLetter(string text) //When this is called, every client will receive this RPC
{
randomLetterText.text = text; //This will set the client's individual text field to this text
}
}
This script will exist on all clients, there will be a Text object on all clients that this script refers to
this is what I'm talking about, that's one function for one text field.
So each client has how many text fields?
Two
Well that's expected surely, those fields do different things
^
You are testing me
not really
Oh you fucking are
You know full well you haven't been crystal clear, so I won't apologise for making a mistake
@shell nest This person is taking the time to talk to you, stop being insufferable.
@olive vessel This is probably a time to take a break and leave it, it's not worth the annoyance.
Alright, so I'm working on the Multiplayer aspect of my game now through Photon. I have a 'NetworkController' script attached to a GameObject which has something along the lines of this in it..
OnConnectedToMaster() {
PhotonNetwork.JoinOrCreateRoom("Test", roomOptions, TypedLobby.Default)
}
OnPlayerEnteredRoom(Player newPlayer) {
PhotonNetwork.Instantiate("player-blue", gameController.transform.position, gameController.transform.rotation);
}
The player-blue prefab has a PhotonView attached to it, with a PhotonTransformView attached aswell. But when two players join, it creates the Prefab but it doesn't seem to be syncing the positions.
It's very possible I'm doing this wrong. Any help greatly appreciated.
My 'Player' prefab (screenshot above) contains all of the scripting.
public class Attack : MonoBehaviour
{
[SerializeField] private bool isAttacked;
[SerializeField] private Slider playerHP;
[SerializeField] private int damage;
[SerializeField] private PlayerMovement playerMovement;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (isAttacked && playerMovement.view.IsMine)
{
playerHP.value = playerHP.value - damage;
isAttacked = false;
}
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isAttacked = true;
playerHP = other.GetComponentInChildren<Slider>();
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isAttacked = false;
}
}
Hallo, how can i identify only a single player (the one that is being attacked)?
How do i make an string Network variable? Every solution from the documentation is outdated or doesnt work. (using Networking for Gameobjects)
thats the problem. idk which namespace i need to include to use Fixed private StringContainer m_StringContainer = new StringContainer(); or private NetworkVariable<FixedString128Bytes> m_TextString = new NetworkVariable<FixedString128Bytes>();
thanks, i miss read the Unity.Collections with System.Collections
also, how do i pass a param to an Server RPC method? i get an mega error when i try
public class Weapon_Destroy : NetworkBehaviour
{
public GameObject player, PickedUp;
private Inventory_Handler inv_handler;
// Start is called before the first frame update
private void OnTriggerEnter2D(Collider2D collision){
if(IsOwner){
DestroyWeaponServerRpc(collision);
}
}
[ServerRpc]
private void DestroyWeaponServerRpc(Collider2D collision){
if(collision.gameObject.tag == "Player" && collision.GetComponent<Inventory_Handler>().lootcount < 3 || collision.gameObject.tag == "Bot" && collision.GetComponent<Bot_Inventory>().lootcount < 3){
Destroy(this.gameObject);
gameObject.GetComponent<NetworkObject>().Despawn();
}
}
}
Error:
Don't know how to serialize Collider2D. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. If this type is external and you are sure its memory layout makes it serializable by memcpy, you can replace UnityEngine.Collider2D with ForceNetworkSerializeByMemcpy`1<UnityEngine.Collider2D>, or you can create extension methods for FastBufferReader.ReadValueSafe(this FastBufferReader, out UnityEngine.Collider2D) and FastBufferWriter.WriteValueSafe(this FastBufferWriter, in UnityEngine.Collider2D) to define serialization for this type.
I don't think there's a built in serialiser for a Collider2D
Maybe try finding a way of passing what you want rather than the entire thing
also decide if this is supposed to be client or server authoritative, if its client-auth, you can do all the validation on the client and just send a despawn signal, if its server auth, you'd want to detect that trigger collision on the server anyway and no RPC is needed.
if i try to despawn it on the client it gives me an error that only the server can spawn/despawn network prefabs
Does anyone have any advice here? A little lost otherwise. If I just add the PhotonView to the 'Player' prefab and remove it from both 'astronaut-blue' and 'PlayerPrefab', it seems like once there's two clients connected, the master is controlling the secondary's screen.
make sure to use photonview.isMine whenever you're dealing with movement or individual syncs like hp/stamina
Get your next game design project organized - Sign up to Milanote for free: https://milanote.com/blackthornprod0621
Udemy Multiplayer course: https://www.udemy.com/course/beginners-guide-to-multiplayer-game-development-in-unity/?couponCode=86D7C0073D7CD59B6C07
0:00 - Intro
0:3...
I actually am as far as I'm aware. if(!photonView.IsMine && PhotonNetwork.IsConnected) { return; } is on any move request pretty much.
I'm on my phone rn but maybe try to check that video
it helps setting up a lobby + characters
my player movement has stopped syncing. i have network transform with client auth, rotation and position ticked. it is syncing rotation just not position for the clients, any ideas why?
Did you perhaps add a feature that messes up transforms since it worked ?
Not that i can think of. its a pretty fresh project, just has player movement, and weapon switching, the weapon switching is just a syncvar hook that enables / disables the child objects
host can see both players moving / switching weapons. the client cant see the host moving, only rotating and changing weapons
public class Attack : MonoBehaviour
{
[SerializeField] private bool isAttacked;
[SerializeField] private Slider playerHP;
[SerializeField] private int damage;
[SerializeField] private PlayerMovement playerMovement;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (isAttacked)
{
playerHP.value = playerHP.value - damage;
isAttacked = false;
}
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isAttacked = true;
playerHP = other.gameObject.GetComponentInChildren<Slider>();
playerMovement = other.GetComponent<PlayerMovement>();
}
}
public void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
isAttacked = false;
}
}
}
i want to have my enemy attack a player and make him lose HP, while the other one still has full HP. my problem is that for some reason the one that is being attacked is not the one losing hp, and vice versa. (im using photon)
Hi, how can I fix this error?
That's not an error. If you want to change it, go to the PhotonServerSettings ScriptableObject in your project.
i just learned about RPCs
the enemy is removing HP from my players
but whats weird is
if it attacks player 1 it removes hp from player 2 and vice versa
So I might of been overthinking my project's instantiation.
I have a 'PlayerPrefab' which hosts the camera, movement, controllers etc and I have an actual character inside that Prefab which has a PhotonView & PhotonTransformView attached to it.
When I start the game, I have set up to automatically join or create a room, and Instantiate the character (which has the photon views) and parent that to my PlayerPrefab.
When another person joins, I see their character but their position is not synced at all and I'm unsure why
Under that inactive capsule is where the first character (me) would load in.
And then the prefab which gets instantiated and parented to 'PlayerPrefab' looks like https://i.imgur.com/VeIF1uM.png
why dont these glasses sync up but the movement etc does it?
Is it cause of this ?
i got if (hasAuthority)
Isn’t if (hasAuthorityk) to see if it’s the client so it will only do it for the client ?
But then that’s weird cause I have my movement func inside a if (hasAuthority) but that replicates, Is it cause the player is a network transform ?
Bump on this.
if youre using netcode for gameobjects then you need a client network transform
umm just a question, Ill send a video of my animations, They do not work online, And when i am in the scene view at game view, In the game it looks as it should but in the scene view it looks well kinda weird
Or wait, No
When i come into a certain radius of the player it starts animating
tf
Think i found it
I managed to get player positioning, rotationing & animations synced. On any object that I want to have clickable, I have a 'void Click()' function within the script attached to that object. Click() is called by a Raycaster on my PlayerController which checks to ensure that what I'm looking at isn't null and is within a distance of < 2.5m. What is the easiest way that I can simulate a click across all clients?
GetComponentInChildren<PhotonView>().RPC("ClickObject", RpcTarget.All, hit.transform.gameObject); is something I tried but it's complaining saying GameObject doesn't exist.
I have a guy who is programming a game for me is having this issue with photon’s network if more than 4 players try to join 1 room. Any suggestions…? Thanks!!!
https://cdn.discordapp.com/attachments/1017081313834049596/1029078114149601311/unknown.png
It’s creating a duplicate room when the 5th player joins and not keeping them in the same room.
Okay, it turns out you can't pass objects over through Rpc, fair enough - so my solution was to pass over the Vector3 and do a very small Physics.OverlapSphere() on the hit.point of my ray cast to send a message to objects.
Well now that's gotten me the error message:
RPC method 'ClickObject(Vector3)' not found on object with PhotonView 1001. Implement as non-static. Apply [PunRPC]. Components on children are not found. Return type must be void or IEnumerator (if you enable RunRpcCoroutines). RPCs are a one-way message.
With this code:
[PunRPC]
void OnClick()
{
RaycastHit hit;
if(Camera.main)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.transform != null && hit.distance <= 2.5f)
{
// ClickObject(hit.point);
GetComponentInChildren<PhotonView>().RPC("ClickObject", RpcTarget.All, hit.point);
}
}
}
}
[PunRPC]
public void ClickObject(Vector3 objTransform)
{
RaycastHit hit;
Collider[] x = Physics.OverlapSphere(objTransform, 0.1f);
foreach(Collider c in x)
{
c.SendMessage("Click", SendMessageOptions.DontRequireReceiver);
}
// objTransform.SendMessage("Click", SendMessageOptions.DontRequireReceiver);
}
The PhotonView prefab itself is childed to where this script is being run.
Why are the scores adding on top of each other? Also, why can both players select the input field at the beginning of the match? https://pastebin.com/1S8GPbJg
recruiting goes here https://forum.unity.com/forums/commercial-job-offering.49/ #📖┃code-of-conduct
You can send view IDs of PhotonViews and convert them back to PhotonView references.
So I thought about solving this problem without serializing a whole gameObject to pass it to the Server Rpc method. But there comes no other way to my mind when i think about destroying a NetworkPrefab in the scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class Weapon_Destroy : NetworkBehaviour
{
public GameObject player, PickedUp;
private Inventory_Handler inv_handler;
private void OnTriggerEnter2D(Collider2D collision){
if(IsOwner){
DestroyWeaponServerRpc(collision.gameObject);
}
}
[ServerRpc]
private void DestroyWeaponServerRpc(GameObject collision){
if(collision.gameObject.tag == "Player" && collision.GetComponent<Inventory_Handler>().lootcount < 3 || collision.gameObject.tag == "Bot" && collision.GetComponent<Bot_Inventory>().lootcount < 3){
Destroy(this.gameObject);
gameObject.GetComponent<NetworkObject>().Despawn();
}
}
}
Do you have any ideas how to either serialize the whole GameObject or have another way to reference to the to be destroyed gameObject?
maybe you should redesign this whole system to make it more compatible with networking constraints
a good multiplayer design eliminates unnecessary messages/arguments wherever it can
Well you are right. it was originally planned as a Single player playing against Bots. But now i planned an additional local multiplayer. The Game is way to far on the code base for it to 100% optimize for mulitplayer. But lets say i convert it. I then still wouldnt have any clue how to destory a network perfab using ServerRpc
converting a game to multiplayer that wasn't planned as such is a death march project
Ik but i still wanna go for it
There MUST be a way to solve the problem
there is a way, but it isn't worth it
pls tell me i ll figure it out
there is nothing to figure out, its just a long journey digging through all the crappy solutions and workarounds you have to create, fix endless bugs and issues and realize that it took you about 5 times longer than rewriting the whole thing
ok lets say i rewrite it, what would i change to destroy that gameobject with an server rpc
actually i am rewriting it rn more or less
You would work with IDs so you don't have to serialize whole gameobjects
Client sends ID to server, server destroy network object
But having client decide over network object despawn sounds like a smell
You probably should rethink the whole logic to have the server decide what to destroy
In a "somehow perfect" network solution, server is authoritative and client sends only player input
Brilliant, thank you. Thats where I am going to start working tonight. Now i just have to figure out how to work with that ids.
👍
Have fun 👍
With Netcode NetworkVariables is there a way I can have a nested Array within a struct? For example (screenshot). I cannot use Team struct in the NetworkVariable due to the Jersey[] variable. But Jersey type is INetworkSerializable and can but put into a NetworkVariable by itself.
How are you serializing Team? I think you can write the array length and then each Jersey in the array, on read create an array with the written array length and read back each Jersey
So it would work i changed Jerseys[] jerseys to Jersey jersey1 Jersey jersey2, Jersey jersey3 etc...but that seems bad
I agree that it seems bad. Does your current version throw errors or are you just not getting the correct data?
It throws this error:
Ah, I see. To be honest I don't know Netcode well enough to give a definitive answer to this. I believe the issue is that the "normal" C# arrays are a managed type, which is why you can't use it in the NetworkVariable. Not super sure if Netcode has a premade solution for this. If not, you could implement your own implementation inheriting from NetworkVariableBase. Would look along the lines of this: https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/index.html#complex-value-types
Introduction
Again though, not sure on this in general and maybe someone knows how to fix your issue without doing this
This is the link I actually meant to post btw https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/index.html#custom-networkvariable-implementations
Introduction
This kind of thing should not be handled by net variables but rather by a custom message that maybe just sends a json blob for such low frequency complex messages. A net variable is intended for low complexity, flat, primitive data
How do you use delta time? in netcode?
For what purpose?
Movement
controller.Move(inputDirection.normalized * (speed * (Delta?)) + new Vector3(0.0f, verticalVelocity, 0.0f) * (Delta?));
This happens on both the client and server this move logic
that doesn’t make sense for plain netcode
you’d only run that code on one side with its local fixed deltaTime and sync the result to the other
if you want to make a deterministic sim (where you sync only inputs) you’d have to implement a network tick system and use the tick interval as deltaTime
controller.Move(inputDirection.normalized * (speed * minTimeBetweenTicks) + new Vector3(0.0f, verticalVelocity, 0.0f) * minTimeBetweenTicks);
it is just so insanely fast no clue what I'm doing wrong
I call this from onTick
minTimeBetweenTicks = (1f / NetworkManager.Singleton.NetworkTickSystem.TickRate);
NetCode - Is it good for MMO RPG games ?
In the hands of a large exceptionally talented team, it can be, but they’d probably want to make their own framework. Generally for a mmo, a netcode library is only a tiny piece of the puzzle.
Hello :D, someone know why in my game i cant get a clientconnection if i'm not a host too, i want to change my player prefab to another variant
there is the code:
The problem is when i want to get the connectionToClient of my only client this is null :c
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is a simple server authoritative movement script I wrote, how can I improve this?
By improve, i mean improve security
I know i can do !isOwner
Is there a security issue?
You could validate the input before using it to make sure that it's not outside the expected ranges.
Hi guys, does anyone know how to build the server build when the server build option no longer available? Thanks
Hello! I'm using NGO + Relay and when i'm trying to join a host through a generated joinCode i get that the join code doesn't exist... I have basically copied the docs example for joining and generating with join codes (https://docs.unity.com/relay/relay-and-ngo.html#Configur)
Here's my snippet for joining using TMP input field (see image) I'll also send the error I'm getting
I saw this forum post about this issue: https://forum.unity.com/threads/problem-joining-a-private-lobby-through-lobbycode-joinlobbybycodeasync.1287908/#post-8171102 but I'm already using TMP_InputField as my joinCodeInput... what could be wrong?
It’s on the left side, below Windows, Mac, Linux
Thanks for the reply!!
I wrote a cheat sheet for Netcode for Game Objects like...the calls any normal person would make. https://global-log-c3f.notion.site/Cheat-Sheet-f615aa3bbcab415abe9647f62aa88339
Includes all the little how-tos for RPC that will eventually be fingertip knowledge
@vestal stump I might be able to help
Hey, thanks! Appreciate the very quick helping offer
You want me to dm you or just keep everything in this place? 🤔
Best keeping it here, then I can be nosy
Yes keep it here

First I had this issue. Things worked with one character, broke the second the second bean got in tho. The host was unable to move, the camera didn't work with him at all, and there were some other annoying issues
At this point, each player had his own camera attached to them
Let me see the controller code
Then I got someone's advice and just used one camera in the scene and referenced it from each individual player
It makes the usage of the host character possible, even when I drop the second player into the scene, but now the second player doesn't work.
Also, whenever I build my game, for some reason I can't move???
It works perfectly fine in the editor game simulation tho???
It sounds like you are trying to move the client but the server can’t prove it
Sure! I'm new to Unity and C# tho, so my bad in advance
Holup, my bad
Hastebin is best imho
New to Unity and C# and doing multiplayer, what could possibly go wrong
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.
Citations needed

This is my movement script. Also want the camera movement script or is this enough?
So what you gotta do is move the actual movement into a ServerRpc
Introduction
I have a simple 2d one moment
sure
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is like the bare minimum
Obviously you’ll just put your rigid body code in a serverrpc
Not the input code
The actual part that moves your entity
Mhmm mhmm
Notably
Btw
Id recommend not doing multiplayer or Unity without learning c# but we all know you aren’t gunna take the proper steps amiright
Does it make a difference whether I use OnNetworkSpawn or Start
It depends on the use case
I know Java so I didn't really bother properly trying to figure out C# lol
How so?
Referencing variables no, but doing things that need to be seen by everyone yes
Thanks!
Mhmm mhmm
Still don't exactly know how to work with RPCs but found a tutorial so will look into that
Imma go off for half an hour for smth else now, thanks
Btw, I doubt just changing the movement will be enough to fully fix this
I'm additionally getting the error "GetSceneOriginHandle called when SceneOriginHandle is still zero but the NetworkObject is already spawned!" with my Client
No idea what Unity wants me to do
Did you create the RPC?
not yet, will do in a bit
Just thought I'd throw that error message out there before leaving for a while
If you have a method called that figure out what’s wrong with it 😂
I just know I had this same exact issue you are having now
I'm using Photon to make a multiplayer game. When I call the RPC on the second line in the If statement, it gives me a "Write Failed" exception. It works without the parameter "mouseRay.collider," am I using the parameter call wrong in this method?
This is the method I'm calling
Oh, it seems that Photon doesn't support this sort of parameter
Is there a way to just sync a gameobject component with any changes made?
I'm back!
Used RPCs now, nothing changed, still doesn't work
What errors is it throwing?
The same as before.
This
Everything is perfect with the Host as long as it's the Editor version, but the Client do be doing nothing either way
He just
Flying, essentially
Not even affected by gravity
Just staying in the air
Also, again, the Build version isn't working while the normal editor version is, even if I just create a single host
I can move in the build, but only if I'm not grounded
So I can't walk, but jump
I can do these things in the editor tho 🤔
Hi, what's the best networking solution to my games?
The best networking solution to your games is the one that fits your games the most.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Any particular reason the animations make it to the server for the host but not the client? I did create an OwnerNetworkAnimator recommended by the unity docs
what would be the best for an fps online game? free of course
thoughts on riptide?
Probably nothing if you want to have more than 20 players
I don't
probably just a few friends
As for which one to choose, is mostly a preference thing. Most of them work in a similar way and have similar API. Might want to compare the plans that they offer(including the free plan).
Then anything would work.
Might still want to go over and compare the free plans and see of there are any additional limitations
Is it possible to remove data from scriptable objects for server build?
I have some AnimationClips reference on scriptable objects that i use both on server and client but it is not needed for server
Would this be the right channel to ask this? For instance I need my game to access a mySQL database and I want to know the best way to go about it. I was told I should use PHP in the middle instead of accessing my DB directly from my C# code.
All frameworks have an equivalent of onNetworkStart and onClientConnected callbacks
What they probably meant was that you should have a layer between your client and your backend DB, assuming the DB lives on a server. You probably don't want clients making their own queries and hoping whatever access controls hold in your DB solution.
It's just a language commonly used for backend stuff, but C# and many other languages get use in the backend too
Especially back in the olden days
Using a language you know and is capable for the job is probably easiest.
OK.
Bump, collisions are also collected on host but not client
I do in fact have the network rigidbody and network animator
Ive tried to make it into a network in code and it made no difference
has anyone here used normcore? my prefab is spawning in a weird spot and im trying to change the default spawn location
I'm looking for a cheap/(free if that's a thing) way to host a server for a chess game. Someone told me to use microsoft PlayFab but it does look really scary (like one step to the side and I'm billed hard, I just don't know if it's safe to use).
Do you know any alternatives that don't have that factor ?
my thought would be probably one of the free plans on aws/azure that then charge a couple cents per overuse
or spin up a .net backend you just have running while you play?
and use that until launch?
alr I'll look into how spending limits are setup in aws then. thank you
When I try and use this script the camera is on the other player. I looked in the inspector and player is set to the right player.
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class MoveCamera : MonoBehaviourPunCallbacks
{
public PhotonView pv;
public GameObject player;
void Update()
{
// forEach()
if(pv.IsMine){
Camera.main.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, Camera.main.transform.position.z);
}
}
}
How can i test my steam multiplayer game without having to run into my brothers room every time i want to test something
Nah didnt work
Just says "Client already made"
Yeah I don't think you'll be able to test the Steam bit on one PC
ye :/ IM setting up a vps rn
if anyone is on i need help trying to figure this out, i have my original project open and a clone i all the way up to having the HOST, SERVER, CLIENT. but when i host on my main project and go in the game, and then switch to my clone and join as client i cant see either player on either project, any ideas?
pretty sure if your wanting to connect to yourself, your supposed to build the game not clone the entire project
i built an ran the game on both projects
you play the game in the editor and open the build from that same project. not anything on another project
so build it from the original project, host from build the client from unity project?
yeah
okay will try!
didnt work still cant see each one another, i even tried following along unity's golden path and im still having the issue of not seeing client and host
Show the setup of the player prefab
It might also be useful to add some logs, NetworkManager has a OnClientConnectedCallback
i took screen shots i dont know where to find them in file
If you use Windows + Shift + S they are copied to your clipboard
sorry i still dont know where that is im so sorry
If they're in your clipboard, you can just Ctrl + V to paste them here
And that is set as the prefab on the NetworkManager?
i assume so its what spawns when i host or join as client
So if you host using the editor, and join as a client using a build, what happens?
Can you show the hierarchy of the editor when a client joins
ill try that ive only done the other way around
Well if you use the editor to host, you can see any errors
okay one moment
this is the hierarchy on the host
not showing the client join
but the client is in the "game"
no errors
What does the client see now?
just the scene but not the host
Create a script and stick it on the NetworkManager object, give me a minute and I'll write some code for it
okay will do thank you so much!
using Unity.Netcode;
using UnityEngine;
public class RenameMe : NetworkBehaviour
{
private void Awake()
{
if(isServer)
{
NetworkManager.OnClientConnectedCallback += ClientConnectedCallback;
}
}
private void OnDestroy()
{
NetworkManager.OnClientConnectedCallback -= ClientConnectedCallback;
}
private void ClientConnectedCallback(ulong clientId)
{
Debug.Log($"Client joined with ID: {clientId}");
}
}
If my Notepad++ code is correct, this should log whenever a client joins the server.
Rename this class to the name of the file.
There's a callback for disconnect too, might be handy to add, but this should tell us if the client is actually joining or not
Huh, I thought NetworkBehaviour had isServer
i fixed the isserver one the i in IsServer was lowercase
what about the yellow one?
It's a warning
You can either add override before void on OnDestroy, or just leave it
you think ill be fine. the other OnDestory i have is so controlling is indipendent from each client
screw it gonna run it
okay so no dice
i guess the client isnt even joining in the first place
Well that'll be a field on the Transport component, which will be attached to the NetworkManager
Yeah that works
i guess not for me
the server needs a listen address, else nothing can connect (at least it used to be that way)
if you want it to listen on all addresses you can set it to 0.0.0.0
i set it to 0.0.0.0 still wont work
can you be more specific
been troubleshooting for the past hour
i build and run, host on the project and client on the build both instances join a "game" but i get no debug.log that was made to show when client joins so i know its not joining, also isnt in hierarchy so its just not connecting
at first i thought it was connecting i just couldnt see the two prefabs but i now know they arent even connected
you should get a log message that the connection failed
i get nothing of the such
So how do you connect the client
well ive run into a new problem, BUT i would try connecting by build running and then hosting from project and then clienting from build if thats what you mean
No, I mean how do you do it
What says "Go and connect to this server"
Where do you tell the client to connect
only thing i think i can answer that with is the network manager and unity transport
Where have you called NetworkManager.singleton.StartClient()
I presume you have also done blah.StartHost() on the server too?
Oh for God's sake
im pretty sure this is all ive got manually made
wait
wait
i stg im an idiot
well atleast THANK YOU for opening my eyes! im so sorry
It's always the simple things
but what about the blah.starthost whats that
Well that was because I couldn;t be arsed typing out the full thing twice
ahhh okay
well lets try now
but ive run into a new bery recent problem on the build and run clicking host server or client does nothing
