#archived-networking
1 messages · Page 24 of 1
Make sure to initialize the network list in awake method. You can subscribe to onlist update event and get event when anything in list modified, added, removed, etc
private NetworkList<int> playerDataNetworkList;
private void Awake()
{
playerDataNetworkList = new NetworkList<int>();
}
yeah i had done that too
And only server or host can add or remove or update list not clienst
and i also tried to initiale it when i instantiated it
You deriving from NetworkBehaviour?
yeah i made sure that only host is updating it
deriving from network behaviori?
i do am using a network behavior component
The class should use this
public class PlayerDataHandler : NetworkBehaviour
Not MonoBehaviour
yeah i am implementng that too
and there should be component NetworkObject added in that gameobject
network object is also attached as component
ohh
currently i am not using that anymore
i am just using two seperate arrays which are being updated by one another
so thats not the problem
but i am encountering a stack overflow when i am updating the value of a variable
i have a playerside variable (which is local and not network)
i am selecting the starting side
from the host side
and then
calling clientRpcto update its value on the client side
Maybe the function calling itselft again and again causing stack overflow
btw you should come to new Rpc, the clientRpc and serverRpc is legacy now
i wasnt making something too big
it was just tic tac toe so i though i could use them
so i should only use Rpc keyword?
No no, refer to this link for details.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc/
You can stick to server and client rpc if you want tho
Any process can communicate with any other process by sending an RPC. Starting in version 1.8, the Rpc attribute encompasses Server to Client Rpcs, Client to Server Rpcs, and Client to Client Rpcs.
yeah you were right
it was calling a function to update on the client side from the host side
and as host is also a client
it overloaded the function
Nice you found out
how do i install netcode for entities 1.2
since unity package manager only allows 1.0.17
click the little plus top left of package manager and install by name
am just declaring a networklist of type integer and it is shows me this
line 14 is the one in which the integer list is being initialized
public NetworkList<int> integerList = new NetworkList<int>();
You can't initialize an NetworkList inline like that. It has to be in Start() or Awake()
so i need to instantiate it in the class and initialise it in the awake method?
Declare it globally there, yea.
ok let me try that
i am declraring the list in a network prefab
is that fine?
or should i declare it in some other class?
the prefab does have a network object and i am implementing monobehavior
It needs to be a networkbehavior. but otherwise thats fine
yeah it does have ClassName : NetworkBehavior
so thats fien right?
Yea. that's correct
I'm very new to networking...this is a very beginner question.
Let's say I'm using Unity relay to connect two players, and let's say player 1 shoots a laser, will the laser affect player 2? assuming that both player 1 and 2 have the same scripts for shooting lasers and taking damage from them?
No, you have to send a message of some sort, since player 2 has no idea that player 1 pressed the button
in this case most likely a RPC
Very generally, most of the game logic will be handled by the host. The host is the one who starts the match and is usually player 1. So what will happen is that player 1 will shoot player 2 then will tell player 2 that they just got shot. The other way around player 2 will tell player 1 that they pulled the trigger then player 1 will figure out if player 2 hit anything or was out of ammo or actually had died before he pulled the trigger. Then player 1 will tell player 2 what happened.
Is NGO not capable of server authoritative movement yet? I am being told to use ClientNetworkTransform. Do i just need to learn more, or is this a limitation of NGO at this point?
If (IsServer){
Movement code
}
@rapid crater
You only attach the ClientNetworkTransform to an object you want the client to be able to move
Ok cool, i'll keep going then. Seems like they are saying to use client authority due to laggy movement. I would assume that is network settings, not an authority issue. cool deal, thanks
Does your game need to have strict server authoritative movement?
my final game will, yes. a part of avoiding cheating
Ok are you using a dedicated server or host?
the final game will use dedicated server. while learning, just using host usually. but, will attempt to test with dedicated, asap
Yeah you will find what works best. If you need more help you can pm me. I can share stuff from my projects as they have, dgs, host, and client movement
Also you can just have a separate build be the “server” and use (IsServer) instead of (IsHost) to test how a dedicated server would be
Cool deal, thanks. I am using ParrelSync ATM, since the built in solution (2023) does not seem to like my multi-monitor setup :/ I am still at the very basics though, so time will tell. I appreciate the offer 🙂 @remote relic
Lag is going to be something you will need to deal with one way or another
indeed. I think these tutorials are kind of saying 'use client auth' in the same way they say 'use public so it's accessible in editor' :/
There are some very neat changes coming to NGO soon that will help a ton in mitigating latency
Nice! in 6, or 2023? please don't say further down the road than 6. i'll have to use mirror or PUN in that case
Yea a 2 hour tutorial setting up a client prediction system just to move a capsule is not going to help anyone
2 hours and 35 minutes to be exact! 😄 samyams multiplayer tutorial
Distributed Authority is coming in NGO 1.9.0. It just got added to the docs this week. 2.0.0 seems to have some kind of client anticipation system
Oh...
Is there any tutorial of some sort for such a thing?
Let's say that player 1 spawns actual small bullets in game, and player 2 has a code that takes damage to such a game object in their script. Would it still need rpcs or stuff like that?
i can switch the lobby host when using the lobby system.
is there a way of switching the host of networkmanager so that when the host leaves the clients in the match don't get removed once host leaves.
it looks like UNet could do it, so there must be a way in the newer NGO
https://docs.unity3d.com/2021.1/Documentation/Manual/UNetHostMigration.html
That is one way of doing it. But you really don't want to trust the client to apply damage to itself. Only the host can spawn objects so when player 2 shoots it would still need a message sent
Can I perhaps dm you if I encounter any problems?
I don't mind. But it's better post it here so everyone can learn
Or over on the Unity Netcode discord server
Oki
Thanks for this i will see what i can do.
What do you think would be the cause of when the client drops an object using this server rpc, it remains in its hand SOMETIMES, but other times it just works. It looks like a coin flip.
Is weapon returning null when it fails?
On pickup, it does
Sometimes!
It returns null, but also the weapon
What??
Btw, these debugs only run on the server
hi is there any code equivelant of
if (inside lobby)
//multiplayer stuff
else
//singleplayer stuff
This will depend on the networking library that you're using, and on whether or not the library knows something like a "lobby". What library are you using? (Photon? Mirror? NetCode for GameObjects? NetCode for Entities? Something else?)
sorry, netcode for gameobjects, with relay and lobby
so network variables and list update in the next update for the client than they do for the host?
i am trying to make a tic tac toe game
i want it such that the host is able to select X or O to his will
i am able to achive that
but i am trying to implement is such that when its the turn for the host all the buttons are disabled for the client
and when its clients turn all the buttons are disabled for the host
till the next turn is made
the turns are stored in a networklist so if a grid has a value then the buttons corresponding to it is disabled and the text of it is applied to it
i have tried to update the server and client rpc
usually single player is just connecting yourself as a host.
haha, im aware, but im trying to not use lobby if i can for the release (to save money pretty much)
that being in the case of if the player chooses to play the single player mode
obv ill be using lobby when theres multiplayer involved
but kinda seems like a waste to me if there wont be any multiplayer involved
The alternative is duplicating all your code
huh
so no code exists like this
not even like
if (isOwner != null)
else
IsOwner will work only when the NetworkManager is connected. If there are no other clients then the host will own everything
so in that case would it return null if the network manager wasnt connected? sorry if im being dumb
Anyone?
it will always return false in that case
that forum post seems like the only solution to that
Ohh would have to go with it
coolio thank u for the help
Is the Networkmanager.Singleton.LocalClientId always 0 on the host ?
Yes, but I think it can be overriden by the transport you're using
(for unity transport it's 0)
I want save the clientId in LobbyData .. What is a good practice for that ?
I want make a Lobby Ready check .. Server side is working fine with Rpcs when all players are ready .. but i want make it visual so i need the clioentid of each player for my prefab .. and i think its best practice to save on connection the clientid in the lobbydata
and for the host i want use LobbyId = Networkmanager.Singleton.LocalClientId
I would just have a NetworkVariable/List which holds that information
You must already be sending the player names over to the clients?
or if the players have their own NetworkBehaviour, just a NetworkVariable<bool> should do
I use this for visuals ```
/// <summary>
/// Hier werden alle Spieler angezeigt die in der Lobby sind
/// </summary>
/// <param name="Lobby"></param>
///
public void PrintPlayers(Lobby Lobby)
{
foreach (Transform child in m_PlayerItemParent)
{
Destroy(child.gameObject);
}
foreach (Player player in Lobby.Players)
{
PlayerItem playeritem = Instantiate(m_PlayerItemPrefab, m_PlayerItemParent);
playeritem.Initialize(player, LobbyManager.Instance.IsPlayerItemHost(Lobby, player), LobbyManager.Instance.IsLobbyHost());
}
for (int i = 0; i < Lobby.AvailableSlots; i++)
{
Instantiate(m_EmptyPlayerItemPrefab, m_PlayerItemParent);
}
}```
Then I setup my prefab on
/// Hier wird dem LobbyPlayerItem die Werte hinzugefügt
/// </summary>
/// <param name="Player"></param>
public void Initialize(Player Player, bool IsThisPlayerItemHost, bool LobbyHost)
{
m_PlayerName.text = Player.Data["PlayerName"].Value;
m_HostIcon.SetActive(IsThisPlayerItemHost);
m_PlayerId = Player.Id;
if (!IsThisPlayerItemHost)
{
m_KickIcon.SetActive(LobbyHost);
}
ChangeColorPlayerItem();
}```
Is Player.Data from Lobby? I'm not too familiar with it
yes
alr
I have already my function working but I dont know the clientid ^^
so i want set it up when I join / create a lobby
I'd send over some data the usual way with a NetworkVariable
so what is a good practice to save my client id in the lobby data ?
Again, not sure, but I don't think it's the best solution here
feels like you can handle it without the lobby system
Why does this not work ?
/// <summary>
/// Event wenn ein Client verbindet
/// </summary>
/// <param name="ClientId"></param>
private void NetworkManager_OnClientConntected(ulong ClientId)
{
Debug.Write(ClientId);
}
because the host is a client too or ?
First off Debug.Write doesn't exist or is some other Debug, not the unity one
Debug.Log or print should do just fine
I take back what i said. I am Not enjoying this tutorial. i am finding it a bit scatter-brained and out of order. also glossing over certain things. Some good foundational info though
is photon pun outdated? i’ve been following a tutorial on it and don’t want to get too far into it with something not “useful”
anyone could help?
Hey how could I update this Player ?
/// PlayerData für die Lobby zum anzeigen
/// </summary>
/// <returns></returns>
public Player GetPlayer()
{
return new Player
{
Data = new Dictionary<string, PlayerDataObject>
{
{ "PlayerName", new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member, AuthenticationService.Instance.PlayerInfo.Username) },
}
};
}```
You can see on their homepage. Pun got replaced by Fusion ages ago
Hi! Im trying to spawn in a player object across the network for my racing game, but no matter what I try, it seems to have some kind of race condition (ha.) somewhere that sometimes places the player at 0,0,0 rather than the position they're supposed to be. It's like a 50/50 chance, as far as I can tell. I haven't found the issue with debugging at all. I'm using Netcode for GameObjects for the networking.
I have a "race manager" object that manages the players in a race. Here is how the player is spawned from inside it, using Dreamteck splines for a racetrack:
private void HandleClientConnected(ulong clientId)
{
// Get spawn position on spline
SplineComputer trackSpline = track.GetComponent<SplineComputer>();
SplineTrigger finishLine = trackSpline.triggerGroups[0].triggers[0];
SplineSample finishLineSample = trackSpline.Evaluate(finishLine.position);
// Create new ship and place it in the spawning position.
GameObject newShip = Instantiate(playerPrefab);
newShip.transform.position = finishLineSample.position;
newShip.transform.rotation = finishLineSample.rotation;
Debug.Log("Trying to set pos here!");
// Subscribe player to spline position tracking
newShip.GetComponent<SplineProjector>().spline = trackSpline;
// Spawn player object across network.
newShip.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
// Lock it in place, for now.
newShip.GetComponent<Ship>().isControlsLocked.Value = true;
[...]
From this point, the ship's position isn't touched until its own fixedupdate call. Is anyone able to help?
You'll need to make sure that only the host/server is running this code. Clients can not Spawn objects. The ship's isControlsLocked net var needs to have server write permissions
I do that earlier in a different function! Unless im missing something obvious here:
public override void OnNetworkSpawn()
{
if (!IsServer) return;
// Connect to track for lap recording
track.finishLinePassed += OnFinishLinePassed;
// Listen for new players joining
NetworkManager.Singleton.OnClientConnectedCallback += HandleClientConnected;
}
As for the control lock, it should only have server write permissions (in Ship.cs):
public NetworkVariable<bool> isControlsLocked = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
maybe subscribe to it in Start() If you are switching to this scene with the other clients connected then onNetworkSpawn might end up missing some clients randomly
Gave that a try, but sadly it seems to not run at all in either Start or Awake :<
I think OnNetworkSpawn is working consistently, otherwise there wouldn't be a ship at all - the ship gets created in that function. It's just the position that has a 50/50 chance to be wrong
Would this be better in a thread? I should probably give more details-
I'm trying to get every client player's killcount* using Netcode for GameObjects. I tested this using a Host instance (client-server) and a Client instance, and this code seems to print the Client's killcount for both players. i checked that the Host and Client instances indeed have different networkKillCounts. what's the problem?
*Host and Client instances' players'
If this is on the player then it will just print the host's kill count twice. You would need to get the net var from the NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject. Even then that will only set the _textstring of the host. The clients do not have access ConnectedClientsIds
What do you think would be the cause of when the client drops an object using this server rpc, it remains in its hand SOMETIMES, but other times it just works. It looks like a coin flip.
No clue. Despawn() will always destroy the network object unless it's set with false then it will remain in the server only
When I pickup the same object, sometimes the networkObject (weapon) is null.
Why do you think it could happen? And maybe I can fix it by saying: "You can only pick this up, if the weapon wouldn1t be null, if yes, spawn another in the same position which you can pickup" ?
That shouldn't be possible unless you are destroying the network object component itself somehow
What you think I could do?
anyone here works with photon ?

btw i fixed it thats why i didnt write a follow up, its was from my ridged body not synced through the photon
You should've written the full issue at the start.
yeah, i wont do that after reading what you sent it made sense my bad. low skill in communication
That's alright, just fully explain the issue at once next time. Good luck! 🙂
I finally got an error 'Null object reference' for line 135
So clearly the weapon is null, but how can it be?
Also its not null
But null
Ha?
If I want to have people shooting bullets in my video game, would it be a better idea to have every bullet run their logic on the client or have each client be responsible for their own bullets and the bullets send their position and such over the internet
I think for special animations and particles and stuff it might be easier for all bullet logic to be done on each client but I’m worried about the performance.
It totally depends on your game. Are you firing 10 rounds a seconds traveling at realistic speeds? Or are they going to be visible so they can be evaded?
Worry about performance after you have the system you want working first
I don't know what line 135 says so I can't really help you there.
are there any specific youtube tutorials you would recommend? sorry to be a bother.
No idea. I don't use Photon. Just try to find the most recent video and not the highest views. There are a lot of outdated videoes out there
okay sounds good :D also another question, i'm pretty new to unity and I've gotten a grasp on how to use a lot of the features, and I want to make a multiplayer game. would you recommend implementing multiplayer early on and then getting all the features to work with multiplayer as I go, or the opposite, where I develop a lot of features and then get them working in multiplayer.
You need to design for multiplayer from the very beginning or else you'll be throwing everything out and redoing it
some weapons will have different logic than others. some will just be raycasts because it's not worth doing anything fancy for high speed bullets and others will be slower projectiles. I think it's best to have all bullet logic on the client then, that way I can have more granular control on what happens to non-client bullets and client bullets
Hey guys, I'm thinking of making some performance into my game to save bandwidth, I was wondering how to reduce from 32bit to 16bit when using vector3 and float, well it turns out it's there but I believe I need to add a few line of code to make this happen. Does anyone know how to convert it while using INetworkSerializable to synchronize the value to the server also to all clients across the network.
{
public half Axis;
public HalfVector3 Position;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsWriter)
{
var writer = serializer.GetFastBufferWriter();
writer.WriteValueSafe(Axis);
writer.WriteValueSafe(Position);
}
else
{
var reader = serializer.GetFastBufferReader();
reader.ReadValueSafe(out Axis);
reader.ReadValueSafe(out Position);
}
}
}```
MIght use the BytePacker class.
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.8/api/Unity.Netcode.BytePacker.html#Unity_Netcode_BytePacker_WriteValuePacked_Unity_Netcode_FastBufferWriter_UnityEngine_Vector3_
Otherwise I think you are looking at using some Custom Serialization
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/custom-serialization/#for-networkvariable
Netcode uses a default serialization pipeline when using RPCs, NetworkVariables, or any other Netcode-related tasks that require serialization. The serialization pipeline looks like this:
yeah i have look into custom serialization before but just dont really get it till now. Need some example of what people do on their code. 🤭
anyone got any clue why a register script would send two different conflicting outputs at the same time despite only being called once
https://cdn.discordapp.com/attachments/497872424281440267/1228816634001494137/image.png?ex=662d6bab&is=661af6ab&hm=f95cc377c9ab0a1fb01fb27011c687cb870dd62455ee30a522843e445da66417&
https://cdn.discordapp.com/attachments/497872424281440267/1228816634416861284/image.png?ex=662d6bab&is=661af6ab&hm=9b9da3211e9cbbbd6e82b7607f33c35fb874fc0e00b216fd550c49c488ed6d3e&
I attached this script to a button and that's what calls it
https://cdn.discordapp.com/attachments/497872424281440267/1228816704071532616/image.png?ex=662d6bbc&is=661af6bc&hm=2dad108ce551f6a329023fda11535d2fe3498c9905b29481d058a96cc6d7cb75&
I figured it out, I had a click listener in the register script, and I also attached a click listener in the button menu so it sent it twice
im such a dumbass
Hello, I'm following a tutorial for setting up photon fusion, and I'm completely lost.
this is the tutorial: https://doc.photonengine.com/fusion/current/tutorials/host-mode-basics/2-setting-up-a-scene
I've gotten up to the point "Creating a player avatar" but I'm not sure if I'm doing anything right. I have 16 errors in that one script and they are all telling me to add some interface member.
I already have a player controller and a player, but right now it's all going to shit because they are using unity 3d and I am not.
I can't find useful tutorials on youtube with fusion 2, and yet everyone is telling me to use the latest technology.
Could I have some guidance? I'm really passionate about game dev, just really new and am probably not doing it right.
Photon has their own discord server that you might get better help on
okay, ill try to post the same message there
Hello everyone, I'm new here. Right now I'm working on a project multiplayer game with netcode for game object and encounter problem to sync game object to all network client and host? I want to sync powerup Indicator when player picked up a powerup. I used server rpc but it doesn't work. anyone know what should I do?
You need to use a client RPC to tell the other clients about the powerup. Or you can use network variable
Prefab Powerup Indicator
the concept is when either host or client pickup the powerup, the powerup indicator will set active and follow the player
but i still dont understand the synchronization concept
when either host or client pickup the powerup,
Hello! I am trying to build a multiplayer project that I have been working on and after implementing netcode for game objects, I get this error when trying to build the project.
Hello, how would I go about setting the spawn points for players in netcode? Each time a client joins they always spawn on 0,0,0. I've tried moving the networkmanager but that doesnt help. Any help appreciated
You can use Connection Approval for this
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval/#networkmanagerconnectionapprovalresponse
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.
Thanks man, sorry i forgot to remove this.
I just had to:
public override void OnNetworkSpawn()
{
transform.position = new Vector3(-20, 3, Random.Range(positionRange, -positionRange));
}
https://hastebin.com/share/ivezoqaqil.csharp
why cant client shoot?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
If you are using physics.simulate() then it should be fine to use move() as well
You are missing the [RPC] attribute
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/rpc
Any process can communicate with any other process by sending an RPC. Starting in version 1.8, the Rpc attribute encompasses Server to Client Rpcs, Client to Server Rpcs, and Client to Client Rpcs.
yo guys.. quick question: Code Monkey has 2 tutorials for multiplayer 1 6hour long and 1 is 1 hour long are the 6 hours worth it? i have to learn enough to make a simple survival game.
i have a network prefab which has another prefab inside it
do i need to attach the network object component and make its script network behavior to the prefab that is inside the network prefab?
that entirely depends on what that thing is/does/requires
Does this inner object do something that needs networking features?
Hi Devs, I would like to make an online game where the game should call the server every 10 seconds to save player progress, my question is, would it be better to use a dedicated server or use unity cloud save + other unity tools?
Please provide pros and cons
Thanks for your help!
it calls a funtion in the gamecontroller (attached to the network prefab)
like there is fucntion UpdateMade()
it calls that funtions
and inside UpdateMade() i call a function named "UpdateButtonsRpc" which is sent to both client and host
so it indirectly calls a method in another scrict (which is a network behavior) and calls a local funtion which calls a funtion that is called on both host and client
To perform RPCs it will need to either be a NeworkObject or proxy the call through a NetworkObject.
ok ill make the prefab a network object
Sup guys, im trying to experiment with the netcode for gameobjects package, but i cannot install the 2.0.0-exp 2 version, and i cant find it to install, any tips on how to find install this version?
Hello there,
I want to make a server authoritative physic- based game. I'm thinking about using Netcode but I would like to know your opinion on this.
Cheers.
Anyone know how to use Server/clientRpc's?
is Netcode for Gameobjects expandable?
like can u build up on it
because im not sure which solution to pick
It's not released yet. You can grab the branch from GitHub if you want to go through the source code.
Networking physics will be a challenge no matter what framework you end up using
Any process can communicate with any other process by sending an RPC. Starting in version 1.8, the Rpc attribute encompasses Server to Client Rpcs, Client to Server Rpcs, and Client to Client Rpcs.
The source code is on GitHub, currently under the MIT License (soon to change to the Unity Companion License)
how can i use singleton instances when networking?
like here for example
thats what i did before
i know theres a way to do it with networking
You really don't want to use singletons in networking. Especially for players.
You might be able to get away with it for player input since there is only one local player
You would either need to use dependency injection or use events to hook up with your local network player
yeah i use singletons for most of my scripts
since it was a singleplayer game before
why specificially clients movement laggy? movement code: https://hastebin.com/share/fojapuxako.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
https://hastebin.com/share/ojayupikoc.csharp why do i get the error: OverflowException: Attempted to write without first calling TryBeginWrite()
HandleStates+TransformStateRW.NetworkSerialize[T] (Unity.Netcode.BufferSerializer`1[TReaderWriter] serializer) (at Assets/Scripts/HandleStates.cs:40)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Anyone know why I can't move my camera sideways? It just rotates the cube though I'm rotating the player transform which has both the cube and the camera parented. It's also shaking for some reason. Already tried making it rotate the camera transform and had the same problem except it didn't rotate the cube.
Offline Transport (Single Player) Allows games to be played offline without the need of an internet connection.
im reading a networking solution comparison chart
and it says that fishnet pro has this, and mirror and netcode for gameobjects don’t
what does it mean?
like cant u make singleplayer and multiplayer without this?
i haven't used fishnet but i think that's if you want to write your game logic using multiplayer features like RPCs and have it work in singleplayer too, useful if you don't want to have separate code for singleplayer and multiplayer
iirc you can still do it by hosting on 127.0.0.1 on the default transport, it's probably more efficient to have built in support though
are network variables still datatypes only?
value types. structs will have to implement INetworkSerializable
so i cant pass in a class or scriptable object or something
You can not
private void OnEnable()
{
NetworkPlayerInputController.markerStart += AddPlayerJoined;
CharSelectMarker.ReadyConfirm += AddReady;
CharSelectMarker.ReadyRemove += RemoveReady;
}
private void AddPlayerJoined(NetworkVariable<int> ID, NetworkPlayerInputController inputController)
{
AddPlayerRPC();
inputController.ID = playersConnected;
}
[Rpc(SendTo.Server)]
void AddPlayerRPC()
{
playersConnected.Value++;
}
why isnt this working?
this is the on the network player input controller
figured it out, i think the player input controller is being created before the other one is a network component
how can i change this?
because the lobby is spawned before the player it wont run things properly
why isnt this working on the client?
public void MoveMarker(InputAction.CallbackContext ctx)
{
if (!IsOwner) {return;}
if (ctx.performed)
{
markerMove = ctx.ReadValue<Vector2>();
print(ID.Value + " Move marker: " + markerMove);
}
else
{
markerMove = Vector2.zero;
}
}
it works fine on the host, but on the client it breaks
or just doesnt work at all
why cant i delete this?
as soon as i delete it a new one is made
cause i have another one already
its in the project settings to automatically create a default network prefab list
where
is it this?
oh no clue about fishnet, but looks like thats it
are these okay to use in networking?
Hey
I wanted to ask does photon work well with steam? I plan to make a peer to peer fps game and want to know if it is compatible
so i have a rigidbody movement system
im not sure what network components to put onto it
as u can see it looks good when other players move
but not when u move
the camera like jitters
Is the camera parented to the player in some way?
no
its a networking issue because when i remove the NetworkTransform and OfflineRigidbody it doesnt jitter
Where is the camera getting set of it's not part of the prefab?
what do you mean
If the camera is not part of the player prefab then when the player spawns it will not have a reference to the camera.
no the camera its inside of the prefab
Movement - (Movement script with rigidbody, collider etc)
Camera Holder
Camera ```
Player is the prefab
https://hastebin.com/share/ojayupikoc.csharp why do i get the error: OverflowException: Attempted to write without first calling TryBeginWrite()
HandleStates+TransformStateRW.NetworkSerialize[T] (Unity.Netcode.BufferSerializer`1[TReaderWriter] serializer) (at Assets/Scripts/HandleStates.cs:40)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Not sure if this belongs here, but I'm sending some pretty large dictionaries over my network from my client to server.
In the beginner chat several people said I shouldn't send dictionaries, but I don't understand why or what to do instead
Hello everyone,
I want to do some load tests on the megacity metro sample. For this, I intend to create thin clients outside the editor, which is possible with the -enable-thin-clients parameter. But they do just try to connect to matchmaking in the megacity metro example.
Does anyone know how and where to change the behavior of the thin clients in megacity metro? I've made it work that the first thin client correctly connects to my local server, but the others fail to do anything.
Furthermore, is there any documentation on ThinClients? I wasn't able to find any.
Your only practical option is to flag all server code with #if SERVER (define depends on the framework you’re using) and compile it out of the clients that way
a common practice to simplify that is to always have a -server/-client/-shared triple for all network related classes
those can also be partial classes which simplifies the encapsulation
Unity actually implemented ThinClients for ECS with the PlayMode Tools. The only problem is that (as with everything Netcode for Entities related) they are documented very poorly.
Suppose that depends on your definition and context what ‘thin’ means
Unitys ThinClients can be made as thin as you want ...
Ask the folks over on #1062393052863414313 I've only been able to use thin clients through the editor
I've got it to work! Seems like megacity metro already had a system for this, but someone commented it out (for whatever reason...)
Thank you for your halp evilotaku!!
Nice! Where exactly is it? I glanced around the repo a bit but couldn't really find it
https://github.com/Unity-Technologies/megacity-metro/blob/master/Assets/Scripts/Gameplay/Client/Netcode/ThinClientAutoConnectSystem.cs
To use this you would have to create thinclients in the player with the parameter "--enable-thin-clients <amoung>".
If used in headless mode this will trigger the matchmaking flow in the megacity metro sample, but if used without headless mode the thin clients will follow the main clients connection. It would be great if you could just specify a network address and port the thin clients should connect to, but I think I'll have to implement that myself
hey can u help me to despawn objects on server from client
im using netcode and wanna despawn object on server but the client have to call it
its not getting despawned for me right now, im even using ServerRpc
its not getting despawned for me right
I'm trying to host a github page over at https://tetiewastaken.github.io/solardemo-webgl/ but I keep getting CORS errors and I don't really understand it. I've tried setting the headers as https://docs.unity3d.com/560/Documentation/Manual/webgl-networking.html suggested after building again I'm still getting the same errors, why?
Here's my code:
UnityWebRequest webRequest = UnityWebRequest.Get("https://ssd.jpl.nasa.gov/api/horizons.api?format=" + format + "&COMMAND=" + COMMAND + "&OBJ_DATA=" + OBJ_DATA + "&MAKE_EPHEM=" + MAKE_EPHEM + "&EPHEM_TYPE=" + EPHEM_TYPE + "&START_TIME=" + START_TIME + "&STOP_TIME=" + STOP_TIME + "&CENTER=" + CENTER);
// CORS configuration
webRequest.SetRequestHeader("Access-Control-Allow-Credentials", "true");
webRequest.SetRequestHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
webRequest.SetRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
webRequest.SetRequestHeader("Access-Control-Allow-Origin", "*");
using (webRequest)
{
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.Success)
{
yield return webRequest.downloadHandler.text;
}
else
{
Debug.Log("Error: " + webRequest.error);
}
}
how come every time player moves transform is set back to 0 https://hastebin.com/share/ocepikogug.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can someone tell me why this object wont spawn automatically when my scene loads? The object this is on is a simple transform with a script that inherits NetworkBehavior. But my game manager script with the same setup in another scene spawns automatically.
Anyone know if there are plans to get netcode for entities working with WebGL? Or if there are any work arounds to get it going?
You'll probably have to wait for WebGL to get proper multi threading or maybe the new webGPU. #1062393052863414313 would know better
Is there any way to store a colour into a customproperty for photon?
im using steamworks and i want to test some features of my game is the only way to test the multiplayer part by getting another device with a different steam account to join?
use a vector3/4 or byte3/4 or create a custom serializer
how come every time player moves transform is set back to 0 https://hastebin.com/share/ocepikogug.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
https://doc-api.photonengine.com/en/pun/current/class_photon_1_1_pun_1_1_utility_scripts_1_1_countdown_timer.html
is there any more detailed tutorial / doccumentation for pun 2 countdowntimer ?
Do I have to add a Prefab Variant to Networklist too ?
You don't need to use prefab variants for anything network related if you don't want to. You only have to make sure that the network object is spawned and enabled in the scene
how can i make sure other players see the weapons
this is a weapon switching script
im using fishnet
im trying something like this
the ObserversRpc is a ClientRpc right?
just fishnet has a different name for it
alright i've got this now
but there are two problems
when i press a key to change a weapon
theres a delay for the owner
and also lets say i have a weapon equipped
and another player joins
he cant see that im already holding a weapon
you can fix that by doing BufferLast = true in the observersrpc
Hello everyone. I'm making a multiplayer air hockey game on Unity with NGO and Relay. I'm having trouble getting the yellow puck to spawn once and share it's position across the host and client.
Hello, please advise what is the best way to implement multiplayer, if I want to implement a game in which the game state will be stored on the server, are there any tools?
does unity have free servers or will i need my own
sorry for the late reply, this is code in the player that's run server-side. why shouldn't it have access to ConnectedClientsIds?
If its only running on the server then only the _texstring and _placement variables on the server will get monified
If you are using dedicated servers then you will have to provide your own. You can use the Relay Service which doesn't use servers but has a free tier
idk im just tryna make a pvp game
how would i get the networkKillCount.Value of each client?
loop through all the clients and get their playerobject with NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject; Then you can get whatever component has networkKillCount on it
can i loop through them like this?
foreach (var clientId in Networkmanager.Singleton.ConnectedClientsIds)
{
NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject
}
like this
Yea. that should work
hey how do i haave multiple game plays at once because i want to see if certain things are server sided or just client sided
If you are using Unity 2023 then you can also use Multiplayer Play Mode
https://docs-multiplayer.unity3d.com/mppm/current/about/
Overview of Multiplayer Play Mode
I've never used networking with Unity before and have a quick question. When you enable a gameobject for use with some type of networking component, netcode, mirror, etc, do all the properties of the object get syncronized with all players or is it only certain ones?
I ask because what if I had to stream some instructions in to a textmeshpro textbox, would every client also see those changes as they're being updated in the textbox?
Nothing gets synchronized automatically
There are a few helper components that make it somewhat automatic to sync transforms and other basic stuff but generally, whatever you want to sync, you gotta do it manually and explicitly.
Some frameworks try to sync „everything“ automatically, but those don’t scale and fall short very quickly
ahh nice, which ones do it automatically? is that Mirror / Photon ?
None of the ones you mentioned or any of the ones that are fit for recommendation
This is not about Unity.
You only want to sync what's vital to the game to function properly.
Bandwidth is not free, it's a limited resource. You should only sync what you need otherwise you would be paying more than you should. Not to mention performance impact of having to sync everything.
using UnityEngine;
using UnityEngine.Networking;
public class PlayerController : NetworkBehaviour
{
public float speed = 5.0f;
// Update is called once per frame
void Update()
{
// Only allow control if this is the local player's object
if (!isLocalPlayer)
{
return;
}
// Handle player movement
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
transform.position = transform.position + movement * speed * Time.deltaTime;
}
public override void OnStartLocalPlayer()
{
// You can use this function to do things like change the player's color
// to indicate which object they control
GetComponent<MeshRenderer>().material.color = Color.blue;
}
}
was playing around with AI co-pilot tryna see its capabilities, I ask it to make movement for a top-down 2D game, does the code check out?
ok, i'll give Mirror a shot first. I'm not concerned with bandwidth or performance at the moment. I'm just looking for whatever is easiest at the moment.
What is your game? Is it player-hosted or dedicated-server? Or just learning networking.
Learning only. Theres no users other than me. I was just curious about learning whats involved in spining up a dedicated server and connecting to it. I might try to make a little chat app first.
Chat app? No. Most of what is involved in that has nothing unique with gamedev. And it's also just msg passing.
Do a simple FPS where you spawn players around a small environment. Maybe add shooting too.
That will teach you a lot of the basics.
Eventually I might get there, right now I'm only interested in "Chat". If you want to think of it in terns of gamedev, think of it as talking with an npc.
I think I'm all set, i dont have any other questions. Gonna give mirror a shot first.
Good luck!
thx!
Hey everyone! Hope youre having a good day,
Im having an issue with serverRPCs and ClientRPCs, With this code oprovided i shoot on the host and it shows up on the client too, but if i shoot from the client, nothing happens.
Code here - https://gdl.space/ubulemowob.cs
😭
youre trying to spawn the bullet on the client when you should be spawning the bullet on the server
Hey thanks! And even if i want the game to be client authoritive?
am i spawning on the client when i do the serverRPC?
in the function Shoot which is called on the client you're doing currentBullet.GetComponent<NetworkObject>().Spawn(true); and you can only spawn objects on the server, so id say spawn the object on the server and do all the calculations on the server
when i change the Serverpc method to call just Shoot(); Then i dont know how to get the client to be able to do it too i guess maybe thats where im stuck and confused?
ok, you have two options for synchronizing the bullet to clients, either have a networktransform on the bullet or you can have the client fire the bullet locally, basically duplicating the server's actions
from documentation i read serverrpc will be fire from client executed on server, but it doesnt do anything, on the bullet i do have a ClientNetworkTransform, Maybe that NEEDS to be a regular NEtwork Transform instead?
also thanks so much for helping
im not sure, i use fishnet which doesnt haven clientnetworktransform, only networktransform, but you can try the networktransform
but using networktransforms for every bullet might use up a lot of bandwidth so the better method may be to just shoot the bullet locally AND on the server, but that might have desync issues
ah i see, ok thanks so much!
i've never done this method before so i dont really know but i think a possible solution to better sync up projectiles would be to first, fire the bullet on the client, then fire it on the server, then the server sends back information ONCE about the position and velocity of the bullet in order to fix any possible desync
@strange jungle so maybe something like this?
if (isAutoFire)
{
if (Input.GetMouseButton(0) && currentAmmo > 0 && Time.time >= nextTimeToFire)
{
ShootServerRPC();
if (!IsServer)
{
Shoot();
}
}
}
in regards to if youre just a client just shoot locally?
thats a great idea ok cool i will try that out'
So that code i just sent almost everything works now just need to get the bullets to show up from client to other clients. Almost there i think, thanks again ill figure it out!
As client I get this error: NotServerException: ConnectedClientIds should only be accessed on server.
Can someone help me there ?
ngo is right, only the server has this information, so get the client to ask the server to do this via rpc instead
this needs to be a NetworkBehavior. and you need to make sure that SpawnVehicle() is only being called on the server
{
[SerializeField] private Transform[] m_Vehicle;
public override void OnNetworkSpawn()
{
if (IsServer)
{
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += SpawnVehicle;
}
}
/// <summary>
/// Hier wird der Spieler gespawnt
/// </summary>
/// <param name="sceneName"></param>
/// <param name="loadSceneMode"></param>
/// <param name="clientsCompleted"></param>
/// <param name="clientsTimedOut"></param>
private void SpawnVehicle(string sceneName, LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut)
{
foreach (ulong clientId in NetworkManager.Singleton.ConnectedClientsIds)
{
Transform playerTransform = Instantiate(m_Vehicle[ClientSingleton.MyInstance.MySelectedCarIndex]);
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
}
}
}```
I have changed it
and it is working fine thanks a lot
Networking is still hard for me ..
One more question! Im saving the Index of the car to spawn in my CarSelector script! In the next scene I spawn the vehicles! But all players have the same car like the host. what do i false ?
i'm guessing you should add a parameter to VehicleSelectReadyCheckRpc so the client sends which car is selected, rather than using m_CurrentCar, which probably isn't set on the server?
Any solution?
CORS headers are for the server, not the client, you can't set them on your unity requests
I ended up running it through https://corsproxy.io, however I did get forbidden errors when using it in the editor.. On web it works fine
I've also included a hardcored set of headers, from the official docs (the heads with a bunch of ALLOWEDs and underscores) , just to test it out, but the request doesn't even reach my server. My server runs locally
where are you setting the headers?
I read online that using a proxy is overkill and there's no guarantee for it's responsiveness
To every response from the server, for testing out. It's a simple c# server, using HttpContextResponse.AddHeaders
I should also note that the server works fine
hmm what's the error you get in the browser?
For non webgl clients
🤷♂️ on the unity forum I got told there was little I could do except for using a proxy
I see the preflight failure mark in the Network tab of dev tools in Edge. As for the error log itself, it's similar to this one
(I'd remove the embedded image from the link but I'm on mobile)
next thing to check would be that you can see the CORS headers being sent in response to the preflight request as you'd expect
oh wait are you accessing the server via localhost? last time i checked you had to run the browser with security stuff disabled for that to work
Yeah but i see absolutely no request in my local server...
yeah, it's a browser feature
in chrome it should work if you run chrome with the --disable-web-security command line option
Fortunately my server module is open source so i can share it.
https://github.com/somedeveloper00/HttpListener/blob/f1e4aac2bc2ce9faead40476ed49018de9ef6862/HttpServerComponent.cs#L173
The highlighted line is where I add the headers hardcoded. I don't expect you to read everything in there of course
Point is that it uses standard libraries from C#
So if there were any requests, it should've caught them
yes, it's a browser feature so the browser will refuse to send requests if the CORS doesn't check out
which it won't on localhost
So okay lets ignore my implementation for a moment. Conceptually, in my 2nd server, I should expect an OPTIONS request, and I should respond to that with the standard CORS headers, and then expect the actual POST request later. Is that right?
yup
I'm asking to make sure that I've got the concept right
you can see it happening on pretty much any webpage out there these days, check the console and click around a bit and you'll see preflight requests all over the place
it's required for anything dynamic that isn't just loading a resource iirc
@fluid walrus thanks, and sorry for the last few weird messages, they were supposed to come one after the other but my internet was really slow. Just got your response
dose any one know too too make a part of my player model invisble too the owner but not too other players im using Photon
You presumably know how to check if the player is the owner or not, so assuming that, have a check that disables the mesh renderer of the player model for the owner.
im new so i have no clue how too
Well, ignoring the fact a beginner should not attempt networking (since beginners are deaf to that advice), you need to find a tutorial for photon that covers the basics with special attention to learning how to determine the authority of an object.
Once you actually know how, then you can worry about hiding the model.
Yo guys quick question. Is Mirror a LAN or WAN
What would be a point of lan only framework. Mirror also supports several punch-through frameworks as well for p2p connection.
I fixed it in the end, just 10 lines of code. im very surprized a lot of web results suggested to install a whole bunch of modules or use a complex proxy for 10 lines of code...
if anyone in the future wanted to know how, my solution is open source, at this permalink
🤷♂️ the proxy wasn't that complex, you just had to add the link before the website you wanted to access and it would do it for you
it's a dependency
if you don't mind, it's alright. but for some cases, dependencies are not desirable
Hey I trying to make StartPositions (its a racing game) my list is working correctly .. i have the problem when I join with 3 players or more players join on the same spawnposition. maybe u can find the problem here:
{
// Iteriere über alle Spieler, die verbunden sind
for (int i = 0; i < NetworkManager.Singleton.ConnectedClientsIds.Count; i++)
{
ulong clientId = NetworkManager.Singleton.ConnectedClientsIds[i];
// Überprüfe, ob der Spieler in der Dictionary enthalten ist
if (HostSingleton.MyInstance.MyPlayerVehicleDictionary.ContainsKey(clientId))
{
// Hole den CarIndex aus der Dictionary
int carIndex = HostSingleton.MyInstance.MyPlayerVehicleDictionary[clientId];
// Nutze den CarIndex, um das entsprechende Fahrzeug zu spawnen
Transform playerTransform = Instantiate(m_Vehicle[carIndex]);
// Wähle eine Startposition für den Spieler aus
Transform spawnPosition = GetSpawnPositionIndex();
if (spawnPosition != null)
{
// Setze die Position des Fahrzeugs auf die Startposition
playerTransform.position = spawnPosition.position;
// Sorge dafür, dass das Fahrzeug als Spielerobjekt gespawnt wird
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
}
else
{
Debug.LogWarning("Es sind keine Startpositionen mehr verfügbar!");
}
}
else
{
Debug.LogWarning("Client " + clientId + " hat keinen zugewiesenen CarIndex!");
}
}
}```
{
int playerCount = NetworkManager.Singleton.ConnectedClientsIds.Count;
// Kopiere alle Startpositionen in die Liste
m_StartPositionsList.Clear(); // Stelle sicher, dass die Liste leer ist
m_StartPositionsList.AddRange(m_StartPositions);
// Überprüfe, ob die Anzahl der Spieler kleiner ist als die Anzahl der Startpositionen
if (playerCount < m_StartPositionsList.Count)
{
// Berechne die Anzahl der Startpositionen, die entfernt werden sollen
int numToRemove = m_StartPositionsList.Count - playerCount;
// Entferne die letzten 'numToRemove' Startpositionen aus der Liste
m_StartPositionsList.RemoveRange(playerCount, numToRemove);
Debug.Log(m_StartPositionsList.Count);
}
// Mische die Liste unabhängig von der Anzahl der Einträge
m_StartPositionsList.Shuffle();
// Nehme den ersten Eintrag aus der Liste
Transform spawnPosition = m_StartPositionsList[0];
// Entferne den ersten Eintrag aus der Liste
m_StartPositionsList.RemoveAt(0);
// Gebe die ausgewählte Startposition zurück
return spawnPosition;
}```
Not sure if this belongs here but:
Sry for it being an image, just copied it from another place where I asked
In Editor it works fine. When I build it in Fullscreen it doesnt work .. Player get spawned not at the spawnpoint. Maybe someone see the problem here ?
In build only the first one. I have 8 Spawnpoints for my vehicles. I want that every player spawns on a different spawnpoint but only if 4 players are playing then spawnpoint 0-4
if 6 players are playing then 0-5
but on mixed positions
not the first one on 0
Wrong type of networking, my dude
Hello. I'm trying to get messages displayed on the screen of whichever player enters a trigger (client or host). At the moment, regardless of who enters the trigger, the message is only displayed on the server (host) screen
Hello I have very simple question about Vivox voice service.
Is it possible to use Vivox voice chat without integrating unity service. I want to host my own server for voice chat.
Hello, I just wanted to ask...
Im using Photon 2D and the movements and others is synchronized but when it comes to my character (sprite) that have bones its not updating on different devices
what is some good networking solutions for unity right now? i looking for something that both support p2p and server client connection. i was debating to make my own from the bottom as i think it would be a good experience but that isnt what i am focused on right now. any ideas?
Im using mirror but there is alot of different ones
Fishnet is another one ive heard
But mirror is a really nice open source one with very helpful devs and community
yea i looked into mirror but i didnt find alot documentation about p2p
what do you mean?
peer 2 peer
yeah I know but how did you not find anything i wonder
I never did any multiplayer/ networking in my life and I somehow managed to get my game working in multplayer + steam integration and lobbies. I dont know much about other solutions so I am not sure I am a big help
But my experience with mirror was very nice, and for p2p it has a ton of transports that you can use
do you have a link to the p2p docs?
well this is just the one I use
not sure if mirror has their own transports
There is a few in the list on there
This is the ones that come with mirror
alright thanks ill check it out
This one I use does not come with mirror but is the most used solution for steam i think
If you have questions you should ask on the mirror discord, they are very helpful there
alright thanks
{
foreach (ulong clientId in clientsCompleted)
{
if (HostSingleton.MyInstance.MyPlayerVehicleDictionary.ContainsKey(clientId))
{
int carIndex = HostSingleton.MyInstance.MyPlayerVehicleDictionary[clientId];
Transform playerTransform = Instantiate(m_Vehicle[carIndex]);
playerTransform.position = m_StartPositions[0].position;
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
}
}
}```
Whats the problem here ? On fullbuild when I join my player gets spawned not on the spawnpoint. But in editor it works fine ..
I have an array with 8 spawnpoints. I just wanted test it with 0 to find the problem.
``` public override void OnNetworkSpawn()
{
if (IsServer)
{
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += SpawnVehicle;
}
}```
I use it on this event. Maybe someone can help me out here ..
Unity relay
{
if (IsServer)
{
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += SpawnVehicle;
}
}
private void SpawnVehicle(string sceneName, LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut)
{
foreach (ulong clientId in clientsCompleted)
{
if (HostSingleton.MyInstance.MyPlayerVehicleDictionary.ContainsKey(clientId))
{
int carIndex = HostSingleton.MyInstance.MyPlayerVehicleDictionary[clientId];
Debug.Log("Erster Debug: " + m_StartPositions[0].position);
Transform playerTransform = Instantiate(m_Vehicle[carIndex]);
playerTransform.position = m_StartPositions[0].position;
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
Debug.Log("Zweiter Debug: " + m_StartPositions[0].position);
}
}
}```
Both Debug.Log give the correct position. But sometimes the player spawns on 0.0.0! can someone help me there ?
there is literally only one solution with what you want, which is Photon Fusion (PUN too, but that one is outdated)
Mirror and all the alike don't support p2p at all. they are just client-server netcodes fully
hey, you don't look you have any experience with this. P2P is not what you think it is
p2p is not a "transport", it's a whole different paradigm of game networking
I know
I told him there is a variety of transports for p2p
p2p has nothing to do with transports
it's a complete different paradigm of game networking
unsupported by mirror
What???
yes, mirror is client-server only
it does have client auth, but that is a different thing
p2p is when you are physically connected to other players in the game, direct tcp/udp connections, which sometimes can be relayed
mirror does not support that
Cool
Good to know I guess xD
Told you I dont have any experience and never did any networking
Probably a silly question but when using a ServerRpc, specifically the netcode for gameobjects implimentation. If a client decompiled, modified the instructions inside of a serverrpc and then recompiled. Would that client then be able to run custom code on the server or does it run the implementation that the server has?
yes, VERY SILLY question
like did you somehow think that the client is going to send the rpc instructions with every sent rpc and the server is going to naively execute them? 
😂
it would be the easiest job in the world to do remote code execution and do huge damage so easily
Yeah lol. Just getting exposed to netcode. I just wanted to make sure I wasn't creating a massive security problem xD
There is no such thing as a silly question. But to add on, the only data sent in RPCs are the arguments of the function. Rule #0 of networking is to never trust the client. You should always sanity check any data received because you never know what bad actors might be trying
Would something like this work to prevent cheating in my game?
It's an idle game build in Unity, the server is a C# Cloud Code Module (UGS) and the database is MySQL on Google Cloud
CCM server is not persistent, so it loses all data and stops execution immediately upon a return statement
-
Player logs in
-
Client requests a random seed from server
-
Server generates a random seed, saves it to the database, sends it back to the client
-
Player clicks “Adventure”
-
Client immediately starts adventure using the random seed received in step 3
-
After each important event, the client sends a notification to the server
-
The server re-calculates all combat and rewards up to then, with the random seed to check if everything is still ok
-
Server saves everything to database and generates a new random seed, saves it to the database and sends it back to the client
-
After the next important event, the client starts using the new seed
-
Repeat from 6
An important event could be like every time an item is dropped or a boss is killed, and automatically after every 10 seconds or so?
It's pretty hard to explain the whole concept here, feel free to ask questions!
Does someone have experience with steamworks stats?
private void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
Debug.Log("Enemies Killed: " + StatHandler.GetStat("enemies_killed"));
Debug.Log("Enemies Killed HS: " + StatHandler.GetStat("enemies_killed_hs"));
}
if (Input.GetKeyDown(KeyCode.K))
{
SteamUserStats.SetStat("enemies_killed", 10);
SteamUserStats.SetStat("enemies_killed_hs", 10);
SteamUserStats.StoreStats();
}
if (Input.GetKeyDown(KeyCode.M))
{
Debug.Log("Attempting Callback");
SteamUserStats.RequestCurrentStats();
}
}
I have this code to test it but whatever I do it always show the stats with 0. The callbacks all return successfully. Any Idea what the problem could be?
Does someone have experience with
Hello everybody! I would like to make a rogue style game that allows for networked multiplayer for up to 4 people per game to play together. I know that recently Unity reworked it's networking system and I don't know much at all about network programming. What Unity networking solution would I need to look into working with? Also, can players be in separate scenes in multiplayer as well (like one died and is back in town, while the other is still alive fighting through a dungeon)?
Netcode for Gameobjects should work fine for most of that. the custom scene management is a bit more complicated
Well I definitely don't want to overcomplicate it. Maybe what I could do then is if a player dies they hang out in a view watching the other players until those players reach a kind of "checkpoint" which revives all dead players.
Hello, I'm creating a system to connect a database to Unity (from a server). I'm using PHP on the website to do it, and I already have HTTPS. But I have one important question: is this secure? I mean, can someone just connect to this site and grab information? If yes, then are there any ways to make it secure?
Its as secure as your php code. the website and DB especially should not be publicly available. It would be worth it to pay a hosting provider to deal with that aspect
Thanks, but what if it's planned to have the game downloaded, and i need to connect into it?
The database should really only be connected to by the game server.
Hey guys! I'm making a network multiplayer air hockey game on Unity with NGO and Relay. The collisions on the host work seamlessly but on the client, it struggles. Is there a way to easily fix this issue and get seamless collisions on the client as well?
I'm trying to develop an ideal stock market game. Which server should I use to connect the clients? No lobby/room system is required?
Just saw a group of seagulls flying outside at 2 am now😱
The moon is so bright that seagulls thought it’s daytime
client side prediction maybe
Networking physics is some of the hardest things you can do.
A client anticipation system was just released in 1.9.1 but it's almost entirely undocumented currently
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/releases/tag/ngo/1.9.1
The API docs have a bit more information but not by much
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.9/api/Unity.Netcode.Components.AnticipatedNetworkTransform.html
There is also an experimental sample that seems to use an older version
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/main/Experimental/Anticipation Sample
Thanks for the help 😁
I'll try it out if I can
But I'm on a tight deadline. What if I create a doll of the client on the server/host and have that follow the client around. So the doll would have the same physics set up and act like the client but exist on the server/host?
Yea. That's basically the concept of the ghost object. You just have to make sure that you are resimulating physics for the local client. Unity physics is non-deterministic so it's possible that the client and server might still get out of sync occasionally
😩
how can i delete the lobby?
because at the moment when i leave the lobby
and i was the host
i can still join it with the old id
and at that point the lobby shouldnt exist
steam lobbies should get automatically 'destroyed' when everyone leaves
they dont
apperantly
after everyone leaves
including my self
i can still join with the old code
I just checked and I do the exact same that you do
It works for me
you sure the CurrentLobbyID you use to leave is correct?
yeah
could u try and record a video
to show me that its working
the same problem
i just wanna make sure im not tripping
its alright if u dont want to
how would I even show that its not open anymore
I have my own custom lobby List, I can show you how old lobbies I created dont show up there after I leave I guess?
but not sure how that would help you
alright dont worry
wait i got a video
i can show u
i think
because im not in my house rn
this is what i mean
i host a lobby
copy the id
exit the lobby (which should destroy it)
and then i try to join with the id
how do you join/ create the lobby
You sure its the same lobby and not a newly created one?
im making a tag game and have 2 players in a scene i want to set up a round system where if the players collide or a timer runs out the round resets and the players swap roles and a point is added to the right player im using mirror and was wondering how to go about making this
Hey maybe someone here can help me.
public override void OnNetworkSpawn()
{
if (IsServer)
{
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += OnSceneLoaded;
}
}
private void OnSceneLoaded(string sceneName, LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut)
{
SpawnVehicle(clientsCompleted);
}
private void SpawnVehicle(List<ulong> ClientsCompleted)
{
foreach (ulong clientId in ClientsCompleted)
{
if (HostSingleton.MyInstance.MyPlayerVehicleDictionary.ContainsKey(clientId))
{
int carIndex = HostSingleton.MyInstance.MyPlayerVehicleDictionary[clientId];
Transform playerTransform = Instantiate(m_Vehicle[carIndex]);
playerTransform.position = m_StartPositions[m_StartPosition.Value].position;
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId, true);
m_StartPosition.Value++;
}
}
}```
Here I spawn my player. Each variable is working fine. But sometimes the player got spawned on 0.0.0 on the map.
try setting the position after calling SpawnAsPlayerObject?
Unity.Netcode.NetworkSceneManager.SceneHashFromNameOrPath (System.String sceneNameOrPath)```
I get this error when I make unity editor host and visionOS or simulator client. If I run simulator or vision as host and connect with either one it works fine without errors.
I'm not loading any other scene dynamically or anything, the game is a single scene thing. The network manager has 'enable scene management' on beause it would complain about the networkObject inscene otherwise.
Anyone has an idea?
I have tried it. Doesnt work either. But I found the problem its something in my vehicle scripts. now i have to figure out witch is the problem.
what happens if im using 2022
Then you would need to use ParellSync
yup i have it working now! thanks
only issue everytime i add something new do i make a new clone
or can i like update the old clone?
I was pretty sure the clone would update automatically. Do you happen to have Domain reload turned off?
How do I check 😭
so i turn it on?
Yea give that a try
thanks! ill try rn
no didnt work i even tried creating a new clone and its same as old one
Hi everyone, I'm building a 2 player turn-based tower defense game in Unity and I'm looking for the right networking solution. I've started using Socket.IO, is it the best solution for my situation?
Here's a breakdown of what I have:
Game Description:
Players take turns placing towers and enemies on a defined map with pre-set paths.
After a set of turns, the simulation begins (enemies start to move in their corresponding paths)
Then the roles switches and defender becomes the attacker and other way around.
The game is decided by whoever tanked the most enemies.
Need to sync the game state after each turn, including:
Tower positions and types
Enemy signed paths
Current player turn
Also:
Enemy positions and health
Tanked Enemies,
Tower targeting system (in simulation part)
I know it is quite complex to integrate a multiplayer, that's why i'm asking for any recommendations or tips.
Thanks a lot!
hey im havong trouble with unity's netcode. i made it work last week, and suddenly it doesn't work anymore. the players can join a lobby, and the relay, but then the transform for other players is not updating. i tried rewatching the tutorial i followed (CodeMonkey), but somehow it's not working anymore. i checked everything multiple times, rewrote the script, started from the beginning again but nothing seems to be working. any ideas?
the player prefab has the network object component, and the network transform component
i can see that the relay and lobby services are being used in the unity dashboard, but for the sake of the video and debugging i went back to the basic local multiplayer hosting
{
[SerializeField] private Button joinButton;
[SerializeField] private Button hostButton;
private void Awake()
{
hostButton.onClick.AddListener(() =>
{
NetworkManager.Singleton.StartHost();
});
joinButton.onClick.AddListener(() =>
{
NetworkManager.Singleton.StartClient();
});
}
}```
I have this script, with assigned join and host buttons. these all work fine. i can see in the hierarchy that the players are joining the same game
But then the players are not updating their location on the other devices
If you were making a stock market game in Unity which networking framework would you use
The players are moving locally but not across the network? Should you be using a client network transform instead? We'll need to see you player movement script
{
private void Update()
{
if (!IsOwner)
{
return;
}
Vector3 moveDir = new Vector3(0,0,0);
if (Input.GetKey(KeyCode.W))
{
moveDir.z += 1f;
}
if (Input.GetKey(KeyCode.S))
{
moveDir.z -= 1f;
}
if (Input.GetKey(KeyCode.A))
{
moveDir.x -= 1f;
}
if (Input.GetKey(KeyCode.D))
{
moveDir.x += 1f;
}
float moveSpeed = 3f;
transform.position += moveDir.normalized * moveSpeed * Time.deltaTime;
}
}```
the same code *CodeMonkey* used in his video
Depends on how real time you need it. Any of them should work fine for basic stock simulation
How can we make Kick / Ban system?
I am using Unity Netcode, relay and lobby together
Ok, that is going to need a client network transform to work. Currently it would work on the host but no where else
The kick feature can be made by calling RPC on target client for disconnection but how to implement Ban system?
but it does, no?
That's a Network Transform but not a Client Network Transform
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform/#owner-authoritative-mode
Introduction
It would be okay if the client updated in 1 minute
Bans are a bit more complicated. There is a Moderation Service but I think it's still in alpha. I think right now the only way to ban a player is manually through the Dashboard or maybe with Cloud Code API
Ahh I see
I added the client network transform, and it works now! thanks. But what I'm confused about is that i the exact steps from the video (which uses network transform), not even a week ago, and everything worked. and suddenly it broke down without me changing anything
You could also use cloud code if you go for a serverless architecture
Hi all, was just exploring Fish-Net's documentation, do they no longer have examples?
Not sure if blind
Network Transform is server authoritative only so that move script will not work with it. I'm pretty sure code monkey used client network transform there too. Or he was just demoing on the host
Their own link on Github pages just gives Page Not Found
https://fish-networking.gitbook.io/docs/manual/tutorials/example-projects
i want to host a dedicatet Server
They have their own discord server that could probably better answer that
I just joined as you sent, great idea. Great minds think alike! 😄
stay away from that, the creator is banned here
Hello. I have a problem with starting a host/client after they've been shutdown. I keep getting "Host/Client is shutting down due to network transport start failure of UnityTransport" errors.
I'm making a 2 player game and after every match I want both players to disconnect and go back to the main menu. When I try to Host/Join a new game I get that error.
🤯
Fishnet is banned? What's the story
Yea I'm actually curious as well, what happened?
here you go
The creator was banned from this server for specific comments. They were also known to have alt accounts praising the library, including even interacting with their main, to promote it. Time to move on. If you have a specific question, ask it.
Oh wow. Sounds like the ban was justified.
[ServerRpc(RequireOwnership = false)]
public void SpawnPlayerServerRPC(ulong clientId)
{
var player = Instantiate(playerPrefab, spawnPoints[0].transform.position, Quaternion.identity);
player.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
SpawnPlayerClientRPC(clientId);
Debug.Log("client id =" + OwnerClientId);
}
[ClientRpc(RequireOwnership = false)]
public void SpawnPlayerClientRPC(ulong clientId)
{
}```
Ive tried just about every way, finding documentation has proven to be difficult. Anyone avail to help me figure out how to spawn player for the client?
not really networking, but there's an official unity mobile notifications package
i've never used it though
#📱┃mobile might be a better place to ask
Oh thanks!
Spawning a child object is not supported
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
Error: PlayerMovement on First Person Player requires a NetworkIdentity. Please add a NetworkIdentity component on First Person Player or its parents.
does anyone know the fix for that?
nvm I fixed it, I figured out I had 2 instances of my player
thanks but its not a child object.
Ah you're right, I totally misread that. No reason that shouldn't work
unless its not in a NetworkBehavior
its ok no worries, i re did my code, its working but i have no idea why, one sec
[ServerRpc(RequireOwnership = false)]
public void SpawnPlayerServerRPC(ServerRpcParams rpcParams = default)
{
ulong senderClientId = rpcParams.Receive.SenderClientId;
SpawnPlayersOnClients(senderClientId);
SpawnForClientRPC(senderClientId);
}
[ClientRpc(RequireOwnership = false)]
public void SpawnForClientRPC(ulong clientId)
{
Debug.Log("I Sent this to the server Client # " + clientId);
}
void SpawnPlayersOnClients(ulong clientId)
{
GameObject player = Instantiate(playerPrefab, spawnPoints[0].transform.position, Quaternion.identity);
var playerNetworkObject = player.GetComponent<NetworkObject>();
playerNetworkObject.SpawnAsPlayerObject(clientId);
}```
playerSpawnManager.SpawnPlayerServerRPC();
and then i call it here @sharp axle
but theres nothing inside of the client rpc @sharp axle so i dont understand why its working, because without the clientrpc it does nothing
ok so nvm its working without clientrpc.
the whole issuse was i called the spawn when a timer was over
I was about say...
and the timer was sending rpc to update client for timer
i wasnt using a network variable. love wasting 8 hours when im just dumb. i was like i swear this should work
thanks for the help!
Hello, I want to make a multiplayer game with photon , but I have the problem that I have 2 "Resources" folders (one for TMP and the other for Photon) can someone help me to fix it?
That shouldn't be a problem
As long as the items have unique names that won't be an issue. But I know very little about Photon
is it valid in your opinion?
I just saw that someone in the internet had that issue (didnt expained how he solved it),which is why I assume that it is the same case here.
the names of the two prefabs in the picture
can you debug or log those out to make sure they match? it's possible for names saved in assets not to match their filenames
they match
is it logging an error?
if it started working after recompiling, could be some static state inside the library that needed clearing
ok, thanks anyways
I am looking for a Netcode tutorial that covers Data Persistence. Do any of the official project samples cover that? Or, can someone just point me to a tutorial that does
That's not really a Netcode thing. But you can look up tutorials on Unity Cloud Save or really any cloud storage like Amazon S3 buckets
Very true. Looking at UGS now, thanks
Hello there i know this isnt the best place to ask this but a friend of mine uses the playmaker visual scripting tool and would like have access to either Network for game objects or Fishnetwork.The problem is i am unsure of how to make a networkbehaviour talk to playmaker.If any of u guys used pm before and moved to c# any advice would be helpful
Playmaker has their own discord that could probably give a better answer
I tried but havent gotten an answer i can really work with but thx
hello everyone i am actually omw to create a medieval variant of advance wars and i need help creating the multiplayer version(its a uni project )
Hi guys, when I put this if (view.IsMine) on the update function, for some reason my character does not recognize that it is stepping on the ground
how do i spawn a camera for a client and not replicate it across clients?
You do not spawn the camera. You can just instantiate one locally if its not in the scene or on the player prefab
ok, i did that. for some reason it still appears in the hierarchy (i instantiate it in OnNetworkSpawn())
You need to make sure that only the local player is instantiating a camera
Will it cause server lag if I do a session ID check in void update()? If yes, what are the other ways to do it?
That depends on what the session Id is and how you are checking it
Has anyone here worked on a multiplayer project that used both networked monobehaviours and networked entities together? If so, are there any resources you'd recommend, or best practices to keep in mind?
How can I use Mirror networking with my inventory system? I have methods that are typically used in an inventory system like AddItem, PickupItem, RemoveItem, and a method to instantiate the item as a child of an inventory slot. Any help would be appreciated.
You wont be able to use both Netcode for GameObjects and Netcode for Entities at the same time.
You can mix regular Entities or GameObjects with either Netcode just not both Netcodes at once
oh interesting, could you elaborate on why this is the case? Or do you have any references I could read through to understand the differences?
They both use Unity Transport so you would need like 2 network cards to use them both. The official docs are pretty good. I don't think I can post links here but they should be in the pinned message here
Thanks for the info!
Hello. I'm making a 2 player game. The host creates a lobby and the client joins. After the game ends they both go back to the main menu, leave the original lobby and the host/client is stopped from the Network Manager ( using NetworkManager.Singleton.Shutdown() ). The problem I have is that the original host can't host again, I get this error: "Host is shutting down due to network transport start failure of UnityTransport!".
Which Transport are you using? I've heard the Steam transport running into this issue of not shutting down correctly
Unity Transport
I tried to change a couple of values, but I set them back to the default ones
Does the main menu have a network manager already in it? You might be getting duplicates
The Network Manager is only present in one initial scene that I never go back to
Huh, dunno what the issue is then. Have you tried checking Allow Remote Connection? It shouldn't matter connecting to localhost though
I haven't, I will give it a try
Doesn't work. Is there a reset for the NetworkManager or something?
Shutdown() is the reset
well, it shuts down the Network Manager but I can't start the Host again. I tried destroying it and instantiating a new one but it doesn't work
Hi guys, when I put this if (view.IsMine) on the update function, for some reason my character does not recognize that it is stepping on the ground
Sounds like you are not the owner of that character for whatever reason
Why does a NetworkList result into a memory leak?
elaborate
hey, does anyone have experience with networking in photon fusion 2?
im trying to make a game manager singleton that syncs with every player (to control a lobby screen)
but im not sure where to start
i have functional player syncing (so i can walk around on one client and it syncs to to the other)
i have a question, my game has multiple teams, and every team has a network variable for their money, if i create 4 network variables but only 2 teams are playing, does that affect network performance, and is there a better/dynamic way of doing it? (currently in code i check if (team == 1) {teamValues.Instance.team1Money.Value -= money} else ... and so on and i think that is not that efficient)
That should be fine. Network Variables only get sent when they change values.
I am trying to network my inventory system and I have a small issue, right after I made the InitialiseItem method into a ClientRpc call, Unity gives me an error with the item icon, it said "texture data is either not readable, corrupted or does not exist", here's the code which contains the method, ive also included the item class https://pastie.io/jrzlvc.cs
this is Mirror btw
You can't just send a ScriptableObject over the network like that. Usually I will have a List or Dictionary of SOs that I can reference by id. Then you only need to send IDs around
So make a list of type Item?
If so, how can I implement that because I don't really get how I can use IDs instead of the scriptable object itself?
Either use the list index as the id or add an id field in the SO. You can use Linq to search the list
alright there is already an id attribute in the SO so I guess I will try that first.
thank you
what should i make my tickrate for a non compettive p2p arena game? 4v4 physics based
Tick rate should be the same as your physics step. The default should be fine.
I'm making a game that has both singleplayer and multiplayer, but want to be able to reparent network objects while in the single player mode, is there a way to essentially start a host for single player without actually needing an Internet connection or anything?
You don't need the Internet to connect to localhost
Oh duh, for some reason using that never crossed my mind, thanks
I REALLY NEDD HELP
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class SpawnPlayers : MonoBehaviour
{
public Vector3[] spawnPoints;
void Start()
{
Debug.Log("Start function called.");
if (PlayerPrefs.HasKey("LastTransferredPlayerChild"))
{
Debug.Log("PlayerPrefs key 'LastTransferredPlayerChild' found.");
string lastTransferredPlayerChild = PlayerPrefs.GetString("LastTransferredPlayerChild");
Debug.Log("LastTransferredPlayerChild: " + lastTransferredPlayerChild);
string path = "Players/" + lastTransferredPlayerChild;
Debug.Log("Prefab path: " + path);
GameObject loadedPrefab = Resources.Load<GameObject>(path);
if (loadedPrefab != null)
{
Vector3 randomPlayerSpawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
GameObject childObject = Instantiate(loadedPrefab, randomPlayerSpawnPoint, Quaternion.identity);
PhotonNetwork.Instantiate(childObject.name, randomPlayerSpawnPoint, Quaternion.identity, 0);
}
else
{
Debug.LogWarning("Prefab not found at path: " + path);
}
}
}
}```
The game does not perceive the PhotonNetwork.Instantiate and records an error of "view = 0"
Start() is probably getting run too soon before the network is connected
Yesterday I asked about networking my inventory system. Since I cannot pass scriptable objects across the network, I have made a dictionary of items which allows me to retrieve the items by ID. It works but I am only having a problem with the item's sprite, a white box appears inside my inventory slot instead of the icon of the item itself. https://pastie.io/vljpuv.cs
I've included 3 relevant scripts in the pastie
I guess you'll also need to show the code for the item slot. Or is the image sprite not getting set to the item icon?
Okay so now when ive setup some debug logs it gives me a debug log says "Item ID not found". I have my Items folder placed inside a folder called Resources. And also yeah the image sprite is not getting set to the item icon but that's obviously because the item itself is not being found.
Sorry nevermind, I made a check so that it logs the names of the added items and it actually logs them in the console by doing this
foreach (Item item in items)
{
itemDictionary.Add(item.id, item);
Debug.Log(item.name);
}
Either the id is not getting set in the item SOs, or the InitialiseItem() is getting passed the wrong id
so I am not sure what the problem is with the icons
I will try to find out where the problem is coming from then. Thanks.
public class EnemyHealthComponent : NetworkBehaviour
{
public int maxHP = 10;
public NetworkVariable<int> HP = new();
public override void OnNetworkSpawn()
{
HP.OnValueChanged += onHpChanged; //updates the value on a hp bar slider
healthBar.maxValue = maxHP;
healthBar.value = HP.Value; //cursed line!!!
if(!IsServer) return;
HP.Value = maxHP;
//SetHPServerRpc(maxHP);
//print("HP set to "+HP.Value+"!");
base.OnNetworkSpawn();
}
this is my code for simply updating the hp of an enemy when damaged. This works great everywhere, EXCEPT for the initial HP=MaxHP value for all clients. All enemies are server-owned. Since I set the callback on all clients first, and then replicate the initial value only on the Server, all should nicely initialize, no? NO
for some reason chatGPT recommended adding this line:
healthBar.value = HP.Value; //cursed line!!!
this worked, but is exactly the same thing that should be called by OnHpChanged:
private void onHpChanged(int prev, int curr){
print("HP changed from "+prev+" to "+curr);
healthBar.value = curr;
}
I am still wrapping my head around as to why. From the Clients' POV the HP value could still be not initialized, so trying to set it to the slider seems counter-intuitive, yet works... How can a networked variable be initialized and synchronized with a value faster than the server-called function initializing it??? And most importantly, why does the onHpChanged callback work always, but the first time?
Only idea I get is some race condition, where the server goes through it's onNetworkSpawn first, sets the value, then the client subscribes to the callback, but has no clue about anything being changed. Does that sound possible, and if so, how would you ensure this does not happen. The entire reason for NetworkVariables was to easily synchronize across all clients, including late-joiners, but there's still many work-arounds you need to for this to be true
OnValueChanged is not called when the object is first spawned. So you would need to call onHpChanged manually or set healthBar.value directly in OnNetworkSpawn
so the event literally called "onValueChanged" is not called, but according to the docs the value is changed...?
" A NetworkVariable.Value is synchronized with:
Newly joining clients (that is, "Late Joining Clients")
When the associated NetworkObject of a NetworkBehaviour, with NetworkVariable properties, is spawned, any NetworkVariable's current state (Value) is automatically synchronized on the client side."
Yea. the naming can be kinda misleading. On Spawn the variable value is already up to date so is not technically changing
I can imagine this question appearing very often due to the naming convention, perhaps a short mention about it in the docs would save a lot of frustration and time. Good to know I'm not crazy, thank you!
<@&502884371011731486> i believe to be in the wrong channel
I'm making an idle game with semi-multiplayer.
My game uses Unity and UGS C# Cloud Code Modules with UGS Cloud Save.
Players click "start" which then starts idle/automated combat on the client. Players get experience and items from combat.
I want this to happen real-time on the client, it takes too long to pre-generate all the combat and loot on the server.
But I want my server to check everything so there's no cheating.
I want to prevent cheating because trading items between players will be a big part of the game.
My plan at the moment is the following:
- player starts the game and sends a request to the server for a Random Number Seed (RNS)
- server generates the RNS and stores it in Cloud Save then sends it back to the player
- player clicks "start" and combat is processed real-time using the RNS, items are also generated using this
- on significant events, for example level up, every 10 seconds or on an item drop, the client pings the server to let it know something important happened
- the server then re-calculates all the combat up to that point and if everything checks out it saves all the rewards to Cloud Save
- the sever then generates a new RNS that will be used after the next event (to prevent players calculating rewards a long time up front)
- on the next event the client pings the server again and then starts using the new RNS
The issue I have is my combat logic must run on both client & server, so I have duplicate code that I need to keep in sync. How can I manage this?
Code https://gdl.space/ifuyugapin.cs
I'm using mirror and for some reason the [Command] CmdShoot method works only on the host + client and not on the client, why is that? Everything works in the video tutorial
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class SpawnPlayers : MonoBehaviourPunCallbacks
{
public Vector3[] spawnPoints;
void Start()
{
Debug.Log("Start function called.");
ConnectToPhoton();
}
void ConnectToPhoton()
{
Debug.Log("Connecting to Photon...");
PhotonNetwork.ConnectUsingSettings();
SpawnPlayer();
}
void SpawnPlayer()
{
if (PlayerPrefs.HasKey("LastTransferredPlayerChild"))
{
Debug.Log("PlayerPrefs key 'LastTransferredPlayerChild' found.");
string lastTransferredPlayerChild = PlayerPrefs.GetString("LastTransferredPlayerChild");
Debug.Log("LastTransferredPlayerChild: " + lastTransferredPlayerChild);
string path = "Players/" + lastTransferredPlayerChild;
Debug.Log("Prefab path: " + path);
GameObject loadedPrefab = Resources.Load<GameObject>(path);
if (loadedPrefab != null)
{
Vector3 randomPlayerSpawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
GameObject childObject = Instantiate(loadedPrefab, randomPlayerSpawnPoint, Quaternion.identity);
PhotonNetwork.Instantiate(childObject.name, randomPlayerSpawnPoint, Quaternion.identity, 0);
}
else
{
Debug.LogWarning("Prefab not found at path: " + path);
}
}
}
}```
Like this?
It still does not work
Does anyone know how to add different game modes to my game?
I mean when you are in the main menu you can select a game mode and you get send to that server? With Steam API.
Remove the player prefsb from the network manager and spawn the players manually after the next scene loads. You might have to listen for scene events if you want to wait for all clients to load that scene
You have to disable the camera on the remote players. Unity will only show one active camera int the scene. You can get around that if you are using cinemachine
Hi, I have issue with multiplayer play mode, im getting a timeout error when teying to star virtual player window
Its says that thr player 2 is active but I dont see the game view
Does the same thing happen for player 3 and 4?
hi guys, coming back after a long break and almost forgot anything.
my problem is, my players dont see the gun from each other. they see their own gun. its an fps in 3d. what are some possible problems?
If the gun is not a network object getting Spawned then you'll need to use an rpc to instantiate is on the other clients
Anyone had a chance to look at #1236177820280164413 yet?
{
Debug.Log("Received room list update. Count: " + roomList.Count);
for (int i = 0; i < AllRooms.Length; i++)
{
if (AllRooms[i] != null)
{
Destroy(AllRooms[i]);
Debug.Log("Destroyed room object: " + AllRooms[i].name);
}
}
AllRooms = new GameObject[roomList.Count];
for (int i = 0; i < roomList.Count; i++)
{
if(roomList[i].IsOpen && roomList[i].IsVisible && roomList[i].PlayerCount >= 1)
{
GameObject Room = Instantiate(RoomPrefab, Vector3.zero, Quaternion.identity, _content.transform);
Room.GetComponent<Room>().Name.text = roomList[i].Name;
AllRooms[i] = Room;
Debug.Log("Adding room: " + roomList[i].Name);
}
}
}```
WHY ITS NEVER CALLED??
I have 4 prefabs for my inventory slots, just 1 prefab called Slot and duplicated 3 times in the canvas. Im trying to assign them in the itemSlots array but it seems like they are never found and never assigned to the itemSlots array. The debug log gives me "Found item slots 0". Also yes, each slot has the InventorySlot script attached to it.
public InventorySlot[] itemSlots;
public override void OnStartLocalPlayer()
{
itemSlots = FindObjectsOfType<InventorySlot>();
Debug.Log("Found item slots" + itemSlots.Length);
}
I want to shoot as a client but if I create a clientprc it just doesn't work for the client, it doesn't shoot nothing.
However this is all server side spawning, which makes the bullet "desynced"
Whats the solution?
With KCP and transport, how do I debug exactly what message is '1459' ?
Im getting it unregistered in very specific circumstances, but I can't seem to track down what it is or where/when/how to debug it
Do I need to put a separate canvas for each player instance?
Normally the UI canvas is not networked at all. Unless its a world space canvas
well the problem is, my Inventory slots are always apparent on screen and there are 4 of them, I need to add their prefabs in a list in the Inventory script that is attached to the player but I cant because the player isnt in the scene
obviously the player only gets instantiated when someone joins the lobby
the 4 slot prefabs have the scene canvas as their parent
You can have a separate UI Manager script that listens for players joining the lobby. Or have the players register themselves to the UI manager when they connect. The UI manager can then instantiate or bind your inventory data to the UI
Alright thanks
Im noob. I saw that for multiplayer, you have to use code so that a game instance has both the host and the client code and dependinf on what it is, it runs the code accordingly. But if the game can be played single player, how is the code now? Is it a fake host with local ip, or a total dofferent program for singleplayer? Hope it makes sense what im asking.
H-hello. May I ask, haven't found a backend channel here, so.. here? if it's okay
I have some exp with Unity, 0 exp with any backend though.
I'm trying to add multiplayer, matchmaking, login and simple data save/load to my webgl game.
Multiplayer part looks like something I at least know how to start making(with the help of Fishnet), but backend sadly nowhere near.
My utmost priority is self-hosted open source(~zero cost, no premium/pro/enterprise tiers to be accurate) solutions or even making these parts myself. Best I could find is xsolla backend(no tiers, % of income though), but maybe I somehow missed something obvious?
If no such solution exists, where should I start with these things(matchmaking, login, save/load data)?
The easiest way to do single-player without duplicating a bunch of code is to host to the localhost.
I'm not sure there is a true zero-cost solution to server hosting. Even if you host the dedicated server on a old pc in your closet, you still have to pay for bandwidth.
The Epic Online Services and Steamworks are free to use as well.
No-no! Not to server hosting, sorry, this is alright. To backend I meant
Dedicated server model. But I don't have an ability to pay for backend. Either open source or my code
There are no turn key solutions for self hosted backend infrastructure like that. You'll need to build and host the database, matchmaking, lobby, and authentication servers yourself. Not to mention maintaining the security of player data.
Sounds sad, where should I start then?
Honestly, I would start with using one of the Backend as a Service. Once you know exactly what you need, you can start to strip it out and build your own if needed.
I see, thank you! By the way, do you know anything about xsolla backend?
very little. We talked to their booth at GDC. They are legit though. Personally I'm sticking with the UGS backend
Okay! Thanks a lot!!
Hey so I am using photon and I need help! I want so that if someone clicks a button it plays the music to everyone (like a soundboard) id know how to make this client sided but idk server sodddd
I don't use Photon but you'll need to use an RPC to send the command to the other clients
A question regarding Lobby sample
#archived-unity-gaming-services message
sorry I have one more question, wouldn't it be easier if I networked the UI and made it as a child of the player instance?
like what would be the problem if I did that?
The main issue is that you can't spawn a network object as a child. You have to represent it after you spawn. And that jacks up the UI. Im sure that there are ways to deal with that but it just seems like more trouble than it's worth
alright fair enough, thanks again
bumper
Okay so i have this its a soundboard and basically on collision enter it enables the sound but the sound is only client sided and i would like others to here any ideas? (I USE PHOTON VR)
You would use an RPC to send that client to the other clients
welcome to NGO
{
Debug.Log("Received room list update. Count: " + roomList.Count);
for (int i = 0; i < AllRooms.Length; i++)
{
if (AllRooms[i] != null)
{
Destroy(AllRooms[i]);
Debug.Log("Destroyed room object: " + AllRooms[i].name);
}
}
AllRooms = new GameObject[roomList.Count];
for (int i = 0; i < roomList.Count; i++)
{
if(roomList[i].IsOpen && roomList[i].IsVisible && roomList[i].PlayerCount >= 1)
{
GameObject Room = Instantiate(RoomPrefab, Vector3.zero, Quaternion.identity, _content.transform);
Room.GetComponent<Room>().Name.text = roomList[i].Name;
AllRooms[i] = Room;
Debug.Log("Adding room: " + roomList[i].Name);
}
}
}```
Why its not called back?
we'll need to more information
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class RoomsList : MonoBehaviourPunCallbacks
{
public RoomItem roomItemPrefab;
public Transform _content;
public List<RoomItem> roomItemsList = new List<RoomItem>();
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
UpdaeRoomList(roomList);
}
void UpdaeRoomList(List<RoomInfo> list)
{
foreach (RoomItem item in roomItemsList)
{
Destroy(item.gameObject);
}
roomItemsList.Clear();
foreach (RoomInfo room in list)
{
RoomItem newRoom = Instantiate(roomItemPrefab, _content);
newRoom.SetRoomName(room.Name);
roomItemsList.Add(newRoom);
}
}
}```
The `OnRoomListUpdate` function does not work for some reason
maybe because you are not in a lobby yet?
but im yes
I understood why this happens.
A certain parameter is missing that causes the function not to be called, but which one?
@ripe mesa @sharp axle
I can't help you there, sorry. I don't use Photon
Has anyone ever dealt with XR Sockets in a VR project over a network while using Netcode for GameObjects? I am continuously running into the problem that once an object enters the socket it cannot be removed on the host and client side. I am using Client RPC's to change socketActive but it does not seem to be doing much. Been stuck on this for weeks...
Well can you help?
Hello guys, I'm trying to polish my multiplayer prototype and I have some issues to set the correct player to Cinemachine virtual camera, IDK why but my event subscriber doesn't call :
using UnityEngine;
using Cinemachine;
using System;
using Unity.Netcode;
public class PlayerCameraFollow : NetworkBehaviour
{
[SerializeField] private CinemachineVirtualCamera virtualCamera;
private void Start()
{
virtualCamera = GameObject.FindWithTag("Camera").GetComponent<CinemachineVirtualCamera>();
}
private void OnEnable()
{
GameManager.OnGameInitialize += OnGameInitialize_SetCameraFollowTarget;
}
private void OnDisable()
{
GameManager.OnGameInitialize -= OnGameInitialize_SetCameraFollowTarget;
}
private void OnGameInitialize_SetCameraFollowTarget(object sender, EventArgs e)
{
if (virtualCamera != null && this != null && IsOwner)
{
virtualCamera.Follow = transform;
}
}
}
Any ideas? here's my part of the code in my GamaManager when I call OnGameInitialize invoke:
public static event EventHandler OnGameInitialize;
public void StartRound()
{
OnGameInitialize?.Invoke(this, EventArgs.Empty);
isGameActive = true;
isPlayerAlreadySpawn = true;
}
I want to shoot as a client but if I create a clientprc it just doesn't work for the client, it doesn't shoot nothing.
However this is all server side spawning, which makes the bullet "desynced"
Whats the solution?
good morning everyone!
my scripts are grabbing the reference to the clones gameobjects instead of mine, any idea how to make sure it only grabs the owners only?
First, you'll need to make sure the correct muzzle position and rotation are set.
Second, make sure there is a network rigidbody so that the velocity is getting synced.
If BulletScript.parent needs to be synced back to the client then it should be a Network Variable.
Where is StartRound() getting called?
Distributed authority is one possible network topology you can use for your multiplayer game.
does unity not provide this? cant find anywhere how to implement distributed auth
Why would a transform be a networkvariable? I just want so the bullet is not desynced on the client and is shot right after I click
You might not need it at all. I have no idea what you are doing with the parent
this is part of the NGO 2.0 experimental branch. You'll need Unity 6 to install it
doesnt work /:
So my problem is when I shoot the gun on the client, it looks like it waits .5 ish seconds and then shoots it which makes it desynced.
On the host it works, since it is a server rpc, so how do I spawn the bullet on the client and verify it on the server?
Ok, thats just lag not actual desyncing. You can either just instantiate bullets locally or you can try out the distibuted authority in 2.0
https://docs-multiplayer.unity3d.com/netcode/current/terms-concepts/distributed-authority/
Distributed authority is one possible network topology you can use for your multiplayer game.
You'll need to install it by name. and the version is 2.0.0-exp.2
I debug my StartRound, it's called normally, actually It's called when the player it's enable
If you are subscribing to and invoking in OnEnable(), You are likely running into a race condition. Change the player Start() or OnNetworkSpawn()
actually I'm invoking on Awake let me try
tysm, it works
🙂
yea. Awake() is before onEnable()
I'm planning on making a game where people can play card games with other players and I'm thinking about using mirror. I want my game to support
- Playing against a "bot"
- Playing against up to 8 other players
- Playing against players invited by a player
- Playing against players joined by some sort of simple matchmaking system
If possible, I dont want to have to pay for any networking costs and have everything work peer to peer
Which multiplayer service do you guys reccomend?
play card games, is it turn based? what platform is it?
turn based i think and itll be like mac windows linux maybe webgl but prolly not
Fusion shared or pun no doubt
How do I instantiate them locally and then sync them to everyone?
I have this, but on the client it doesn't spawn it and it just floats in the air without moving
I would use the new [Rpc(SendTo.Everyone)] to just instantiate the bullet and set its velocity
I would send the position and rotation in the RPC
You don't need to Spawn() in that case.
I would also have the bullet script itself set its own velocity
Why I cannot see those virtual players?😭 Multiplayer Play Mode
hello I need help about my code for short i create a moba and I use photon (PUN) for the multiplayer and I don't understand who send to every player info about a variable
in red variable i need to send
I think i need to use RPC but don't understand how it works
It will need to be an RPC and you will probably need to send the the position instead of the entire gameobject
and who can i do that
I don't use photon. You'll need to read up on the docs
phototono
can anybody help me fix my code
it giving all of my clients the same movment so i can control another player when im trying to move and the same for the othe rplayer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FishNet.Connection;
using FishNet.Example.Scened;
public class playercontroler : NetworkBehaviour
{
[Header("Base setup")]
public float walkingSpeed = 7.5f;
public float runningSpeed = 11.5f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public float lookSpeed = 2.0f;
public float lookXLimit = 45.0f;
CharacterController characterController;
Vector3 moveDirection = Vector3.zero;
float rotationX = 0;
[HideInInspector]
public bool canMove = true;
[SerializeField]
private float cameraYOffset = 0.4f;
private Camera playerCamera;
public override void OnStartClient()
{
base.OnStartClient();
if (base.IsOwner)
{
playerCamera = Camera.main;
playerCamera.transform.position = new Vector3(transform.position.x, (transform.position.y +3) + cameraYOffset, (transform.position.z-2));
playerCamera.transform.SetParent(transform);
}
else
{
gameObject.GetComponent<PlayerController>().enabled = false;
}
}
void Start()
{
characterController = GetComponent<CharacterController>();
// Lock cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
bool isRunning = false;
isRunning = Input.GetKey(KeyCode.LeftShift);
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpSpeed;
}
else
{
moveDirection.y = movementDirectionY;
}
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
characterController.Move(moveDirection * Time.deltaTime);
if (canMove && playerCamera != null)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
}
}
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 falowed another tutorial and it worked the first time but now when i try to do the exak same its not working anymore
you use photon ?
Wishlist my FishNet game here: https://store.steampowered.com/app/2349410/Forging_Ahead/
This is episode 1 to the short series where i explain you how to setup a mutliplayer projects in Unity. In this video we will make the basic setup and have the basic position and rotation of the players networked. In just 7 minutes we go from an empty proje...
i did the same first time and it worked but the i had to start a new project and did the same thing agen and now its not working
sorry I don't use it
aight
What is the multiplayer tech behind mtg arena and hearthstone
For data sync and simulation
You need to make sure that only the local player is running the update. You should probably just disabke the player controller on the remote players
You can't send a gameobject in an RPC. Just send the collider.tranform.position
is this a bug in netcode or am I being bald
so I have a player object that is set to spawn in by the network manager, and its runs this coroutine on Start()
It's likely a custom web server of sorts. Games don't usually discuss their network architecture unless it's a gdc talk somewhere
for some reason, setting stest throws a warning saying that the object might not be spawned (despite the fact that it is)
and an error is thrown if I try to change PlayerID, which is the same as stest exept its a FixedString128Bytes.
Don't run it on start. Use OnNetworkSpawn instead
fair
but that wouldn't fix the problem
unless its taking over 5 seconds to spawn it
also I specifically told it to wait until it actually is spawned
anyway, tracing the error it seems to come from here saying "object reference not set to an instance of an object"
thats in the NetworkVariable.cs file from netcode
was wondering if there was anyway to modify this file to delete this line, it keeps undoing my edits if I try
or if there is any way to not make unity die
The problem is that the object not spawned. I'm not even sure the isSpawned property is properly initialized by the time start() runs.
Start() runs before the network manager connects to he network
im aware
but this code runs way after its connected
I just threw together that example to try and see if I could figure out why it wasn't working, but I haven't been able to find anything
so does this spawn the object before its connected to the network?
because thats whats spawning the player lol
again, this is the code thats running
stest appears to work with a warning in the log, but PlayerID doesn't
the code works but brakes when i add animations
For dynamicly spawned objects Start() is after OnNetworkSpawn for in scene objects Start() is before. I always just stick with OnNetworkSpawn.
If it's only the fixedstrings that's failing then that might be a bug. 1.9.1 made some changes to network variables that could have introduced some bugs
im in 1.7.1 since im in 2021.3.19
Weird. Fixedstrings worked fine then. If you can reproduce that in a fresh project then open a GitHub issue on it
wack
so im doing some testing
this also does not work
and neither does the "safe" varient of WriteValue
I can prob get around needing network vars for strings, its just annoying
sorry don't understand
gameObject is not serializable so you can not send it over the network in an RPC
yes that I understand now , but who can i do ? (sorry my english)
me out here just making my own network variables because netcodes wont work
If you only need the position then you can send collider.transform.position instead of collider.gameObject
Hey not sure if this is the right channel bc I havn't used this in ages. I am having trouble with my Unity Server (Unity's Lobby and Relay System.) The issue is in my bootstrap code but is showing no errors and I have been stumped for days...
I have a dedicated server architecture multiplayer game. While I am planning on setting it up on Unity's Game Server Hosting, I don't plan on using it (since it costs). Since my game is lightweight, I could simply start up a dedicated build instance whenever my friends want to play. I don't know how to do things like "port forwarding" and "NAT Punchthrough." Most of the tutorials I find are for Relay or Game Server Hosting (Multiplay), can anyone point me to tutorials on how to make a player-hosted dedicated server?
Why multiplayer play mode doesn't work with unity 6 preview?
It always shows a timeout when opening a virtual player window
Whoever is running the server will need to setup port forwarding on their router. That process is different for every router.
I don't know what error you are getting but I use MPPM in Unity 6 so it does work. I had some error when I first updated and had to delete the Library folder and restart Unity
I will try
Are you working with unity 6 preview?
yep
Here. MultiplayerPlaymode]: Timeout reached for client message 'OpenPlayerWindowMessage:0d0dc11b71824956b50030438f99cb19'
UnityEngine.Debug:LogWarning (object)
Unity.Multiplayer.Playmode.Common.Runtime.MppmLog:Warning (object) (at ./Library/PackageCache/com.unity.multiplayer.playmode/Common/Runtime/Log/MppmLog.cs:12)
This is weird. I can hear the intro sound two times but I cannot see that virtual player window
Are you using MPPM 1.0?
I'm using 1.0.0
So yes
So when you have two players activated (main editor + 1 virtual player) and then you click play then the editor will start playing and a new window will be opened?
You should be seeing the virtual player window even before you hit play
And where can that window be?
In that case, either it is hiding somewhere because I can hear audio or it's an error and I will delete the library and restart
its technically a separate editor, but if you are hearing it then the process is running somewhere
when you check the virtual player you should be seeing a new editor start up
You mean completely new editor running?
yes
No, I can't see it 😭
I can see how it's only activating then it's active but no new editor
Should I show it in explorer and then manually open that virtual player?
I don't think that will work. Does the same thing happen with player 3 and 4?
Yes. Simply, those virtual players won't show up
I will try deleting the library folders.
Now I am hearing intro four times
And will focusing work?
Select which virtual player to view in the Multiplayer Play Mode window.
i don't know, maybe. But if you aren't even seeing the window, I'm not sure it will work
So in your case, when you enable the second virtual player then a completely new window opens? Once a virtual player is activated?
Yes. A whole new editor will load and import assets
Just a question about network variables, why can’t you use strings?
I know you can use fixed strings, but I’m pretty sure not normal ones, and it doesn’t make much sense to me since you are able to strings in RPC methods
in the earlier version Network Variables would only support value types like structs. Strings just weren't part of the built in types supported
Strings have an unbounded size and cannot be sent efficiently over static buffer sizes
ie they would make it impossible to have a zero allocation netcode framework
In the latest versions of NGO they added support for the Lists and Dictionaries so strings should be less of a problem
But they work in RPCs, does this not have the same problem?
I suppose you are free to implement non-smart things in RPCs then.
anything that’s not a primitive value or struct thereof isn’t ideal to be synchronized through a high performance realtime game networking framework
you can sync lists etc, but the expectation is that you know and understand the tradeoffs of doing that
Potentially unity has added support for unbounded types for convenience reasons, since in many situations people do not care at all about performance. And for them it’s just frustrating if they can’t send a novel and json files through a RPC for init/setup etc.
Its also pretty easy to set up a custom serialization from a string to a fixedstring
Looks like I am not the only one with this error. https://forum.unity.com/threads/virtual-player-no-showing-up.1575088/
Do you also have the a* Pathfinding asset? I saw that thread when I was having my issues.
No, but I have a lot of assets from Unity asset store
But I tried to make a new project without anything and I enabled virtual players and still nothing.
I have that timeout warning
Will this help?
Maybe, if your issue is that language bug
After adding nothing related to spawning players, I suddenly can't spawn a player on a client join... a host player is spawned fine, but the client prefab is not spawned on either instance, making this fail:
public void onPlayerJoined(ulong playerId)
{
print("onPlayerJoined "+playerId+" ");
if(!IsServer) return;
print(NetworkManager.ConnectedClients[playerId].PlayerObject.name);
var player = NetworkManager.ConnectedClients[playerId].PlayerObject.GetComponent<PlayerController>();
after attempting to get the newest connected client. onPlayerJoined is subscribed to the NetworkManager.OnClientConnectedCallback += onPlayerJoined;
It is mind-bending why adding a few Mono-behaviors results in the clients not being able to connect. This is the exact error I receive when trying to get a [playerId].PlayerObject
MissingReferenceException: The object of type 'NetworkObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.get_name () (at <30adf90198bc4c4b83910c6fb1877998>:0)
GameMaster.onPlayerJoined (System.UInt64 playerId) (at Assets/Core/GameMaster.cs:27)
Unity.Netcode.NetworkConnectionManager.InvokeOnClientConnectedCallback (System.UInt64 clientId) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/Connection/NetworkConnectionManager.cs:45)
if I remove the code calling for it the issue persists until I reference the connected clients somewhere else. Googling and browsing docs results in nothing, was wondering if anyone got a cure for this
What is even more bizzarre is that when the client joins, the host-client is correctly replicated on the client, and the connectedclients count is correct (2),but when it comes to spawning the client playerObject, it's gone. I am not destroying the playerobject anywhere in my code (didn't implement dying and exiting, they are eternal)
Best hope is reverting changes made so far and doing baby-steps to see what failed, but that's some hours I would prefer to not lose... thanks in advance
MaxPacketQueueSize
MaxPayloadSize
Are these values can be set at anytime or before Starting Host and Client?
Has anybody dealt with inconsistant crashes in your development builds? Me and my coworker have recently noticed game crashes, we can find them dating back to versions of our build we had 4 months ago ... But it only happens like every sixth time that we test it. We have Debugger Logs going and are not noticing much of anything helpful. If you have had this before how have you dealt with it?
Yes, I changed that line and it works now. Thanks to MPPM and you I managed to successfully test lobbies. Thanks!
Hi, I have a question about using Cross-play with Game Server Hosting to enable cross-platform gaming. I'm looking at the example code below
// Create a UDP driver
var udpDriver = NetworkDriver.Create(new UDPNetworkInterface());
udpDriver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7777));
udpDriver.Listen();
// Create a WebSocket driver
var wsDriver = NetworkDriver.Create(new WebSocketNetworkInterface());
wsDriver.Bind(NetworkEndpoint.AnyIpv4.WithPort(7778));
wsDriver.Listen();
// Add both drivers to a new MultiNetworkDriver.
var multiDriver = MultiNetworkDriver.Create();
multiDriver.AddDriver(udpDriver);
multiDriver.AddDriver(wsDriver);
As per the sample, the udp and web socket drivers are bound to different ports. Multiplay (Game Server Hosting) only returns a single port when getting an allocation config BUT are all the ports in between allocations open too? E.g. when my Multiplay servers start, available visible ports are 9000, 9100, 9200 etc. BUT every port in between is also open and can be bound/listened to?
Does that mean for Cross-play setup, its as simple as binding the udp driver to port 9000 and binding the web socket driver to 9001?
Hmm. It does indeed look like the intermediate ports are available to bind to. Just tried binding to 9001 and connected no problem.
I have a dedicated server build, and when it's starting up I get 4-5 Curl error 6, could not resolve host. This doesn't appear in editor console logs. Looking at my client build logs and editor log file, they are also getting several Curl error 6. What is Curl error 6 exactly, since it apparently isn't an error or exception.
Google ‚unity netcode lobby‘
Hello,
Does anyone what experience about gamelift + mirror on webgl??
I developed a build which is working on desktop, but the same build not working on webgl platform
You are looking for Unity Lobby + Relay + Netcode integration
Are you running both on the same PC?
You'll need to switch Authentication Profile if you are using Anonymous Sign in
It should.
Hi , did you know this error : NetworkRoomManager no RoomPlayer prefab is registered. Please add a RoomPlayer prefab. I try to configure my NetworkRoomManager , i create a prefab for the RoomPlayer prefab but its didnt working
First, remove the player prefab from the network manager. Then you can call .SpawnAsPlayerObject(clientId) on any network object you want from the server
https://docs-multiplayer.unity3d.com/netcode/1.9.1/basics/networkobject/#creating-a-playerobject
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:
Should I get that client ID from NetworkManager.Instance.LocalClientId?
That would need to be the client id that you want to own that player object. If you use local client id from the server then the server will own it.
hello, quick question, currently all I want is for 2 players to be able to play a turn based game, I am trying to avoid a server as this is just a turn based, everything that a user do, can be sent in a similar pattern as notification. The other player's game will just wait for those notification and update the games state.
Now, my question is which tools or library is best for my use case? an example would be a tictactoe game.
I have read playfab but is it really necessary
Hello everyone, I have a question regarding networking(not sure if this is where I'm supposed to ask in, I apologise if it isn't)
So I'm planning on getting a server PC for my unity game so I can run the whole multiplayer system on that server pc instead of relying on cloud hosts, my question is what do I need to make it work? What programs do I use, how do I setup a cloud system on the server PC? If there's a tutorial out there that you can share I'd be greatly appreciated!
Learn about port forward and NAT
if your game blows up, now learn security
Hi everyone, I have big issue on my little 2d multiplayer game. I have create my map with a tile map with a tilemap collider 2d, a player prefab with Box Collider 2d and a rigidbody 2d ! All works well without the network part ! But when i add the network Rigidbody 2d, my player overlap on evvery prefab and tilemap... Really need help 🙏
Would it work the same as Unitys Multiplay?
on premis / self hosted is a little different
the concept is same for terraria/minecraft server hosting
Would I be able to achieve something similar in the future? Because all I'm trying to do is to run my game through my own server pc and not use the cloud that they have offered
the concept is same for terraria/minecraft server hosting
run minecraft_server.exe -port 25565 -maxPlayers 10
now you have to do the networking part, the NAT and port stuff I said
You can use Cloud Code for this. Here is a tic tac toe example using js Cloud Code
https://github.com/Unity-Technologies/com.unity.services.samples.use-cases/blob/main/Assets/Use Case Samples/Cloud AI Mini Game/README.md
And here is a chess game using c# modules
https://github.com/Unity-Technologies/com.unity.services.samples.multiplayer-chess-cloud-code
Would the tic tac toe module be usable in a 3D game?
I don't see why not.
And I can run that through a server pc I own?
No, Unity cloud code and cloud save are web services. But there is no reason you couldn't make your own node js server that do the same thing
Is there a tutorial on how can I make one? Because I'd be better off running my own server through my own server pc than cloud it
there are tons of node js tutorials out there
So okay, I've done the node js server and all that
Once I've done it, what's the next step to making it work with unity?
there is not really a next step. you make web requests to the node server
https://learn.microsoft.com/en-us/gaming/playfab/features/social/groups/using-shared-group-data
I guess this is what I am looking for
Yea. that's the same thing as Unity Cloud Code just using Azure Playfab
im watching a tut on how to make a game multiplayer and when deciding to join as a host or client the oyutuber makes 2 seperate buttons for them, and also, he makes those buttons in the same scene that the client would join on.
What if i want it to check if there is a server, and if not, join as a host, otherwise, join as a client, and to do so in a different scene, like from main menu scene, you click play, looks for server, lets say it found one, then it joins you as a client i nthe game scene
It depends on how you are hosting your servers. If you are self hosting then would need to use a relay service with a lobby system. Then you can look for all open lobbies and use it to connect to your server
im using unitys lobby and relay thingie, registered and downloaded all the packages and stuff
Hello everyone, does anyone here have a server hosted on AWS and the game running on itch.io?
I need help configuring the server to accept HTTPS requests.
I know I need the SSL certificate, but if anyone can help, I would be grateful.
I obtained the certificate using a different domain, not the itch.io domain. How do I proceed?
Hello everyone, apologies if this has been asked before, but i've just joined a multiplayer mmo style project, they are using NetCode for Entities, and plan on using a Dedicated Server.
I'm still ramping up, and they have followed the examples and demos in the docs: https://docs.unity3d.com/Packages/com.unity.netcode@1.2/manual/client-server-worlds.html
But I've got this funny feeling about the NetCode Client Target, it appears the only options are "Client" or "ClientAndServer"... and I'm confused, why would I want a client running on my headless dedicated server? I understand that if i change the platform to Dedicated Server, it adds the scripting define UNITY_SERVER that can be checked in code, but I refuse to litter my code with compiler flags, so I'm super surprised there is no Server target as far as NetCode is concerned and there are just never any client worlds allowed to be created in it just as if Client is the target there are no Server worlds allowed to be created.
Maybe the answer is just "because the system needs it, i can ignore it, it will never do anything" but that bugs me. We never plan to have a client host a server, so they should never be in the same process. I understand there's some "world" generation stuff going on that I'm still new to but has this been discussed before?
MaxPacketQueueSize
MaxPayloadSize
Are these values can be set at anytime or before Starting Host and Client?
I'm pretty sure they can be set at runtime. I'm not sure why you would be changing it after connecting though
In my case, There can be upto 20 Clients connected and i want to make sure these size vars updated based on the equation i fount on the internet
I call these whenever the client connects and disconnects.
Please correct me if i am wrong
transport.MaxPacketQueueSize = networkManager.ConnectedClientsIds.Count * 32;
transport.MaxPayloadSize = (networkManager.ConnectedClientsIds.Count + 10) * sizeof(float) * 3 * 3 * 10;
These changes on both client and host
What's the issue with just setting the max to the 20 client limit from the start?
I saw in a forum that setting these values high creates useless memory buffers
I can be wrong
Do I set these high already?
Also are these calculations correct?
Dunno. I've never had any issues from the defaults. Literally have never changed them
Ohh i see
If you are seeing dropped packed from a full message queue then you might have other issues going on
I didnt seen any. But i cannot test the game with 20 players. So i am not sure
Hi guys, hopefully quick question. When a RPC is called from a client to the server, if the code interacts with the scene hierarchy is it seeing the gameobjects of the server or the ones of the client that called it?
It would be wherever it's running. If the rpc is running in the server then it will be the server scene. If it's sent to other clients then it will be that client's scene
Thanks appreciate it 🙏
If I am making a new game that I plan on making co-op capable, is it an ok plan to make the game itself first and then add multiplayer capabilities? Or does the co-op stuff have to be integrated into the codes from the beginning
you can rework a game to add it in later, it's just harder than building around it from the start
If you add it later you'll end up rewriting most of you code.
can u explain how one would look for open lobbies if they are using unity relay and lobby
Hey guys, I used the SimpleWebServer to test a WebGL build locally on localhost:8017, how can I stop the server from running?
You can query for lobbies with available slots, or any other variables you want to set
https://docs.unity.com/ugs/en-us/manual/lobby/manual/query-for-lobbies
I think you just have to stop the SimpleWebServer.exe process manually
The problem is there is no SimpleWebServer.exe running on cpu
How are you running it?
I ran through cmd, on simplewebserver dir, and then /SimpleWebServer.exe "build_dir" 8017
terminate it through task manager
or cmd task kill command