#archived-networking

1 messages · Page 24 of 1

lavish scaffold
#

i tried network lists but it gives me error for NullObjectReference
it alwas used to show me that error whenever i tried to
list.Add(0)

waxen quest
waxen quest
#

And only server or host can add or remove or update list not clienst

lavish scaffold
#

and i also tried to initiale it when i instantiated it

waxen quest
lavish scaffold
lavish scaffold
#

i do am using a network behavior component

waxen quest
#

The class should use this

public class PlayerDataHandler : NetworkBehaviour

#

Not MonoBehaviour

lavish scaffold
#

yeah i am implementng that too

waxen quest
#

and there should be component NetworkObject added in that gameobject

lavish scaffold
#

network object is also attached as component

waxen quest
#

ohh

lavish scaffold
#

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

waxen quest
#

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

lavish scaffold
#

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?

waxen quest
lavish scaffold
#

yeah you were right

lavish scaffold
#

and as host is also a client

#

it overloaded the function

waxen quest
#

Nice you found out

crude peak
#

how do i install netcode for entities 1.2

#

since unity package manager only allows 1.0.17

empty quiver
#

click the little plus top left of package manager and install by name

lavish scaffold
#

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>();
sharp axle
lavish scaffold
sharp axle
lavish scaffold
#

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

sharp axle
lavish scaffold
weak plinth
#

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?

neat veldt
#

in this case most likely a RPC

sharp axle
# weak plinth I'm very new to networking...this is a very beginner question. Let's say I'm us...

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.

rapid crater
#

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?

remote relic
#

If (IsServer){
Movement code
}

#

@rapid crater

#

You only attach the ClientNetworkTransform to an object you want the client to be able to move

rapid crater
#

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

remote relic
#

Does your game need to have strict server authoritative movement?

rapid crater
#

my final game will, yes. a part of avoiding cheating

remote relic
#

Ok are you using a dedicated server or host?

rapid crater
#

the final game will use dedicated server. while learning, just using host usually. but, will attempt to test with dedicated, asap

remote relic
#

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

remote relic
rapid crater
#

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

sharp axle
#

Lag is going to be something you will need to deal with one way or another

rapid crater
#

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' :/

sharp axle
#

There are some very neat changes coming to NGO soon that will help a ton in mitigating latency

rapid crater
#

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

sharp axle
rapid crater
#

2 hours and 35 minutes to be exact! 😄 samyams multiplayer tutorial

sharp axle
weak plinth
weak plinth
arctic iris
#

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.

rapid crater
sharp axle
weak plinth
sharp axle
#

Or over on the Unity Netcode discord server

weak plinth
#

Oki

arctic iris
split hedge
#

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.

sharp axle
split hedge
#

Sometimes!

#

It returns null, but also the weapon

#

What??

#

Btw, these debugs only run on the server

molten hazel
#

hi is there any code equivelant of
if (inside lobby)
//multiplayer stuff
else
//singleplayer stuff

orchid mortar
molten hazel
lavish scaffold
#

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

sharp axle
molten hazel
molten hazel
#

obv ill be using lobby when theres multiplayer involved

#

but kinda seems like a waste to me if there wont be any multiplayer involved

sharp axle
molten hazel
#

huh

molten hazel
#

not even like
if (isOwner != null)
else

sharp axle
molten hazel
waxen quest
#

Anyone?

sharp axle
sharp axle
waxen quest
molten hazel
warped pilot
#

Is the Networkmanager.Singleton.LocalClientId always 0 on the host ?

neat veldt
#

(for unity transport it's 0)

warped pilot
#

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

neat veldt
#

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

warped pilot
#

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();
    }```
neat veldt
warped pilot
#

yes

neat veldt
#

alr

warped pilot
#

I have already my function working but I dont know the clientid ^^

#

so i want set it up when I join / create a lobby

neat veldt
#

I'd send over some data the usual way with a NetworkVariable

warped pilot
#

so what is a good practice to save my client id in the lobby data ?

neat veldt
#

Again, not sure, but I don't think it's the best solution here

#

feels like you can handle it without the lobby system

warped pilot
#

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 ?

neat veldt
#

First off Debug.Write doesn't exist or is some other Debug, not the unity one

sacred schooner
#

Debug.Log or print should do just fine

rapid crater
#

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

wet berry
#

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”

warped pilot
#

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) },
            }
        };
    }```
sharp axle
simple spire
#

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?

sharp axle
simple spire
# sharp axle You'll need to make sure that only the host/server is running this code. Clients...

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);
sharp axle
simple spire
#

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-

hazy sonnet
#

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'

sharp axle
split hedge
#

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.

sharp axle
split hedge
sharp axle
dire rose
#

anyone here works with photon ?

dire rose
dire rose
loud bluff
dire rose
loud bluff
split hedge
#

So clearly the weapon is null, but how can it be?

#

Also its not null

#

But null

#

Ha?

spare vault
#

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.

sharp axle
sharp axle
wet berry
sharp axle
wet berry
#

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.

sharp axle
wet berry
#

thats what i thought, just making sure

#

thanks again :)

spare vault
junior flower
#

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);
        }
    }
}```
sharp axle
# junior flower Hey guys, I'm thinking of making some performance into my game to save bandwidth...

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:

junior flower
vocal hornet
#

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

wet berry
#

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.

sharp axle
wet berry
#

okay, ill try to post the same message there

desert gulch
#

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?

sharp axle
desert gulch
#

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

sharp axle
#

when either host or client pickup the powerup,

vestal bronze
#

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.

storm sierra
#

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

sharp axle
# storm sierra Hello, how would I go about setting the spawn points for players in netcode? Eac...

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.

storm sierra
wild mortar
sharp axle
#

If you are using physics.simulate() then it should be fine to use move() as well

sharp axle
rich basalt
#

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.

lavish scaffold
#

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?

hearty dock
#

Does this inner object do something that needs networking features?

vital kernel
#

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!

lavish scaffold
# hearty dock Does this inner object do something that needs networking features?

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

hearty dock
lavish scaffold
toxic marsh
#

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?

winged socket
#

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.

storm sierra
#

Anyone know how to use Server/clientRpc's?

nimble drift
#

is Netcode for Gameobjects expandable?
like can u build up on it
because im not sure which solution to pick

sharp axle
sharp axle
sharp axle
sharp axle
nimble drift
#

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

sharp axle
#

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

nimble drift
#

since it was a singleplayer game before

wild mortar
wild mortar
#

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)

harsh glade
#

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.

nimble drift
#

Offline Transport (Single Player) Allows games to be played offline without the need of an internet connection.

#

im reading a networking solution comparison chart

nimble drift
#

what does it mean?

#

like cant u make singleplayer and multiplayer without this?

fluid walrus
#

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

timber pebble
#

are network variables still datatypes only?

sharp axle
timber pebble
timber pebble
#
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

timber pebble
#

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

nimble drift
#

why cant i delete this?

#

as soon as i delete it a new one is made

#

cause i have another one already

sharp axle
# nimble drift

its in the project settings to automatically create a default network prefab list

nimble drift
#

where

sharp axle
timber pebble
#

are these okay to use in networking?

mild magnet
#

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

nimble drift
#

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

harsh glade
nimble drift
#

no

nimble drift
sharp axle
nimble drift
#

what do you mean

sharp axle
nimble drift
#

no the camera its inside of the prefab

#
    Movement - (Movement script with rigidbody, collider etc)
    Camera Holder
        Camera ```
#

Player is the prefab

wild mortar
#

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)

river gazelle
#

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

rotund night
#

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.

austere yacht
#

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

rotund night
austere yacht
rotund night
sharp axle
rotund night
sharp axle
rotund night
# sharp axle Nice! Where exactly is it? I glanced around the repo a bit but couldn't really f...

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

GitHub

Megacity-Metro: a thrilling shooter game, using Netcode for Entities for a multiplayer experience supporting 128+ players. Latest DOTS packages and Unity Gaming Services elevate the user experience...

flint grove
#

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

sharp axle
#

its not getting despawned for me right

rain olive
#

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);
      }
  }
wild mortar
twilit ingot
#

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.

junior sapphire
#

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?

sharp axle
signal iris
#

Is there any way to store a colour into a customproperty for photon?

stable dust
#

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?

sterile creek
wild mortar
subtle tulip
warped pilot
#

Do I have to add a Prefab Variant to Networklist too ?

sharp axle
nimble drift
#

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

strange jungle
spring galleon
#

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.

vestal meadow
#

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?

loud echo
#

does unity have free servers or will i need my own

hazy sonnet
sharp axle
sharp axle
loud echo
#

idk im just tryna make a pvp game

hazy sonnet
sharp axle
hazy sonnet
#

can i loop through them like this?

foreach (var clientId in Networkmanager.Singleton.ConnectedClientsIds)
{
NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject
}
#

like this

round ether
#

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

sacred schooner
#

google parrelsync

#

godsend

sharp axle
opal night
#

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?

austere yacht
#

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

opal night
#

ahh nice, which ones do it automatically? is that Mirror / Photon ?

austere yacht
#

None of the ones you mentioned or any of the ones that are fit for recommendation

dry maple
muted garden
#
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?

opal night
#

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.

dry maple
opal night
#

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.

dry maple
opal night
#

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.

opal night
#

thx!

fringe imp
#

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

fringe imp
#

😭

strange jungle
fringe imp
fringe imp
strange jungle
#

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

fringe imp
#

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?

strange jungle
#

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

fringe imp
#

also thanks so much for helping

strange jungle
#

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

strange jungle
#

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

fringe imp
#

@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?

fringe imp
#

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!

warped pilot
#

As client I get this error: NotServerException: ConnectedClientIds should only be accessed on server.
Can someone help me there ?

fluid walrus
sharp axle
warped pilot
#
{
    [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 ..

warped pilot
#

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 ?

fluid walrus
#

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?

warped pilot
#

ok i give it a try

#

ok now it is working correctly

fluid walrus
rain olive
#

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

neon rampart
fluid walrus
#

where are you setting the headers?

neon rampart
neon rampart
#

I should also note that the server works fine

fluid walrus
#

hmm what's the error you get in the browser?

neon rampart
#

For non webgl clients

rain olive
neon rampart
#

(I'd remove the embedded image from the link but I'm on mobile)

fluid walrus
#

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

neon rampart
#

Yeah but i see absolutely no request in my local server...

fluid walrus
#

yeah, it's a browser feature

#

in chrome it should work if you run chrome with the --disable-web-security command line option

neon rampart
#

Point is that it uses standard libraries from C#

#

So if there were any requests, it should've caught them

fluid walrus
#

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

neon rampart
#

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?

fluid walrus
#

yup

neon rampart
#

I'm asking to make sure that I've got the concept right

fluid walrus
#

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

neon rampart
#

@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

unkempt glade
#

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

haughty heart
#

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.

unkempt glade
haughty heart
#

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.

noble flower
#

Yo guys quick question. Is Mirror a LAN or WAN

oak flower
#

What would be a point of lan only framework. Mirror also supports several punch-through frameworks as well for p2p connection.

neon rampart
#

if anyone in the future wanted to know how, my solution is open source, at this permalink

rain olive
#

🤷‍♂️ 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

neon rampart
#

if you don't mind, it's alright. but for some cases, dependencies are not desirable

warped pilot
#

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;
    }```
main bloom
#

Not sure if this belongs here but:

#

Sry for it being an image, just copied it from another place where I asked

warped pilot
#

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

sharp axle
#

Wrong type of networking, my dude

storm sierra
#

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

heady sentinel
#

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.

tight orchid
#

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

brisk chasm
#

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?

main bloom
#

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

brisk chasm
#

yea i looked into mirror but i didnt find alot documentation about p2p

main bloom
#

what do you mean?

brisk chasm
#

peer 2 peer

main bloom
#

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

brisk chasm
#

do you have a link to the p2p docs?

main bloom
#

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

brisk chasm
#

alright thanks ill check it out

main bloom
#

If you have questions you should ask on the mirror discord, they are very helpful there

brisk chasm
#

alright thanks

warped pilot
#
    {
        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 ..
storm sierra
#

Unity relay

warped pilot
#
    {
        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 ?
blissful jay
blissful jay
main bloom
#

I told him there is a variety of transports for p2p

blissful jay
#

it's a complete different paradigm of game networking

#

unsupported by mirror

main bloom
blissful jay
#

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

main bloom
#

Cool

#

Good to know I guess xD

#

Told you I dont have any experience and never did any networking

cosmic veldt
#

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?

blissful jay
#

it would be the easiest job in the world to do remote code execution and do huge damage so easily

cosmic veldt
#

Yeah lol. Just getting exposed to netcode. I just wanted to make sure I wasn't creating a massive security problem xD

sharp axle
river gazelle
#

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

  1. Player logs in

  2. Client requests a random seed from server

  3. Server generates a random seed, saves it to the database, sends it back to the client

  4. Player clicks “Adventure”

  5. Client immediately starts adventure using the random seed received in step 3

  6. After each important event, the client sends a notification to the server

  7. The server re-calculates all combat and rewards up to then, with the random seed to check if everything is still ok

  8. Server saves everything to database and generates a new random seed, saves it to the database and sends it back to the client

  9. After the next important event, the client starts using the new seed

  10. 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!

main bloom
#

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?

river gazelle
#

Does someone have experience with

cedar garnet
#

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)?

sharp axle
cedar garnet
dreamy condor
#

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?

sharp axle
dreamy condor
#

Thanks, but what if it's planned to have the game downloaded, and i need to connect into it?

sharp axle
spring galleon
#

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?

mortal vessel
#

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?

mystic gorge
#

Just saw a group of seagulls flying outside at 2 am now😱

#

The moon is so bright that seagulls thought it’s daytime

sharp axle
# spring galleon Hey guys! I'm making a network multiplayer air hockey game on Unity with NGO and...

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

GitHub

[1.9.1] - 2024-04-18
Added

Added AnticipatedNetworkVariable, which adds support for client anticipation of NetworkVariable values, allowing for more responsive gameplay (#2820)
Added AnticipatedNe...

#
GitHub

A collection of smaller Bitesize samples to educate in isolation features of Netcode for GamesObjects and related technologies. - Unity-Technologies/com.unity.multiplayer.samples.bitesize

spring galleon
#

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?

sharp axle
spring galleon
#

😩

nimble drift
#

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

main bloom
nimble drift
#

they dont

#

apperantly

#

after everyone leaves

#

including my self

#

i can still join with the old code

main bloom
#

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?

nimble drift
#

yeah

main bloom
#

Im doing the same

nimble drift
#

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

main bloom
#

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

nimble drift
#

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

main bloom
#

how do you join/ create the lobby

#

You sure its the same lobby and not a newly created one?

stable dust
#

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

warped pilot
#

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.
twilit ingot
magic mirage
#
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?
warped pilot
round ether
sharp axle
round ether
round ether
#

or can i like update the old clone?

sharp axle
sharp axle
round ether
#

thanks! ill try rn

#

no didnt work i even tried creating a new clone and its same as old one

shut coyote
#

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!

bronze tendon
#

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

mortal vessel
#

If you were making a stock market game in Unity which networking framework would you use

sharp axle
bronze tendon
# sharp axle The players are moving locally but not across the network? Should you be using a...
{
    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
sharp axle
waxen quest
#

How can we make Kick / Ban system?

I am using Unity Netcode, relay and lobby together

sharp axle
waxen quest
bronze tendon
#

but it does, no?

mortal vessel
sharp axle
bronze tendon
sharp axle
gaunt summit
#

Hi all, was just exploring Fish-Net's documentation, do they no longer have examples?
Not sure if blind

sharp axle
gaunt summit
mortal vessel
sharp axle
gaunt summit
#

I just joined as you sent, great idea. Great minds think alike! 😄

blissful jay
granite stump
#

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.

ripe mesa
#

Fishnet is banned? What's the story

azure crown
blissful jay
#

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.

azure crown
#

Oh wow. Sounds like the ban was justified.

fringe imp
#
[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?
fluid walrus
#

not really networking, but there's an official unity mobile notifications package

#

i've never used it though

sharp axle
median viper
#

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

fringe imp
sharp axle
#

unless its not in a NetworkBehavior

fringe imp
#
[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

fringe imp
#

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!

violet tapir
#

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?

violet tapir
#

Really?

#

ok, then I have no clue why the objects doesn't Instantiate

sharp axle
#

As long as the items have unique names that won't be an issue. But I know very little about Photon

violet tapir
violet tapir
violet tapir
fluid walrus
#

what are the names you're passing in?

violet tapir
fluid walrus
#

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

violet tapir
#

ok

fluid walrus
#

is it logging an error?

violet tapir
#

For some reason it works now

#

Im really confused right now

fluid walrus
#

if it started working after recompiling, could be some static state inside the library that needed clearing

violet tapir
#

ok, thanks anyways

rapid crater
#

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

sharp axle
rapid crater
stray moth
#

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

sharp axle
stray moth
ornate pier
#

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 )

zealous seal
#

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

https://gdl.space/ulihacihih.cpp

hazy sonnet
#

how do i spawn a camera for a client and not replicate it across clients?

sharp axle
hazy sonnet
sharp axle
dreamy condor
#

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?

sharp axle
winged yoke
#

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?

median viper
#

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.

sharp axle
winged yoke
sharp axle
granite stump
#

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!".

sharp axle
granite stump
#

Unity Transport

#

I tried to change a couple of values, but I set them back to the default ones

sharp axle
granite stump
#

The Network Manager is only present in one initial scene that I never go back to

sharp axle
granite stump
#

I haven't, I will give it a try

#

Doesn't work. Is there a reset for the NetworkManager or something?

sharp axle
granite stump
#

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

zealous seal
#

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

https://gdl.space/ulihacihih.cpp

sharp axle
granite stump
#

Why does a NetworkList result into a memory leak?

blissful jay
west lance
#

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)

mint anvil
#

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)

sharp axle
median viper
#

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

sharp axle
median viper
#

If so, how can I implement that because I don't really get how I can use IDs instead of the scriptable object itself?

sharp axle
median viper
#

thank you

fringe imp
#

what should i make my tickrate for a non compettive p2p arena game? 4v4 physics based

sharp axle
sharp walrus
#

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?

sharp axle
sharp walrus
#

Oh duh, for some reason using that never crossed my mind, thanks

zealous seal
#

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"

sharp axle
median viper
#

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

sharp axle
median viper
#

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);
        }
sharp axle
median viper
#

so I am not sure what the problem is with the icons

median viper
sacred schooner
#
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

sharp axle
sacred schooner
#

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."

sharp axle
sacred schooner
#

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!

olive vine
#

<@&502884371011731486> i believe to be in the wrong channel

river gazelle
#

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?

bitter bough
zealous seal
# sharp axle Start() is probably getting run too soon before the network is connected
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

verbal oracle
#

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.

sharp axle
#

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

visual spire
#

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

sharp axle
white igloo
#

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?

sharp axle
river gazelle
zealous seal
#
   {
        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??
median viper
#

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);

}
split hedge
#

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?

stable shadow
#

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

median viper
#

Do I need to put a separate canvas for each player instance?

sharp axle
median viper
#

obviously the player only gets instantiated when someone joins the lobby

#

the 4 slot prefabs have the scene canvas as their parent

sharp axle
old seal
#

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.

frozen acorn
#

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)?

sharp axle
sharp axle
#

The Epic Online Services and Steamworks are free to use as well.

frozen acorn
#

Dedicated server model. But I don't have an ability to pay for backend. Either open source or my code

sharp axle
frozen acorn
#

Sounds sad, where should I start then?

sharp axle
frozen acorn
sharp axle
round ether
#

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

sharp axle
cobalt gust
median viper
#

like what would be the problem if I did that?

sharp axle
median viper
round ether
#

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)

sharp axle
zealous seal
#
   {
        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?
sharp axle
zealous seal
# sharp axle 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
ripe mesa
zealous seal
#

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

sharp axle
carmine iris
#

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...

split hedge
flint bluff
#

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;
    }
split hedge
#

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?

fringe imp
#

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?

sharp axle
sharp axle
fringe imp
#

does unity not provide this? cant find anywhere how to implement distributed auth

split hedge
sharp axle
sharp axle
split hedge
sharp axle
sharp axle
flint bluff
sharp axle
flint bluff
#

tysm, it works

#

🙂

sharp axle
spiral lark
#

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?

ripe mesa
spiral lark
split hedge
split hedge
sharp axle
teal cedar
#

Why I cannot see those virtual players?😭 Multiplayer Play Mode

crisp egret
#

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

sharp axle
sharp axle
crisp egret
#

I try that

#

and now a new bug

fresh pasture
#

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);
        }
    }
}
fresh pasture
#

i falowed another tutorial and it worked the first time but now when i try to do the exak same its not working anymore

crisp egret
#

you use photon ?

fresh pasture
#

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...

▶ Play video
#

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

crisp egret
#

sorry I don't use it

fresh pasture
#

aight

timid sinew
#

What is the multiplayer tech behind mtg arena and hearthstone

#

For data sync and simulation

sharp axle
sharp axle
# crisp egret

You can't send a gameobject in an RPC. Just send the collider.tranform.position

wide ferry
#

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()

sharp axle
wide ferry
#

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.

sharp axle
wide ferry
#

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

sharp axle
#

The problem is that the object not spawned. I'm not even sure the isSpawned property is properly initialized by the time start() runs.

wide ferry
#

ok

#

but it is spawned

sharp axle
#

Start() runs before the network manager connects to he network

wide ferry
#

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

wide ferry
#

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

fresh pasture
sharp axle
wide ferry
sharp axle
wide ferry
#

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

sharp axle
crisp egret
#

yes that I understand now , but who can i do ? (sorry my english)

wide ferry
#

me out here just making my own network variables because netcodes wont work

sharp axle
untold anchor
#

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...

untold anchor
#

Still causes issues, just less

open mirage
#

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?

teal cedar
#

Why multiplayer play mode doesn't work with unity 6 preview?

#

It always shows a timeout when opening a virtual player window

sharp axle
sharp axle
teal cedar
sharp axle
teal cedar
# sharp axle 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)

teal cedar
teal cedar
teal cedar
teal cedar
# sharp axle Are you using MPPM 1.0?

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?

sharp axle
teal cedar
teal cedar
sharp axle
sharp axle
teal cedar
sharp axle
teal cedar
teal cedar
teal cedar
# sharp axle yes

Should I show it in explorer and then manually open that virtual player?

sharp axle
teal cedar
#

I will try deleting the library folders.

teal cedar
sharp axle
teal cedar
sharp axle
wide ferry
#

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

sharp axle
austere yacht
#

ie they would make it impossible to have a zero allocation netcode framework

sharp axle
#

In the latest versions of NGO they added support for the Lists and Dictionaries so strings should be less of a problem

wide ferry
austere yacht
#

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.

sharp axle
#

Its also pretty easy to set up a custom serialization from a string to a fixedstring

teal cedar
sharp axle
teal cedar
teal cedar
teal cedar
#

Will this help?

sharp axle
sacred schooner
#

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

waxen quest
#

MaxPacketQueueSize
MaxPayloadSize

Are these values can be set at anytime or before Starting Host and Client?

carmine iris
#

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?

slender cedar
#

Hello

#

How i can do a LAN Game?

teal cedar
junior sapphire
#

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?

junior sapphire
#

Hmm. It does indeed look like the intermediate ports are available to bind to. Just tried binding to 9001 and connected no problem.

open mirage
#

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.

austere yacht
#

Google ‚unity netcode lobby‘

flat zenith
#

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

waxen quest
#

You are looking for Unity Lobby + Relay + Netcode integration

sharp axle
#

Are you running both on the same PC?

#

You'll need to switch Authentication Profile if you are using Anonymous Sign in

#

It should.

hybrid sonnet
#

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

teal cedar
#

How to manually spawn player?

#

Netcode

sharp axle
# teal cedar How to manually spawn player?

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:

teal cedar
sharp axle
urban blade
#

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

delicate sandal
#

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!

ripe mesa
#

if your game blows up, now learn security

green marsh
#

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 🙏

delicate sandal
ripe mesa
#

the concept is same for terraria/minecraft server hosting

delicate sandal
ripe mesa
#

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

delicate sandal
sharp axle
delicate sandal
sharp axle
delicate sandal
sharp axle
#

there are tons of node js tutorials out there

delicate sandal
sharp axle
sharp axle
trail ibex
#

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

sharp axle
trail ibex
boreal pagoda
#

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?

pearl girder
#

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?

waxen quest
#

MaxPacketQueueSize
MaxPayloadSize

Are these values can be set at anytime or before Starting Host and Client?

sharp axle
waxen quest
# sharp axle I'm pretty sure they can be set at runtime. I'm not sure why you would be changi...

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

sharp axle
waxen quest
#

I can be wrong

#

Do I set these high already?

#

Also are these calculations correct?

sharp axle
sharp axle
#

If you are seeing dropped packed from a full message queue then you might have other issues going on

waxen quest
#

I didnt seen any. But i cannot test the game with 20 players. So i am not sure

nova creek
#

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?

sharp axle
real mica
#

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

fluid walrus
sharp axle
trail ibex
real ravine
#

Hey guys, I used the SimpleWebServer to test a WebGL build locally on localhost:8017, how can I stop the server from running?

sharp axle
sharp axle
real ravine
sharp axle
real ravine
#

I ran through cmd, on simplewebserver dir, and then /SimpleWebServer.exe "build_dir" 8017

ripe mesa
#

or cmd task kill command