#archived-networking

1 messages · Page 17 of 1

weak plinth
#

and noone is controlling host

#

oh man im not sure in anything anymore but host screen is not moving thats what im sure of

#

and i cant seem to understand why

#

yeah they are both controlling client

sharp axle
#

You'll need to check that only the local player has input enabled

#

also there should only be one active camera in the scene if you have a camera in the player prefab

weak plinth
#

void Update()
{
if (!IsOwner)
{
return;
}

#

that is before my input

#

on player prefab

weak plinth
#

i do have cameras on my prefabs

true raptor
#

General networking question! I am creating a mildly competative pvp online game. I can't find much online about dedicated servers working with netcode for game object. Is this feasable for a one person team with a simple game or is it not worth it?

grim sluice
#

Hey i havea problem in netcode. I cant drag my player prefab into the network prefab list, althought a network gameobject script is attached

nova linden
#

How can i get the client id of the client that runs a script ? i have a server -> client rpc and i dont want whatever hapens in the client rpc to happen for the person that called the server rpc so i thought i could send teh client rpc to every client except one, can someone help me with this ?

shrewd junco
# true raptor General networking question! I am creating a mildly competative pvp online game....

Unity has their gaming services which allows you to host servers I believe, otherwise you'll have to look online at other server providers. I doubt theres gonna be any concrete examples out there, a lot of competitive games like to hide their server logic.
If you suspect the game will be pretty popular to the point that cheating would happen, its only feasible to maintain if you already somewhat know what you're doing

shrewd junco
nova linden
#

thank you

shrewd junco
#

Assuming the owner is the one who's running the code

nova linden
shrewd junco
nova linden
#

i solved it like this

shrewd junco
# nova linden i solved it like this

What's this for, when is networking hit called? I feel like you might be able to do this better with network variables depending on the functionality

nova linden
#

i have a gun and if your holding it you own it, if you shoot you call the Networking hit with the guns OwnerClientId

#

aswell as a localHit funktion that only happens for you but without the delay of the server client rpc

shrewd junco
nova linden
#

I get this error when i call the Networking hit funktion, where exactly is the problem with the misisn gobject ? I found the source of the error, its from The OwnerCLientId part

nova linden
shrewd junco
nova linden
#

i need the try catch because if the raycast didnt hit it would cause errors and this part works since i can hear the sound playing caused by the invoking of the localHit

#

wait it isnt the OwnerClientId but also not because the hit object doesnt have a HitDetector

shrewd junco
little violet
#

Can someone explain why this is happening, it leaves an fps of around 4-5

#

when i disable the audio, it returns to 40-50fps

frozen acorn
#

What are my options if I really need multiplayer working(both player host and server would work, but player host would be MUCH better) in WebGL, specifically, on itch.io? While if it's possible - keeping the budget to the min value possible

little violet
weak plinth
#

How can i correctly make a killfeed? it only works for 1 player, and will show that the player was killed by themselves so...

    {
        if (killer != null && killed != null)
        {
            KillFeed.instance.AddNewKillListing(killer, killed);
            killer = null;
            killed = null;
        }
    }```
```    public void Die()
    {
        PhotonNetwork.Destroy(controller);
        CreateController();

        deaths++;

        Hashtable hash = new Hashtable();
        hash.Add("deaths", deaths);
        PhotonNetwork.LocalPlayer.SetCustomProperties(hash);
        Debug.Log(PhotonNetwork.LocalPlayer);

        killed = PhotonNetwork.LocalPlayer.ToString();
    }```
```    [PunRPC]
    void RPC_GetKill()
    {
        kills++;

        Hashtable hash = new Hashtable();
        hash.Add("kills", kills);
        PhotonNetwork.LocalPlayer.SetCustomProperties(hash);

        killer = PhotonNetwork.LocalPlayer.ToString();
    }``` This is Pun 2 btw
quaint lake
#

I'm having a hard time finding a solution to only update clients of network positions/rotations when they are within a certain range. So if I have a multiplayer game with lets say 8 players but the map has POI's with NPC's that are wandering around or chasing players but some players are on the other side of the map, can I occulde network transform messages from them?

versed pawn
#

Does anyone know what Netcode for Entities is in terms of innerworkings?

#

Maybe I'm stupid but the docs are sparse. I can tell that its server authoritative and tracks inputs but beyond that I have no clue.

#

If anyone knows what kinds of data it sends over the network @ me

abstract copper
#

there isn't much to it that is outside of the ordinary

#

docs are probably sparse because its a well-documented approach

#

pretty sure they refer you to the overwatch netcode GDC talk if you want to learn the inner workings, since they were very inspired by it (I think I remember that being mentioned in the docs)

weak plinth
#

Can someone tell me how to get collider we raycasted into RPC call?

#

without raycasting in RPC call

mortal sluice
#

does anyone know their way around fishnet? My WebGL game (Bayou Transport) crashes when I set the IP address to anything except the localhost

abstract copper
abstract copper
brisk bluff
#

how do I test my games for p2p? do I just compile the project? I think there was a plugin that duplicated the entire project but this would take a long time, is there anything simpler I can do? In unreal and godot it's very straight forward and just opens more instances of the game

nocturne vapor
# brisk bluff how do I test my games for p2p? do I just compile the project? I think there was...

you need to build it or use Parallelsync which works by linking the files to the project and opening a second instance
this does not work however if you use a thirdparty transport solution which is account based, like steamworks, there you need a second machine
so building -> uploading -> updating depots -> exiting and reopening steam to get the new update -> test what you wanted to test

#

so having to build the game is not that bad, if you are annoyed however, use parallelsync

stiff hawk
#

hello is netcode for gameobject do not support webgl build?

nova linden
#

can non NetworkObjects call serverRPCs ?

viral locust
#

what exactly settings should I have here in order to connect from my laptop (as client) to my PC (as server)?

sharp axle
viral locust
#

I did 1 build where I added the server's IP at the "(optional)"
passed the files to my laptop
changed the setting on the server to be 0.0.0.0 on address while leaving override bind ip empty
didn't work

I did other build where I added the server's IP at the address
passed the files to my laptop
changed the setting on the server to be 0.0.0.0 on address while leaving override bind ip empty
ran again and nothing connected

#

to see if I get some progress

#

:X

#

man this has nothing to do with what I was doing

#

I thought adding network manager + unity transport and just adding buttons to start as client / server / host etc would be enough, but truth is I can't make the network to work

ripe yarrow
#

I made some code where OnNetworkSpawn i Instantiate buttons that Spawn Items and they work fine on the host player but when the client player joins the host player is no longer able to use there item spawn button?

#
//==== OnNetworkSpawn ====//
public override void OnNetworkSpawn()
{
    if (IsOwner)
    {
        SetupMyPlayerButtons();
    }
}

//==== Setup Player UI Buttons//
public void SetupMyPlayerButtons()
{
    Button buttonClone;
    
    for 
        (
            int i = 0;
            i < codePrefabs.Length;
            i++
        )
    {
       // Debugger.debug.Log(i);

        buttonClone = Instantiate(playerUiButton);

        buttonClone.transform.SetParent(buttonLocation);

        int iLocal = i;// this is why you need to do this https://unity.huh.how/programming/specifics/anonymous-methods-and-closures
        buttonClone.onClick.AddListener(() =>
        {
            SpawnCodePrefab(iLocal);
        });

        buttonClone.GetComponentInChildren<TMP_Text>().text = codePrefabs[i].name;
        buttonClone.name = codePrefabs[i].name; // name buttton after player
    }
}
ripe yarrow
#

I tried making it a ClientRpc and adding "Network Object" script to the "button UI" Prefab but nether of this things worked.

After some testing i found out that Weather or not the buttons are on or spawn the last person to spawn is the only one who can instantiate items and i can't figure out why

I can post a video if that helps

weak plinth
#

can anyone help me with this, when i shoot npc with host everyone gets good information on where he died and he dies there thats it, but when i shoot npc with client npc does a little teleport back,and proceeds to die there

#

the last shot describes it best

#

am i missing something?

gleaming zenith
#

what are some good numbers to use for the debug simulator for The Packet Delay MS Packet Jitter MS and Packet Drop Rate?

weak plinth
#

i am still stuck with teleporting issue does anyone know how to solve it ?

ripe yarrow
weak plinth
#

there is no character controller on that thing crawling

ripe yarrow
#

If there is no character controller
just move it with transform.position = newPosition;

shrewd junco
shrewd junco
#

You'll probably have to show more, like how you're moving the npc. The video really doesnt describe much because theres a billion reasons this could happen visually

ripe yarrow
shrewd junco
lyric thunder
#

just a few minutes ago this started happening. every photon "player" except mine is disabled when it spawns. what i mean by player is an object thats instantiated with photon with a photon view. i think its somethin to do with the photon view because the prefab itself is enabled

open phoenix
#

Im using coherence and I want to implement a trading system where players can trade items with each other. How can I come about this?

weak plinth
#

Is it possible to test game functionality with 2 different pcs without setting lobby and relay?

orchid mortar
#

I have a problem with Netcode for Entities: In a project that was recently developed using Netcode for Entities v0.51 I attempted to upgrade to v1.0 (currently v1.0.15 with Entities v1.0.14, but the same issue was also present with v1.0.12 and Entities v1.0.11). After fixing all the things that changed (Bakers instead of the previous conversion system etc.), I can create a Host and connect with a client, but the Prespawned Ghosts don't seem to work (i. e. they stay disabled i. e. they keep the Disabled tag). Neither the Prespawned Ghost that existed already in the "Lobby" scene, nor a newly created prespawned ghost (i. e. a new Prefab with GhostAuthoringComponent). (In previous version of Netcode for Entities, you had to reference all ghosts in the first loaded subscene or something like that, but even an adjustment like that didn't help.)
The purpose of this prespawned ghost is to keep track of where the players should be (Lobby, Scene A, Scene C, ...) so that the clients can start to load the right scene as soon as it's necessary. Admittedly, this is something that could be achieved in a different way, but later on, the scenes will contained Prespawned ghosts as part of the level design that are objects the players can interact with that also have synchronized values (think about the pickup boxes in Mario Kart for example).
In case it helps, the base for this project was the DOTS Tutorial by Moetsi, even though quite a few things changed in the meantime: https://dots-tutorial.moetsi.com

This is a sample project that demonstrates how to create a multiplayer AR experience using Unity's DOTS. We include full workflows, code, GIFs and also share links to external resources.

honest shoal
#

The code is meant to set a create a network object and set it as a child of the clients, but it only works on hosts, it spawns the object in fine for all clients but when it comes to making it a child the clients get an error of “only the server can reparent network objects” I’ve tried everything go get this working with rpcs to get the host to do this on clients behalf but all it does it make that client parented on the hosts side too(what I wanted but I also need it parented for the client) I’m completely out of ideas to fix this please help

#

It’s literally killing me, 3 days trying to fix it now and nowhere I look online I can find an answer that works anything I try makes it more broken than this ^

#

Using unity netcode, networking for game object

ionic mantle
#

Okay so if you cant tell from the video. The host is on the left, the client is on the right. The issue is that on the left the bullets are shooting fine and they are small and fast, on the right is the client whose bullets are bigger and slower then the client. Then the host can kill the client but the client cant kill the host. This used to work fine but I just changed the model of the bullet from a particle system to a actual gun model. They are both running the same version of the game. The first script that is shown in the video is the script that gets attached to the bullet when it gets spawned. The second script is the gun that shoots and spawns the bullet. The third script is on the player and it deals with the health. The network variable called health is the players health. So could anyone help me about why the bullets are different on the client from the host and why a host can kill a client but a client cant kill a host. I can send the actual code instead of it being in a video if needed. Any help appreciated!

spark copper
#

Hi guys, i have some general questions about how to handle multiplayer in complex scenarios and i am wondering if someone experienced could have a small chat with me on the subject. I would like to ask a simple question, unfortunately i wouldn't even really know what to ask. Basicly i wonder how to architecutre things in a scenario where i would want to have "Units" (base class for character) to control in an RTS fashion, but with a lot of different systems for the unit (direct movement control with wasd but also some pathfinding, inventory, "stats", interacting with the environement, being controlled by multiple players, moving sometimes in "local space" to an other object and sometimes in world space, abilities (like in a Moba), grouping of units to move them together, interaction with objects or the environement and so on). Basicly the game i try to make is about having multiple units on a pirate ship and be able to give them orders to control the ship. And i kind of struggle on how to architecture all this in a "convenient" way. For Solo it wouldn't be an issue, but it gets really messy in my mind when i need to integrate multiplayer. So if anyone experienced has a bit of time to discuss with me, feel free to slide into my dm 😅

chrome saffron
#

So I'm working on a multiplayer fps game but the audio is only being played locally so other players cant here sound effects i.e. shooting reloading etc. would anyone know how to fix this? any help would be appreciated.

ionic mantle
#

You could call a ServerRPC and tell the server to play the sound across the network

#

Just realized your using Photon

#

I am not sure then

severe pilot
#

Hey guys, can anyone point me in the direction of resources on how to get my game to work over the internet? Ik there's a unity solution and also steam transport, but I'd rather not do either of those. Am I able to use NAT punching instead?

shrewd junco
severe pilot
#

Ty

shrewd junco
#

the link just lists options also, doesnt go into how to actually do them

severe pilot
#

kk

#

Why can you not rely on jsut nat punching?

#

How does it actually work?

shrewd junco
severe pilot
#

right. As long as it works in the majority of cases then I'm satisfied. There's always port forwarding as a fall back but obviously ideally players won't have to do that

#

The plan is just to play my game with friends anyhow but it might be nice to publish if possible

shrewd junco
sharp axle
#

Nat punch through requires a server in any case. Might as well just use a Relay service in that case

sharp axle
thin timber
#

How do I send a message to a client from a c# server?

thin timber
#

How do I send a message to one specific client?

dark finch
#

Depends on the framework, but if you are doing raw TCP, you can just send a message to a specific IP?

halcyon flame
#

If using ngo

halcyon flame
#

I think you get the point

#

Your game seems heavily overscoped for your own abilities

#

Many of these problems are seeprste problems with very distinct solutions

#

Try and tackle them one by one instead of one big clump

#

Just start building :)

#

Although if you are planning moving a lot of entities together, maybe DOTS is the solution for you :)

thin timber
halcyon flame
#

Networking for gameobjects

#

Unity's own implementation for networking

thin timber
#

I’m not using ngo

thin timber
dark finch
# thin timber How? Can you send me the code?

We use it a lot for events, or museum work where I need something unity to send data to another thing.

Something akin to this should help:

https://gist.github.com/danielbierwirth/0636650b005834204cb19ef5ae6ccedb

Gist

TCP Client-Server Connection Example | Unity | C# | Bidirectional communication sample: Client can connect to server; Client can send and receive messages: Server accepts clients; Server reads clie...

agile loom
#

Hello .. had a question about running a coroutine on Servers and Hosts ... is this implementation in OnNetworkSpawn the right way to approach this?

`
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Unity.Netcode;

public class TurnTimerUI : NetworkBehaviour
{
private NetworkVariable<int> timerDisplayState = new NetworkVariable<int>();

private IEnumerator GameTimer;

public override void OnNetworkSpawn()
{
    if(IsClient)
        timerDisplayState.OnValueChanged += NetworkManager_TimerDisplayStateChanged;
    
     /*
     * If I want the below code to work in both hosting and server mode
     *  is this the correct way to do this?
     *  or will this cause issues?
     */
    if (!IsHost || !IsServer) return;
    
    GameTimer = TimeGameTurns();
    StartCoroutine(GameTimer);
    Debug.Log("OnNetworkSpawn  Server/Host section TurnTimerUI fired"); 
    
}

public override void OnNetworkDespawn()
{
    if(IsHost || IsServer)
        StopCoroutine(GameTimer);
    
    if(IsClient)
        timerDisplayState.OnValueChanged -= NetworkManager_TimerDisplayStateChanged;
}

private void NetworkManager_TimerDisplayStateChanged(int previousvalue, int newvalue)
{
    Debug.Log($"Network Manager sending Timer Display state changed value of : {newvalue}");
}


private IEnumerator TimeGameTurns()
{
    var waitForOneSecond = new WaitForSeconds(1);
    while (true)
    {

        yield return waitForOneSecond;
        timerDisplayState.Value = 1;
        Debug.Log($"TimeGameTurn value 1"); 
        yield return waitForOneSecond;
        timerDisplayState.Value = 2;
        Debug.Log($"TimeGameTurn value 2");
        
    }
}

}

`

sharp axle
# agile loom Hello .. had a question about running a coroutine on Servers and Hosts ... is th...

That should work fine. You only need a !IsServer check.
Personally, I would just send a clientRPC with the start time then run the timers locally. You can use this if really need the start time to be in sync
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networktime-ticks/#example-2-using-network-time-to-create-a-synced-event

agile loom
# sharp axle That should work fine. You only need a !IsServer check. Personally, I would jus...

Thanks for the reply.

Well .. when I do IsServer style check only - then a hosting player does **not **see the timer. So I need to cover both use cases -- wasnt sure if this if (!IsHost || !IsServer) return; check was the right way to cover both scenarios.

The reason I used a NetworkVariable is because this is a turn based game where everyone needs to be in sync - if a local player can override their turn (via hacking) because I told them to run their timer locally then this would be a major issue.

open phoenix
#

Is anyone familiar or experienced with coherence?

#

DM me if you are

#

Please

red olive
#

how questionable would it be to sync a BigInteger with server and clients?

sharp axle
vital thicket
#

hello, i have question, not really sure how is this called or where i should go for this system. im looking for something from networking for game, so base would be a "singleplayer" with option to call "friends" into your session, max 4-8 player sessions. things done in another session are counted as progress as well to people who joins. not really sure about how it would be hosted, something like automatic player host when starts playing and if someone joins session uses host base? where to look, what to look for this? any guidance will be helpful

gaunt kelp
#

need help with photon.
Im trying to run c PhotonNetwork.InstantiateRoomObject("flamethrower", playerPos, playerQuat);
the prefab "flamethrower" isnt in the Resources folder, how can i load it?

pulsar zenith
#

Hi I have been trying to make a multiplayer game using Netcode for gameobjects but I seem to be running into some problems when it comes to spawning the player in the beginning. It will spawn half the times in the designated coordinates and the other half times it will spawn at the prefab position. I have tried to see if anything is overriding the transform by disabling scripts but so far I cant seem to find a solution the only stack trace im getting in terms of error is this

sharp axle
sharp axle
vital thicket
# sharp axle If you mean like in elden ring, I believe it's something like silent matchmaking...

hmm, could be. i had aim basically on MMO system, but local, if this could be possible. so its not massive multiplayer system but smaller catch. specifically Tom Clancy Division. you have map which is "singleplayer" mode with session + few areas "safehouse" where are players visible to each other in that session, but not in group. if in group, then players are visible in "singleplayer" area

pulsar zenith
vital thicket
sharp axle
vital thicket
#

what about approach of creating "server" and allowing player to make it as LAN or upload to hosting for players to join? something like minecraft? thats client-server thing?

sharp axle
vital thicket
#

yep, something like that, guess i'll have to rework "content" to apply it from mmo to server. what should i look at specifically to research about that approach? so it would be singleplayer based with ability to join multiplayer games hosted on various host services via IP join?

#

and what should i use for it, best practice, photon/mirror/netcode/something else?

sharp axle
vital thicket
#

hmm, then i need to take a look at each one and find one that best suits to game i want to deploy?

sharp axle
#

pretty much. but you can always build features that are missing

vital thicket
#

yeah, indeed. wanted to check here first before diving into networking so i don't strain far from desired output. alright, thanks for some insight mate

woven cliff
#

I want to make a custom server for a unity mmo anyone know if a Blazor Server will work with unity at all?

nocturne vapor
#

You will find more resources on how to implement the udp protocol for mmos as well, since it is pretty much the standard

nocturne vapor
nocturne vapor
#

oh thanks, thats more straightforward than I thought

woven cliff
#

Also how would I even install it

#

Cus from what I know unity does not support nuget

nocturne vapor
nocturne vapor
#

I wouldn't recommend it tho

woven cliff
#

Well I wanna give it a show I'm not planning on making something huge just a place to mess around with friends and teat stuff

nocturne vapor
#

so not a mmo, but a game with like maybe 10 players?

woven cliff
#

Well closest to an MMO I can get but I don't even have a way for massive amounts of players anyways

nocturne vapor
#

otherwise you need to write your own udp server

woven cliff
#

Also aren't RPC just calling functions over we sockets?

#

*websockets

nocturne vapor
# woven cliff What's udp?

https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html
thats how you would do requests
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo/
this is ngo

the internet is basically divided into 2 different protocols udp and tcp
udp just sends your data and doesn't care what happens with it, this makes it fast
tcp sends your data and waits for an acknowledgement, if that didn't arrive, continue sending it, this makes it slow but secure

if you now think about the normal gamedata you want to handle, it usually involves position syncronisation and so on, were this kind of safety isn't required.
Thats why in gamedev you mostly use udp
And in a scenario with lots of players (like a mmo) you would want the fast option

blazor on the other hand is based on http and http is based on tcp
websockets are tcp as well btw

https://media.geeksforgeeks.org/wp-content/uploads/20230406112559/TCP-3.png

Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).

woven cliff
#

Well any recommendations for making my own UDP server?

#

I don't want to use NGO I heard it's not good for bigger amounts of players

#

And I also wanna build the server myself mostly and learn more about networking in the procces

nocturne vapor
#

which language do you want, c#? c/c++?

#

also chatgpt can help a lot with the concepts, since they are pretty much established, wouldn't trust it with code tho

woven cliff
#

c#

woven cliff
#

I don't want to use chatgpt I don't like the way it was trained but I will read the links you send me when j get to work today

nocturne vapor
#

just a quick heads up this will be alot of work, since you would develop your own protocol on top of udp
so this is just worth it if you really want to create a mmo with hundreds of players or as an educational project

woven cliff
#

Yes I realize that

drowsy lava
#

how can i randomize a players hair color on spawn and sync it?

sharp axle
sharp axle
#

The same as with anything else. Start by reading the docs and going through the tutorials

weak plinth
cloud tapir
#

I have a Photon PUN 2 Free project. The problem I'm facing involves creating and joining rooms across different regions. For instance, when I make a room in my master region and a friend tries to join from a different master region (like CAE, TR, US, USW, EU, IN, JP), the room doesn't show up for them. To give you an example, if my master region is set to "TR" and my friend tries to join from the "USW" region, they can't see the room they're trying to join. My project development largely followed the guidance from Redbug Redfern's tutorial series titled "Multiplayer FPS in Unity."

spring crane
# cloud tapir I have a Photon PUN 2 Free project. The problem I'm facing involves creating and...

Seems to be by design

Verify that clients are connected to the same Region. Only players connected to same region can play with each other no matter what device or platform they're using. Make sure to read about "best region considerations" if you use "Best Region".
https://doc.photonengine.com/pun/current/lobby-and-matchmaking/matchmaking-and-lobby
Which makes sense considering how poor the experience would generally become in most PUN projects.

solemn haven
#

Hey, so I am sending UnityWebRequest in coroutine but it takes 3 seconds to arrive. and while that time Unity is PAUSED, animation, everything, editor is not responding. why is this the case? I think somehow it blocks MainThread from execution but how can I fix that?

#

I tried async/await instead of that but nothing changed

gaunt estuary
#

Hello. I have a "design" question. So I have a player Object which is the same for all players and does mostly the same allways. That would be my player prefab. I have however different characters and different skins for each character. Should I create a prefab for each skin or at least for each different character, since they do have sifferent scripts even if they share most of them? Or should I have the one player prefab and then add the specific character scripts and skin on it once the scene loads?

shrewd junco
gaunt estuary
#

Y no I'm going to go with different prefabs for characters and prefab variants for skins. The skins are almost the same but each skin has an override of the base animator controller

weak plinth
#

does anyone know what could cause Client network transform to not sync rotation?

fair notch
#

NetworkServer.Spawn only spawns in host. How to fix

solemn haven
#

you can see at animator, how it freezes unity. O_o how to fix please?

noble crown
#

Is there an easy way to send byreference objects via RPC? Like for example is there an ID associated with every gameobject?

noble crown
#

I have found gameObject.GetInstanceId() I think I will use this one. Does someone know if this is the same for all clients and the server?

nocturne vapor
nocturne vapor
noble crown
#

Aaah okay I will look into that thank you

nocturne vapor
#

what do you want to achieve?

noble crown
#
int i = 0;
            foreach (PlayerController player in alivePlayers)
            {
                ClientRpcParams clientRpcParams = new ClientRpcParams
                {
                    Send = new ClientRpcSendParams
                    {
                        TargetClientIds = new[] {player.playerIDNumber.Value}
                    }
                };
                player.AssignBedClientRpc(beds[i].GetComponent<BedController>(), clientRpcParams);
                i++;
            }
[ClientRpc]
    public void AssignBedClientRpc(BedController bedController, ClientRpcParams clientRpcParams = default)
    {
        if (!IsOwner) return;
        
        _assignedBed = bedController;
        this.transform.position = bedController.transform.position;
    }
nocturne vapor
#

you sure this works?
I would probably create a BedManager which manages an array of a struct consisting of a playerid and a bedid and just return whatever I want with the input of the id
and beds would need to register with the BedManager

#

and ids are easily sendable

noble crown
#

That is indeed a very good idea!

#

I will look into it

#

Thank you very much!

solemn haven
nocturne vapor
solemn haven
#

I used it

#

HTTPClient.

#

still the same

#

Have no idea why web request should block main thread

midnight sonnet
#

iOS build crashes every time I call NetworkManager.Singleton.StartHost();

i'm using Unity 2023.1.7f1 and NGO 1.5.2

#

same goes for StartClient();

midnight sonnet
#

i switched to mirror i hope it gets fixed

ember remnant
#

Hey guys, I've been looking into the networking bit lately and I kinda want some advice.
I know there are some Unity default services (Multiplay, with Lobby and Matchmaking), but there are some other awsome packages (Mirror, Photon, Fish-net) that look promising too.

This will be for an MMO, and I am not here for an advise to not make it awkwardsweat , I am here for some advise on which package to use for the RPC. I am not expecting too much traffic, but I guess roughly 100 CCU will be the max per server (there will be multiple worlds each on an own server). We do have infrastructure and people to do the server hosting, scaling and maintenance ourselfs. Oh and we won't be using atavism or similar packages.

Any advise other than not making would be appriciated 🙂

nocturne vapor
#

I would probably suggest mirror, seems like it could handle this
Ngo ist mostly used for smaller scale multiplayer and I do not know the other solutions too well to suggest them

woven cliff
#

I want to make a custom multiplayer server for a game any recoomendations on how i shud handle stuff like movmewnt verification? shud i build it on a branch of the game inside of unity so i can use stuff like raycasts and stuff and check if a player didnt for example go thru a wall

#

or shud I make the server outside of unity and do it somehow else?

sharp axle
verbal yarrow
#

Hey, I have a Unity Project with UNET and Facepunch for my open world game. Since the OpenWorld is really large it takes time to load. How do I add a working LoadingScreen to the SceneLoading? I've been googling around, but can't seem to find a solution that works with UNET.

verbal yarrow
#

And I have this error and I don't know how to fix it:

sharp axle
verbal yarrow
upbeat pine
#

How would I be able to connect to connect to a game I made with fishnet from a different device using hamachi?

cosmic fossil
#

Heyy
I want to create simple game based mechanics on pawns and I want to make it multiplayer (one player is hosting and player, others are just playing up to 4 players)
What multiplayer system would you recommend to use for such a small game?
I mean this NetCode for GameObject or something else?
I hope you understand! haha

vale tree
#

Hey, I have a NetworkList in each players script. I'm trying to remove each object in the list with certains conditions, with a foreach loop. I'm doing that on a serverRpc(RequireOwnership = false), so only the server's removing items. However, i'm getting this error, which i put it on image, and the line on the method who called this error, is the line of the foreach (I can give some screens from the code if you need it), i really don't know how to fix that

bleak rover
#

this is not working as expected, how should i change it (photon fusion)

verbal yarrow
#

How to Load a scene Async with Netcode?

#

Like for it not to hang/crash/lag and to put my loadingscreen in there

nocturne vapor
#

Thats a good question, I just have my loading screen in my player ui, not the best solution but works for now

gleaming zenith
#

I have a pick up system which I want to make client authoritative but the item that is being picked up can only be assigned to one player how can i make it so if two players try to grab it at the same time it only assigns it to one player?

high night
#

@gleaming zenith Something like that would probably require rollback

#

Maybe you could have the pickup system server authority, and have what happens after client authority?

#

There could be an rpc to have player equip the item.
So when an item is picked up in server, server would run an rpc to make the player equip it

gleaming zenith
high night
#

theres also netcode for gameobjects, i dont know if supports rollbacks like that

#

i think photon fusion supports rollbacks

#

and then there is the photon quantum which is pricey

gleaming zenith
high night
#

having data decoupled makes replication easy

#

but i dont know about netcode for gameobjects

#

what im doing is entities and netcode

#

and i have gameobject views

#

i have systems that makes visual purpose gameobjects follow entities

#

thats how i plan to do stuff that cant be done with entities

#

but as i say, i never checked netcode for gameobjects

gleaming zenith
shrewd junco
gaunt estuary
#

I'm basically pretting my inspectoir for easier and faster use (I mean i would have to set up about 1236789126386183 objects to make the faster part pay off, but it's nicer xd). Anyway, for some reason, outside all this sometimes networkVariables are shown as a dropdown with currentvalue in them, but when click on another object and back again they appear as normal.

What happens is that when I put them in the inspector manually with an editor script they allways appear in this dropdown form

#

Any chance someone knows how to implement them in the correct way? I'm using: `

            EditorGUILayout.PropertyField(channelTime);
            EditorGUILayout.PropertyField(isChanneling);

To show them

vale tree
#

that's kinda weird, but it's working pretty well

ionic mantle
#

I have spent the entire day tryna figure this out and I need some help and if you want I can PayPal you or whatever you a few dollars if you can help me out. I can send you a few my scripts for shooting but I just cannot figure out how to do this.

Script for shooting the gun: https://pastebin.com/8ZpHhmaP

Script that get spawned on every bullet that gets spawned:
https://pastebin.com/nYaFudTy

Script that deals with player health and hopefully kills:
https://pastebin.com/Hzs0DMCg

So you can take a look through my code. I just commented it so it should be fairly easy to understand my messy code but on the KillHealthManager script I want to make it so it detects who shot them. On line 49 is where I detect if the player got hit and what I want you to do is try to make it so it also tells who hit the player and then tell that player who hit them to increase their kill count variable by one if this makes sense. I provided the scripts I am using for shooting the gun, and the script that is on the bullet if you want to take a look at those. Thank you so much if you can help me and if not that is totally okay!

nocturne vapor
nocturne vapor
#

and I would put an IsServer in the OnTrigger enter, just to make sure it only gets executed on the server, so you life won't be too much pain when trying to sync

#

that's probably the easyist thing you can do

ionic mantle
nocturne vapor
#
using Unity;

public class BulletData : MonoBehaviour {
    private ulong id;
    public void setId(ulong id) {this.id = id;}
    public ulong getId() {return id;}
}

player shoot on the server

//bullet is the object you are initiating
//id is whatever id you want to use, clientID, steamID, some custom thing
bullet.GetComponent<BulletData>().setId(id);

on trigger enter

//bullet is the object you are initiating
//id is whatever id you want to use, clientID, steamID, some custom thing
ulong id = bullet.GetComponent<BulletData>().getId();
//send that id to the gameManager
ionic mantle
ionic mantle
noble crown
#

Hey! I have a question regarding ServerRpc. When a player spawns into the world, he sends a message to the GameManager that he spawned in. The GameManager then in their turn adds him to the aliveplayers list and checks if all people have loaded in. For some reason, the GameManager's ServerRpc's method is just completely ignored when called. Can someone help me solve this bug? I have been staring at it the entire day already.

PlayerController.cs (dynamically spawned):

public class PlayerController : NetworkBehaviour
{
    // ...

    private void Start()
    {
        if (!IsOwner) return;

        this.steamID = User.Client.Id.SteamId;
        this.playerName = User.Client.Id.Name;
        this.gameObject.name = "Player " + this.playerName;

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        

        // After player is initialized, tell the game manager he is ready
        GameManager.instance.PlayerInitializedServerRpc(); // <== This method is just completely ignored
    }

    // ...
}

GameManager.cs (already in-scene):

public class GameManager : NetworkBehaviour
{
    public static GameManager instance;

    private List<PlayerController> alivePlayers = new();

    // ...

    private void Awake()
    {
        instance = this;
    }

    [ServerRpc(RequireOwnership = false)]
    public void PlayerInitializedServerRpc(ServerRpcParams serverRpcParams = default) // <== This method is not called at all because the text "Initializing player" is not logged on server-side
    {
        Debug.Log("Initializing player");
        PlayerController playerController = this.GetPlayerControllerFromPlayerID(serverRpcParams.Receive.SenderClientId);

        if (playerController == null)
        {
            Debug.LogError("PlayerController not found");
            return;
        }
        
        playerController.playerIDNumber.Value = serverRpcParams.Receive.SenderClientId;
        this.alivePlayers.Add(playerController);
        Debug.Log($"New player added with ID {playerController.playerIDNumber.Value} ({this.alivePlayers.Count} / {NetworkManager.Singleton.ConnectedClientsList.Count})");
        
        // Test if all players are properly connected
        if (this.alivePlayers.Count == NetworkManager.Singleton.ConnectedClientsList.Count)
        {
            // Start the game
        }
    }

    // ...
}

The class is tested and working normally and both objects have NetworkObjects in them. I have a feeling that there is a problem with ownership but I set it to false which was supposed to be a solution. Also I am aware of the order of how awake, start and onnetworkspawn work. I just find it really really weird that the method is just completely ignored without any errors.

nocturne vapor
ruby solstice
#

We've been using Netcode in our project for a week. Now all of a sudden, VS says we don't have it. But I can see it in the packages folder in unity. I've uninstalled, reintsalled. I've tried all sorts of tricks inside VS to get it to see it, but nothing is working.

Edit: It was an assembly. And I needed to add references to it. Solved!

nocturne vapor
fierce vault
#

Can dots networking create open world games?

noble crown
#

I have one last question and then I am completely done with networking for a while, I am sorry for the amount of questions I am sending the past couple of days.

I recieve this in my PlayerController. Everything works as it should, but the transform position is not executed. The log displays the right position. The client is authoritive (ClientNetworkTransform) so the transform's position should be set properly, but for some reason it is not moved at all. Why is this?

[ClientRpc]
    public void AssignBedClientRpc(float x, float y, float z, ClientRpcParams clientRpcParams = default)
    {
        if (!IsOwner) return;

        Debug.Log(new Vector3(x, y, z));
        this.transform.position = new Vector3(x, y, z);
    }
shrewd junco
ruby solstice
noble crown
sharp axle
noble crown
sharp axle
noble crown
#

The debug.log in front of the line is working, so it is called correctly. But still for some reason the transform isn't moving.

toxic sluice
#

My googling has been weak, does someone have some good leads about to keep the state of a grid for a city builder game synchronized across multiple players?
I understand how I'd set it up with RPCs to let clients & server know what has changed on the grid, but how would I be able to sync that to a late joining player?
Do I have to simplify my grid's elements down into specific int-enums so I can have it set up as a network variable?

spring crane
toxic sluice
spring crane
#

I wouldn't necessarily use network variables for something that only needs to be sent once

toxic sluice
spring crane
#

If the grid isn't something the client can figure out (known map layout, deterministic generation), it needs to be sent by some means

toxic sluice
#

Right, so would this be something you'd set up wholy in a single network variable?

shrewd junco
#

Network variables/lists do sync for newly joining clients

toxic sluice
#

Or the server's grid class object know it's state, and sends RPCs to clients to replicatethe state

#

Are you custom serializing the list, or is the list supported by default?
Would it be a NetworkVariable<List<CustomStruct>> grid?

spring crane
#

I tend to gravitate towards sending an RPC for stuff like this

shrewd junco
toxic sluice
#

Ooooo okay, I missed that NetworkList is it's own class.
That's part of my concern, The grid can get kind of big.
My game is way smaller than factorio obviously (nor as optimized), but how would a grid of that node size be synchrnoized?

#

Like there maybe hundreds of thousands of nodes at the late late game, each one isn't getting updated. Does the networklist support that large of lists? Let me search up on this NetworkList more before I ask basic questions

shrewd junco
toxic sluice
#

That's fair, It's not factorio esque size, but it is a similar 2d top down grid, with similar multi-node structures, and smaller node sizes

sharp axle
#

I would break the city up into chunks. Each chunk can have its own network list.

nocturne vapor
#

Since I'm doing procedural world generationt and wanted to do it with network lists, don't
It doesn't work and I only had arround 40.000 nodes not hundreds of thousands.

It is probably best to do as much as possible (off the grid visualisation, like generating it from data) on the client side and only syncinc the fields that actually got changed

sharp axle
#

You should be able to get your node data into a struct

nocturne vapor
#

Chunks would work too, if you ain't making them too big

toxic sluice
#

most of the grid's info is enums anyway, for node state, and node terrain states. 100k nodes in a list, with a custom struct of enum-ints? I just genuinely don't know if that's reasonable or not

nocturne vapor
#

I just used a large network list of floats (since I only needed to sync the z position of each vertex) and it didn't work.
It was too much to sync and breaking them into little arrays and syncing that step by step with a best case latency of 16ms, so rtt 32ms not factoring in computation, it was too much
I just send the seed and generate on teh client and the server

sharp axle
#

I don't know how far along you are but you might also want to look into Dots and Entities.

#

Yea no way mesh data is not meant to be used that way

nocturne vapor
#

Well we all made stupid mistakes, I really wanted to make that part server authoritive it just refused to work, for obvious reasons

toxic sluice
#

Dang, okay if just floats was too much, the struct will probs be alot too.
I was looking at dots, but I just keep increasing the scope of tech i'm adding I guess.

I'm trying to rebuild the map generator, plus MP, adding dots would be another big learning step.
I'm trying to think, would it be a networklist of Vector 2 ints + prefabIDs of structures. just divide all the major components into individual small lists?

#

me actively making stupid mistakes 😎

#

If anyone has any bookmarked article or good post with some relevant info i'd love it. I'm running through the documentation, but I just need more context I guess

nocturne vapor
#

I'm not enterily sure on your game idea (I have never played factorio)
But I'm guessing all the cells start in a base state you could generate first and only syncing new data when a cell switches its state. This approach would be computationally lightweight, minimalize network traffic, but would be a pain to implement properly with world saving

toxic sluice
#

(The documentation is baiting me to make my own custom network variable, with nested lists, it's baiting me)

sharp axle
#

I guess it really depends on the scale of your nodes.

#

And like how many nodes does the player reasonably need to see updated at any given time.

#

You can get clever and update nodes farther away from the player less frequently or not at all.

toxic sluice
#

It's tough to visualize cause this is the current, old map generator.
but right now it's a 5x5, where a structure takes 1 whole node. I want to basically cut the current nodes to be 3x3 in each node. (aka 3x3 mini nodes per node, if that makes sense)

#

so that's my thought, the nodes only change when a new structure is built

#

it won't happen every frame or anywhere near that

#

BUT the list will get big, I'm using a dictionary to hold the grid right now

#

and i'm using only relative positioning, so only adjacent nodes get called usually.
I can set up RPCs to set out updates on structure/building changes, but idk where the whole grid goes?

sharp axle
#

Nothing wrong with storing the grid locally in a dictionary and just updating via RPCs

toxic sluice
#

Would I have to have a system to catch a late joining player up with a bunch of RPCs?
The map generator is seeded, so terrain & water will be deterministic, but the roads are decided by the map generator, it should always output the same result for the roads, but if only the server has to do the math, and just tell player's the pathfinder's results. That seems optimal.

sharp axle
toxic sluice
#

Hmmm, tangentially have you check out object visibility as it relates to networking?
Can I have a per frame spherecast (or similar distance check) to check which enemy vehicles it needs to be updating?

#

I'm trying to figure out how to do enemies in MP with a mix of local and network objects, because I think networking the cannon fodder is wasteful right, but if I check visability on them. Would that be an easy way to limit network traffic a bit to each client?

drifting plaza
#

The issue i'm having right now is maintaining synchronization with my server authoratitive, client prediction code. The only reason I'm using this approach is to keep the server authoratitve and avoid cheating. Theoretically, could I use some math or whatever to calculate whether or not the result of the input on the client is within an acceptable (non cheating range) on the server whilst using client network transforms to actually update positioning? (essentially client authorative movement where they send their positions to the server). Thus, I could check each tick's movement to ensure no cheating while not having to worry about gradual error build up over time?

toxic sluice
sharp axle
sharp axle
toxic sluice
#

pog ty ty for the help

sharp axle
drifting plaza
nova oak
#

Hi im tying to use NetworkVariable<NetworkBehaviourReference> to synchronize a reference to another NetworkBehavior, however it seems that i cant set the value to null. whats the best way to work around this? i have found that i can use new NetworkBehaviourReference() as value to represent null. is there any problem with this? are there better ways?

sharp axle
median gale
#

Hello,
I've been making a android game in Unity 2021.3.16f1 and using PUN2. I have been creating and joining rooms for the past 2 months.
However, all of sudden, I can't join rooms anymore but I can still create rooms
I am using the free plan.
Do this have to do with the "60GB traffic per month"? If so, where do I check if I hit that traffic? Or could this be something else? I don't think it is a code issue since I've joining rooms the past 2 months.

bitter bough
supple lodge
#

Hi, im trying to make a gun in ngo, but when i run this funtion (makes raycast and spawns hiteffect) it only works for the host.

    {
       RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(cameraShootPoint.transform.position, cameraShootPoint.transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
        {
            Debug.DrawRay(cameraShootPoint.transform.position, cameraShootPoint.transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Did Hit");
            GameObject go = Instantiate(hiteffect, hit.point, Quaternion.LookRotation(hit.normal));
            go.GetComponent<NetworkObject>().Spawn();
        }
        else
        {
            Debug.DrawRay(cameraShootPoint.transform.position, cameraShootPoint.transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("Did not Hit");
        }
    } ```
nova oak
#

well do you use rpcs to execute it on clients?

maiden cosmos
#

I'm reviving a project from 2017 and upgrading to 2022 LTS and migrating to the netcode framework.

I have an init function on my server state which is inheriting from NetworkBehavior

IEnumerator InitBattle()
{
    //...
    OnPregameStartClientRpc(new ClientRpcParams());
}

and I have on my client another class inheriting from NetworkBehavior

[ClientRpc]
void OnPregameStartClientRpc(ClientRpcParams rpcParam)
{
    // do something
}

But I get an error that OnPregameStartClientRpc 'does not exist in the current context'

This makes me think it can't find the reference for this function, but I'm unclear how the script compiler links the definition and usage together, and the documentation is unclear beyond adding the attribute and the correct naming scheme.

woven cliff
#

I need to add signalR to services in the builder and map hubs how do i do that in unity usully i do that in the program.cs file

#

i need these 2 lines one before the app is build the second after it is build

builder.Services.AddSignalR();
app.MapHub<HubName>("Name");
crisp panther
#

Hello, may i ask is there a way to build an exe application to post an api call to let an unity to get the json request?

#

i wanna build a web domain to post some request to unity

woven cliff
winter mural
#

What do I need for simple custom collider & raycast system? (This is for learning purposes and not having to call physics.synctransforms)

I currently have figured out I need AABB ray check, also OBB which transforms the box to AABB. I will initally just use box colliders for sake of simplicity.

What acceleration structure should I use? BVH sounds pretty good for this use case?
[8:42 AM]
Also since the rays need to collide with world I think

  1. my collider system needs to hit the world too
  2. or fire 2 rays, one in unity on world layer which doesnt use synctransforms and other on my custom raycaster and see which hit point was closer to original (edited)
gaunt estuary
#

Hello!

I'm having some questions around unity gaming services and overall online game design. I'm aware this is not the discord for gaming-services, but I thought that your input could be of great value since I'm not asking for implementation details.

First of all I'm going to say that I've not yet decided on the gaming services I'll eventually use, it might be unity, azure, aws... But for simplicity I'm going to present my questions as if I was set on working with Unity Gaming Services.


So I'm working on a MOBA game, for simplicity you can imagine league of legends or dota, but I do aim the game a lil different.
Should I create a different build / app for each map/game mode, since when you spin up a server from the match maker it needs to be set up with the required gameplay and map? This might sound weird and my current view is basically no, the server build should have all the game modes within it and just apply the game mode / map with internal logic.

The second is whether I can use a 2nd app as a client, similar to how league works, which I've seen is not a popular option, but I do have my reasons.
There's 2 ways to go about this.

#

Creating a whole game "client" for the game inside the same unity app, making use of the gaming services Economy and Cloud-save.

Creating a 2nd app. Having my own application to handle all this would allow me to have complete control about it, plus separating all the "client" logic from the actual gameplay might be an advantage since if there are these 2 different apps and systems one could never break the other.

One of the reasons why I'm looking at this separate client logic is so that I can use ReactNative to create a desktop app, since I'm both a game and web developer. By creating my own app I would have my own database for players, my own e-commerce implementation for transactions...

Separating the game app from the client app would also make the server built super light since it would not have to handle all the client logic and would only be gameplay related.

With all that said, having the knowledge that I could use, for example the matchmaker or lobby API's (or implement my own, depending on the amount of work I wana do xd), how could I connect both applications as in booting up the game when a match and server are ready while sending the necessary data to the game app like server Ip, user- authentication and all of that good stuff.

It's a lot to read, I'd appreciate any pointers or some Pros and Cons if you have them (Or telling me NO!, just integrate the client into the game app!) Whatever input is appreciated!

median gale
latent valve
#

Guys my friend cannot join my game even after i port forward and lower my firewall. I gave him my ip and i hosted the game yet he still cant join using unity transport as a client.

nocturne vapor
latent valve
#

the address was correct before

gaunt estuary
#

If i'm not wrong, even if you port forward your router, you have to open the port in your firewall.

regal delta
#

he turned off his firewall

#

check to see if your pc is truly listening on that port with netstat -na | find "YourPortNumber"

#

if you see the entry (and assuming 7777 is only used by your app) then it should be running

#

some ISP's will double NAT your router. You might be able to tell if they double NATTed by checking your router's DHCP address. If it's a private address then they def double natted you, and you'll have to call/email your ISP to open that port and forward it to your router

#

you can also run a port checker on your own public IP https://portchecker.co/ to verify that you see that public open port

#

Something I've been worried about is with the prevalence & accessibility of game dev is how many kids will inadvertently leave themselves wide open to an external attack. Be careful. If possible route everything through an open source--up to date--VPN solution first.

old mural
stark saffron
#

Should client prediction with rigidbody physics even work? Almost every tutorial does that in pseudo networking conditions, but essentially simulation runs on the same scene, but with Unity Networking for Gameobjects I have to reconsile. A lot. Well, player 2 moves kinda okay, I mean, it's the best I've got so far, but I think this movement can't be even smoothed properly because it basically reconsiles every frame, as if it is not determined.

#

My question is - is this normal? I'm kinda new to networking. I can't find any bugs and can't think of a way two separate unity processes with different simulations and 50 ms delay could move a character at the same exact time, every time... Or maybe I did something wrong.

gaunt estuary
#

Just put a network transfrom no?

#

EVIL IS HERE

stark saffron
sharp axle
gaunt estuary
#

xd

stark saffron
#

Well, yeah, I use Network transform for projectiles and stuff, but I didn't know that you actually will recieve that much mini rollback

#

Well I guess I just have to smooth the movement

#

Thanks

mystic coral
#

Hi guys, is there any way to sync transform of an object in unity with 3js. I was thinking about photon real-time but it doesn't have a very good documentation for javascript. Is there any other library which can let me do cross-environment synchronization?

nocturne vapor
nocturne vapor
#

Oh 3js is another engine/editor
Nvm then

#

The easiest solution would be to look into websockets or creating your own api
The problem with that it would be based on http (so tcp), you wound just have to try out if this is fast enough for you
Js doesn't seem to support udp, so there is no real way arround it

mystic coral
#

Ohh ok, I'll take a look at websockets.

mint sundial
#

hello im trying to do vehicle drive system in mirror networking but im taking same error for 3 days, as i understand i need to assign client authority of vehicle to player and im doing it. but I get the error in the image. if you have idea please share it, thanks.

dark valley
#

Hello everyone,

I am creating a new project and I wanted to try Networking for Gameobject, but after some test and reading the doc, I am not sure of one thing; how to write any messages bigger than 1 packet or bigger than 1400 bytes?

For the context, when I start as a host, I try to share with a network variable a class with one big string in it, but each time this string becomes too big, I get this error in my NetworkSerialize method:

OverflowException: Writing past the end of the buffer

So, I read that the problem was that I need to create my own transport pipeline to be able to set a FragmentationPipelineStage, but I don't understand how I connect it to the Networking for Gameobject.

So I am on the good track or I am missing something simpler? Thank you for your time.

ionic mantle
#

Hey everyone. Im looking into hosting a proper game server for my game (I plan on porting a version of it to WebGL so I cant make the player do all the networking) but I am curious to know what in your experience the best provider is. I am looking at The Unity Game Server Hosting but it seems kind of expensive. 75 cents a day for just 1 cpu core and thats not including anything else is a lot. I am looking at AWS EC2 and it looks promising but I want to know what the cheapest solution for game services that are still fast enough to run a very small scale game comfortably.

prisma wolf
#

I spent some days trying to understand how to configure Unity Transport's adress, but I simply don't know what should I do with it to connect to other devices. Can anyone help me?

ionic mantle
prisma wolf
#

Anyways I'll keep researching about it, thank you

ionic mantle
#

You shouldn't need to do anything with the ip

#

I made a online fps game with lobby and relay without even touching anything to do with IP's or port forwarding

#

You will need to use Relay if you want to connect devices from a different IP

nova linden
#

I had this system that worked perfectly fine, then i changed the vrTarget(its a Transform) to a NetworkVariable and now i always get this error in this line and i have no clue why

ionic mantle
#

Are you sure your able to use transforms in a network variable? I thought it has to be a vector3

prisma wolf
nova linden
ionic mantle
mint sundial
#

how can i solve this error?

nocturne vapor
nova linden
ionic mantle
nocturne vapor
#

Everything else can be derived from that on the go and is unnecessary information to send

#

Qauternions and Vector3s can be send without any trouble

#

Even in a network var

nova linden
nocturne vapor
#

transform.position = posVar;

nova linden
#

but thats a fixed point in world space but i need the target to be for example a pos on the gun that is able to move freely so i cant do it without the transform

nocturne vapor
#

Than try converting it to an ulong and back

nova linden
nocturne vapor
nova linden
nocturne vapor
#

But I'k guessing this won't work, because you don't have the dame objects on each client

#
nova linden
#

doesnt work

nocturne vapor
nova linden
#

i have no clue

nocturne vapor
#

What does the error say?

bleak rover
#

Hey, Im trying to jump my character in photon fusion with new input system as docs says. but buttons are not working. why could that be?

spring pilot
#

Hello all. Would anyone have a second opinion on trying to implement VoIP? Ive been looking at Photon, and the main things I would would be looking for are:

a) audio volume is relative to distance between players.

b) is completely compatible with Unitys standard Network workflow.

c) Is somewhat barebones and simple to implement.

Photon looks like it fits my needs but if anyone has any caveats they would know of with it, in particular if it is compatible with parallel sync, or even any other SDKs entirely to recommend I would very much so appreciate it.

wet gale
#

Can anyone here who uses photon pun2 public sever for testing tell me how much ping they were getting? I am in one of the server countries and I am getting like 200ms, is it always this bad in public and gets better when you buy premium or what?

#

Also if anyone answers, please tag so I can see it later

stiff ridge
silk sparrow
#

Hlooo anyone know how to setup photon in unity

nocturne vapor
silk sparrow
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

public class MultiplayerManager : MonoBehaviourPunCallbacks
{
private void Start()
{
// Connect to the Photon server
PhotonNetwork.ConnectUsingSettings();
}

public override void OnConnectedToMaster()
{
    Debug.Log("Connected to Photon Master Server");
    // Join a random room
    PhotonNetwork.JoinRandomRoom();
}

public override void OnJoinRandomFailed(short returnCode, string message)
{
    Debug.Log("Failed to join a random room. Creating a new room...");
    // Create a new room if joining a random room fails
    PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = 4 });
}

public override void OnJoinedRoom()
{
    Debug.Log("Joined a room!");
    // Instantiate player prefab
    PhotonNetwork.Instantiate("PlayerPrefab", Vector3.zero, Quaternion.identity);
}

}
If I use this script in my game will multiplayer work

nocturne vapor
#

That is good, right?

white ledge
#

Is Netcode good if you are creating a large scale game like 1000+?
Or we should look for other networking solution?
If so than which one is better?

nocturne vapor
vale tree
#

Hey, is there a way to make a networklist writtable by clients ?

#

Because I have a networklist, which has all playerdatas, which is shared from host to clients, but when the clients disconnects, i wanna clear the network list in case of the client wanna create a game, but it tells me taht client is not allowed to write

nocturne vapor
vale tree
#

It is on yeah and it is on owner but it doesnt work xD

wet gale
signal bluff
#

yo how do I send my cod ehere

#

my client and my host are unsynced or like have differnt movement

mint sundial
#

please help about this error

nova linden
#

How would i go about implementing scene switching with multiplayer

stiff ridge
crude stirrup
#

Hey, I have this code snippet, it's in a NetworkBehaviour class.
This snippet is part of a PlayerController script i put on my player prefab

But for some reason, the SpawnObject is called everytime a client joins.
How is this possible? How is every client also a host?

was spawned should also be true one the host has spawned it, doesn't it?

mint sundial
#

how can i remove authority of object in mirror please help me

mint sundial
vale tree
#

Hey, i got a big problem with NetworkList. I have a gameObject which is on DDOL, and NetworkBehaviour. This gameobject contains a NetworkList of playerDatas, only writtable by server but readable by everyone.

When a host is hosting a game, and the client joins, everything works perfectly. However, when the host is going back to the main menu, and the client too, and after that, the client hosts a game and the previous host is now the client, in the host side, the NetworkList is fine, but on the client, the informations in the NetworkList are the same as when the client was a host before

Also, when the previous host is becoming a client (NetworkManager.Singleton.StartClient()), the networklsit on his side is empty.
I really dont know why, but... anyway, i hope someone could help me fixing that

I dont really know if i explained this really good bc i'm french and it's kinda hard to explain a situation like this, so if you have questions i'm here for answer

void steeple
#

Hi, I'm trying to make a script that gives every player that joins a netcode server a random colour to their meshrenderer. The code I have created works on the client it's created on, but the other clients see the default colour. I also don't know how to get the player that most recently joined. Is there a better way to do this?

Code: https://pastebin.com/mngAs7EG

Help is greatly appreciated! Please ping replies

nocturne vapor
indigo sage
#

Hello there, I was seeking answers on ChatGPT about data transmission protocols, and it suggested the possibility of a hybrid approach for a multiplayer game, where the client maintains both a UDP and a TCP connection to the server, then, based on the nature of the data, you decide which socket to use.

Do you think that this is a valid approach? Could it impact latency, even if I'm currently using only one of those connections but still have both open?

For example, using UDP for real-time player movement, and TCP for a "dice roll" that will define whether an action is performed or not.

What are your thoughts on this?

empty night
#

I have sprites as the player and can get them in the same game but they can't see each other

stiff ridge
#

There are plenty of protocols using UDP for reliability on demand.

nocturne vapor
#

yea, you are usually writing your own protocol based on udp or use an allready existing one

indigo sage
#

Awesome information, thank you both

modest mantle
#

Hey. Can I assume if I change two network variables in the same class in single frame on the server, I'll receive them in the same frame on clinets? If not, how can I keep data consistency in that way? Don't want to use INetworkSerializable everywhere.

sharp axle
nocturne vapor
sharp axle
# nocturne vapor does the unity transport protocol buffer that kind of information, so we can ass...

RPCs and Network Variables are sent reliably. There are several Pipelines that UTP can use. I haven't dug too deep into them.
https://docs-multiplayer.unity3d.com/transport/current/pipelines/#the-reliable-pipeline-stage

Pipelines are a core functionality of Unity Transport that allows selectively adding layers of functionality on top of the standard unreliable datagrams that UTP provides by default.

nocturne vapor
delicate torrent
#

Hi, I'd like to migrate from Photon PUN 2 to Unity Netcode for GameObjects. Does anyone have some tools/guides/docs that could help me with migrating?

nova linden
#

i have this setup to load and unload scenes for networking and it works for basic scenes but if i load a scene with network objects in it it i cant unload it for some reason with this function

#

i dont even get any errors

ocean spade
#

I've got an optimizaiton question, I know that using a ClientRpcParams x = default and then parsing through a list of users you want to send the event to will, well send the event to them

#

but what if instead, I passed through a bitMasked byte (it's an 8 player game) where each player represents a 1/0 on said byte

#

the upside would be no memory usage creating a ulong array for each time I need to send a message, but the downside would be bitmasking, and bitmasking correctly ever time I need to send a message

#

am I being a clown for not just using unity's provided solution? or is what I'm doing a clever optimization to help save some ram so I can save some battery

#

i have this setup to load and unload

mortal sparrow
ocean spade
#

I mean i'd also have to create a ulong array every time vs bitmasking into a byte

#

It's a message system between players, where the local calls a server rpc, and sends the targets ID. I could construct an array of ulongs and then parse that, which creates more work for the server

#

I mean in that case, it's only be two ulongs, but I also want the ability to send to whichever players I want... Probably overthinking way too hard though

mortal sparrow
#

I don't think you understand how fast computers are. You could do a million of these per seconds and only loose a couple of frames

#

This is not optimization this is just intentionally making things hard and unreadable

ocean spade
#

Alright, I'll go with the regular approach then... Because it also gives better scability

#

Just checking, does saying ClientRpcParams x = default send to all clients? or none?

mortal sparrow
#

Not sure, but i'd assume it's to all.

#

wait lemme check

#

The docs don't saying anything about it. But it wouldn't make sense that it won't be sent to all clients.

ocean spade
#

That's what I was thinking, thanks for the advice 👍

sharp axle
radiant solstice
#

Hey all, I am having a bit of an issue when using NGO. I am using a NetworkPoolManager for object pooling that is provided here:

https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/v2.2.0/Assets/Scripts/Infrastructure/NetworkObjectPool.cs

My issue is that when a client collides with an object that should be put back in the pool it calls :

        NetworkObjectPool.Singleton.ReturnNetworkObject(NetworkObject, prefab);

On the host, it works just fine and the pre-warmed objects are returned to the pool.
On the client however, I get an exception that says :

InvalidOperationException: Client is not allowed to write to this NetworkVariable

I am unsure what I can do to have it work on both clients and host.

GitHub

A small-scale cooperative game sample built on the new, Unity networking framework to teach developers about creating a similar multiplayer game. - Unity-Technologies/com.unity.multiplayer.samples....

void steeple
#

Hi, I want to get the value of a variable stored in a script in the scene from a player prefab. How would I do that as I cannot reference stuff in the scene from a prefab? Ping replies

wintry epoch
#

Do HttpClient works on linux dedicated server?

ocean spade
teal cedar
#

This is so confusing .To make multiplayer game you need both netcode for gameobjects and unity gaming services (relay, matchmaker, authentication...)?

spring crane
sharp axle
# teal cedar Well, it's battle royale so

You can use any networking framework for that. Photon, Mirror, Fishnet will all work. There multiple services you can use too. Epic Online Service and Azure Playfab have authentication, matching, relay, and Playfab also has server hosting

crude stirrup
#

What's the correct way to get the NetworkObject of a player by it's LocalClientId (or something else)?

Currently im doing:

In update:

PickItemServerRpc(pickable.name, NetworkManager.Singleton.LocalClientId);
private void PickItemServerRpc(string name, ulong playerNetworkId)
    {
        PickItemClientRpc(name, playerNetworkId);
    }
[ClientRpc]
    private void PickItemClientRpc(string name, ulong playerNetworkId)
    {
        // Find the player's NetworkObject based on the player network ID
        NetworkObject playerNetworkObject = NetworkManager.Singleton.SpawnManager.SpawnedObjects[playerNetworkId];
        Transform slot = playerNetworkObject.transform.Find("GrabSlot");
        ...
    }

But it throws an error saying that key 0 was not found in the dictionary.
But it should be found because player 0 is the 0's client, which is also the host, which is where I tried to pickup the item.

Im sorry if it's a bad explanation, but can somebody try to figure out what's wrong?

tawny needle
#

need help with client prediction, prediction errors are happening very often:
https://streamable.com/6o0unx

relevant parts of my code:

    struct InputMessage : INetworkSerializable
    {
        public int tick;
        public Vector2 move;
        public Vector2 look;
        public bool jumping;

        public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
        {
            serializer.SerializeValue(ref tick);
            serializer.SerializeValue(ref move);
            serializer.SerializeValue(ref look);
            serializer.SerializeValue(ref jumping);
        }
    }

    struct LagRecord : INetworkSerializable
    {
        public InputMessage inputMessage;
        public Vector3 position;
        public Vector3 velocity;

        public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
        {
            inputMessage.NetworkSerialize(serializer);
            serializer.SerializeValue(ref position);
            serializer.SerializeValue(ref velocity);
        }
    }

    [SerializeField] private NetworkVariable<InputMessage> inputMessage = new(readPerm: NetworkVariableReadPermission.Owner, writePerm: NetworkVariableWritePermission.Owner);
    [SerializeField] private NetworkVariable<LagRecord> lagRecord = new(readPerm: NetworkVariableReadPermission.Owner, writePerm: NetworkVariableWritePermission.Server);
#
private void GameTick()
    {
        if (IsLocalPlayer)
        {
            inputMessage.Value = new()
            {
                tick = NetworkManager.Singleton.NetworkTickSystem.LocalTime.Tick,
                move = inputManager.GetMoveInput(),
                look = inputManager.GetMouseDelta(),
                jumping = inputManager.jumping
            };
        }

        if (IsServer)
        {
            DoMove(inputMessage.Value);

            lagRecord.Value = new()
            {
                inputMessage = inputMessage.Value,
                position = transform.position,
                velocity = _rigidbody.velocity
            };
        }
        else if (IsLocalPlayer)
        {
            TrackPredictionErrors();
            DoMove(inputMessage.Value);

            predictedRecords[inputMessage.Value.tick % recordAmount] = new()
            {
                inputMessage = inputMessage.Value,
                position = transform.position,
                velocity = _rigidbody.velocity
            };
        }
        else
        {
            transform.position = lagRecord.Value.position;
            _rigidbody.velocity = lagRecord.Value.velocity;
        }

        Physics.Simulate(intervalPerTick);
    }

private void DoMove(InputMessage inputMessage)
{
    Vector3 direction = new(inputMessage.move.y, 0f, inputMessage.move.x);
    direction = transform.TransformDirection(direction);

    transform.position += direction;
}
#
private void TrackPredictionErrors()
    {
        LagRecord serverRecord = lagRecord.Value;
        LagRecord predictedRecord = predictedRecords[serverRecord.inputMessage.tick % recordAmount];

        if (serverRecord.position != predictedRecord.position && serverRecord.inputMessage.tick == predictedRecord.inputMessage.tick)
        {
            transform.position = serverRecord.position;
            _rigidbody.velocity = serverRecord.velocity;

            int tick = serverRecord.inputMessage.tick;
            predictedRecords[tick % recordAmount].position = serverRecord.position;
            predictedRecords[tick % recordAmount].velocity = serverRecord.velocity;
            tick++;

            while (tick < inputMessage.Value.tick)
            {
                DoMove(predictedRecords[tick % recordAmount].inputMessage);
                predictedRecords[tick % recordAmount].position = transform.position;
                predictedRecords[tick % recordAmount].velocity = _rigidbody.velocity;
                tick++;
            }

            Debug.Log("corrected, local record: " + predictedRecord.position + " server record: " + serverRecord.position + (serverRecord.inputMessage.tick == predictedRecord.inputMessage.tick));
        }
    }

input msg is written by localplayer and read by server, holds buttons held by player and the tick when it was sent to server
lagrecord is written by server and read by localplayer, holds player position/velocity and input message

#

pls

timid compass
#

I have abilities in my game that have a cooldown, but i am also using client side prediction. I'm thinking it would be better to start the cooldown for each ability only after the server has executed said ability. rather than start the cooldown when the client activates it, Im thinking that if the client is lagging a bit and their ability comes out earlier than on the server than the cooldown will be inconsistent on the server side.

what do you guys think? is this a big deal or can i start cooldown on client activation instead

timid compass
sharp axle
timid compass
#

So if people are trying to time your cooldowns it will be very inconsistent. Unless the cooldown only starts after the server has executed the ability

low spoke
#

When I use Unity.Netcode in any of my scripts it works fine but in some scripts in the same project it can't find the name space

sharp axle
sharp axle
low spoke
inner lily
#

Hey everyone, I have a game running over pun. The players get instantiated and everything. The problem is when another player joins, the new player's UI controller instance replaces the previous player's UI controller instance.

Here's the code
https://pastebin.com/dBwatYzz

keen bluff
#

Can someone help me with unity netcode
Im just trying to learn it

#

I want to make it so that, one player joins, and variable in gameManager named playerID will be 1
Then another player joins, and variable playerID in their gameManager will be 2, cuz 1 is already taken on other device

#

how can i do this im getting so confused with this

keen bluff
#

okay so I will try to be more concise with my problem
I downloaded some stuff called parrel sync and now I have two editor instances. I have made a network manager, I have made buttons to connect client host server. I created a script that derives from network behaviour and inside it I created a network variable<int>. In update I made it add 1 to the variable on some keyboard button press.
Now the problem I currently have is that the 2 instances arent updating at once. If i press on unity instance 1 the key 7 times, its gonna say the value is 7, but only on that instance, not on the other. I want it to be synchronised and i have no idea what im doing wrong i literally just followed the tutorial.
Here is my code for the variable:

public class GameManager : NetworkBehaviour
{
  NetworkVariable<int> curPlayerID = new NetworkVariable<int>(1);

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.X))
        {
            curPlayerID.Value++;
        }
        Debug.Log(curPlayerID.Value);
    }
}
#

Basically in other words, the variable doesnt seem to be working like a variable which is shared across all clients, rather an individual one on every client

keen bluff
#

well, after 4 hours i managed to fix it.
the problem? literally easiest thing on this entire server that ever happened

#

i had to add "Network Object" script

#

everything started working

wet gale
#

Photon PUN2 high latency

timid compass
#

but at that point the server should correct them if they stray to far from what is actually happening

#

either way that has almost nothing to do with the actual question I asked. I'm well aware how it works, only asking others opinion on timing things like cooldowns in competitive games

#

2 seconds is just an example, my point being either way no clients should get subtle advantages for being laggy

faint cedar
#

Hello all. With the network manager, how does the player prefab work across scenes? In my game, I need the players to connect in the main menu scene then load into the game scene, but the player prefab is instantiated in the main menu and not in the game. How do I handle this?

shrewd junco
faint cedar
#

Thank you I will look into that

loud badge
#
    {
        string url = "http://52.79.191.173:8080/user/uploadPost";

        // Create JSON for postRequestDto
        string postJson = "{\"title\":\"게시글 제목\", \"content\":\"게시글 내용\", \"nickName\":\"유저1\", \"longitude\": 127.10459896729914, \"latitude\": 37.40269721785548}";

        // Create form data
        WWWForm form = new WWWForm();
        form.AddField("postRequestDto", postJson);

        // Add image files
        foreach (string imagePath in imagePaths)
        {
            byte[] imageBytes = File.ReadAllBytes(imagePath);
            string imageName = Path.GetFileName(imagePath);
            form.AddBinaryData("imageFiles", imageBytes, imageName, "image/png");
        }




        // Send POST request
        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            // 필드 postRequestDto의 타입을 application/json으로 설정
            //request.SetRequestHeader("Content-Type", "application/json");

            // 요청 및 응답 대기
            yield return request.SendWebRequest();

            // 에러 확인
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("Error: " + request.error);
            }
            else
            {
                Debug.Log("Form upload complete!");
                Debug.Log("Response: " + request.downloadHandler.text);
            }
        }
    }

    public void TestUpload()
    {
        string[] imagePaths = new string[]
        {
            "C:/Users/알고 싶냐/Pictures/arm.png",

            "C:/Users/알고 싶냐/Pictures/arm.png"
            // Add more image paths here
        };
        //StartCoroutine(Start1());
        
        StartCoroutine(tUploadPost(imagePaths));
    }```
hello, i tried to  post multipart/form-data to server but it did not respoding how ever i tried with post man it works so.... i dont know why this is happening 😦
#

here is how i tested on Postman

turbid ether
#

Also what is the actual error and your Unity version

loud badge
#

here's error

loud badge
turbid ether
#

Trusting GPT is bad practice

turbid ether
# loud badge

Unauthorized means you are lacking of credential? Do you have authorization header in your Postman?

loud badge
#

i dont know where to check the authorization header

turbid ether
#

In the header tab

loud badge
#

u mean these?

turbid ether
#

Sounds like you have separate login flow

keen bluff
#

InvalidOperationException: Client is not allowed to write to this NetworkVariable
Unity.Netcode.NetworkVariable`1[T].set_Value (T value)

Whats this :( ? This is my variable:
public NetworkVariable<int> curPlayerID = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);

turbid ether
keen bluff
#

hmmm... but isnt the client the owner if he also has this script?

turbid ether
#

Most of time in netcode owner means state authority = server

#

Or the host

keen bluff
#

hmmm.... well thats weird, how can i allow the client to write the value then?

turbid ether
#

Well change write permission you set

keen bluff
#

ummm
but there are only 2 there... owner and server...

#

at least thats what documentation says

turbid ether
keen bluff
#

ohhhhh

#

i think i see now

turbid ether
#

For objects like character that controlled by client

keen bluff
turbid ether
#

Looks right

keen bluff
#

oh okay thanks

#

hm, but now im wondering, doesnt this thing mean that only 1 client/server at a time can be an owner of a network object?

turbid ether
#

That’s how it works, since one has to be authority, and other client trust that value (proxy)

keen bluff
#

oh
so its not possible to make a variable that every client can write basically?

turbid ether
#

Client writes own input

#

Then server validates and apply to state

keen bluff
#

so i need to write functions which will change value of a variable, which will be run on the server but called from clients (like serverrpcs i believe it was called)? or am i understanding this wrong?

turbid ether
#

Otherwise client cheat or fight over the value right

#

Inputs can be rpcs sure

keen bluff
#

thx for help i will try to do it now

loud badge
#

i gotta a hit on subway so u guys can wait for my helpcall

keen bluff
#

lolll why is this happening to meeeee
"Only the owner can invoke a ServerRpc that requires ownership!"

#

oh I managed to fix it with (RequireOwnership = false)

loud badge
keen bluff
#

Hmm, im having big problems figuring out how to synchronise the network variables well, heres my code:

    [ServerRpc]
    public void TestServerRpc()
    {
        a.Value = 2;
        TestClientRpc();
    }

   
    [ClientRpc]
    void TestClientRpc()
    {
        Debug.Log("Val: " + a.Value);
    }

and on the photo are the results, left is host, right is client.
why does the value on the client says it is 0 (as in not updated), if i just updated it to 2 before calling the function?

#

also i would like to add that the value does update, i can see it in the inspector of the client.
also when i tried doing an invoke for the debug on the client, so that i debugged the value like 3 seconds later, it said 2, which is correct. So it seems like the fact that the network variable is updated doesnt go to client before TestClientRpc() does...

#

this is sooo confusing me

sharp axle
keen bluff
#

hmmm idk, im just figuring this stuff out so far... also, i tried using onvaluechanged and uhhhh... i cant really understand it, maybe could you explain to me when it is run?

#

like, do i need to put OnValueChanged in update or what?

#

or does it just activate whenever the value is changed

#

oh
ohhhhh it makes sense to me now that using both rpcs and network variables is dumb lol

#

ok i made it work with OnValueChanged, thanks

crisp panther
#

wanna ask what would cause this issues?

#

i trying to lauch a localhost server on unity

#

with mssql

weak plinth
#

Hello, im experiencing an issue with photon in which the OnJoinedRoom() function isnt being called. The player can create their own rooms and the scenes change accordingly, but when i try to instantiate the player after the scene is loaded thefunction completely doesnt get clled. any ideas on why this might be happening?

public class PlayerSpawner : MonoBehaviourPunCallbacks
    {
        public Transform spawnPoint;

        public override void OnJoinedRoom()
        {
            PhotonNetwork.Instantiate("Player Holder", spawnPoint.position, Quaternion.identity, 0);
            Debug.Log("Spawned in player!");
        }

    }
weak plinth
crisp panther
#

try to add try and catch see either it got overwriten or not

#

sometime override doesnt work if no error message

weak plinth
crisp panther
#
string message = "";
        try
        {
          //your code
        }
catch(Exception ex)
        {
            message = ex.Message;
        }
        // or Debug.Log(your code)
        return message;

weak plinth
# crisp panther ```csharp string message = ""; try { //your code ...

its giving me these errors:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

namespace Com.DevSpill.SS
{
    public class PlayerSpawner : MonoBehaviourPunCallbacks
    {
        public Transform spawnPoint;

        string message = "TEST";
        try
        {
            public override void OnJoinedRoom()
            {
                PhotonNetwork.Instantiate("Player Holder", spawnPoint.position, Quaternion.identity, 0);
                Debug.Log("Spawned in player!");
            }
        }
        catch(Exception ex)
        {
            message = ex.Message;
        }
        // or Debug.Log(your code)
        return message;
        

    }
}

this is the code so far

crisp panther
#
public class PlayerSpawner : MonoBehaviourPunCallbacks
    {
        public Transform spawnPoint;

        string message = "TEST";
        public override void OnJoinedRoom()
            {
                try
                {
                    
                        PhotonNetwork.Instantiate("Player Holder", spawnPoint.position, Quaternion.identity, 0);
                        Debug.Log("Spawned in player!");
                    
                }
                catch(Exception ex)
                {
                    message = ex.Message;
                }
                // or Debug.Log(your code)
                Debug.Log(message);
        }

    }

weak plinth
crisp panther
#

you need to add using class yourself

weak plinth
weak plinth
crisp panther
#

is your trigger issues

crisp panther
#

you need to find where is your called action to overrite

#

like Start(OnJoinedRoom()) or Update(OnJoinedRoom())

#

or your button need to link into onclick action

weak plinth
teal cedar
#

Don't tell me that when I change something then I have to build and run again when developing multiplayer game

#

Or should I make copy of whole project?

true raptor
#

how do singletons work in unity netcode for gameobjects? it seems to only reference the hosts singleton

crisp panther
quiet ginkgo
#

Does nayone know how to get the UTF-16 PersonaName via Steamworks?

spring crane
spring crane
teal cedar
spring crane
teal cedar
#

Because tomorrow I am going to try it

tawny needle
#

How can i use queues with netvars?

loud badge
#

hello , here i am calling for help for the same problem ``` string url = "http://52.79.191.173:8080/user/uploadPost";
WWWForm form = new WWWForm();
byte[] byteData=null;
string json= "{"title":"게시글 제목", "content":"게시글 내용", "nickName":"유저1", "longitude": 127.10459896729914, "latitude": 37.40269721785548}";
// Add your form fields and files to the form
form.AddField("postRequestDto", json);
string[] imagePaths = new string[]
{
"C:/Users/알고 싶냐/Pictures/arm.png",

        "C:/Users/알고 싶냐/Pictures/arm.png"
        // Add more image paths here
    };
    foreach (string imagePath in imagePaths) {
        byteData=File.ReadAllBytes(imagePath);
        string filename = Path.GetFileName(imagePath);
    form.AddBinaryData("file", byteData, filename, "image/png");
    }

    using (UnityWebRequest www = UnityWebRequest.Post(url, form))
    {
        // Set headers
        string boundary = "----------------" + UnityEngine.Random.Range(int.MinValue, int.MaxValue);
        www.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        www.SetRequestHeader("User-Agent", "UnityPlayer/1.0");
        www.SetRequestHeader("Accept", "application/json");

        // Generate the body with the boundary
        byte[] body = GenerateMultipartFormDataBody(form, boundary);
        www.uploadHandler = new UploadHandlerRaw(body);

        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("Error: " + www.error);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }
    }
}``` using this corutine to send multipart/form-data to server but it says 

Error: HTTP/1.1 401 Unauthorized...
i do not have a clue what to do

loud badge
#

what makes me frustrated is that i tried to send on Postman it works!! so it has to be program error

loud badge
#

i'm kinda feel like an idiot for asking this but.... dose some multiform/data dose not have boundary?

#

acoding to sever dev
this is kind of curl that sends to server

--form 'postRequestDto="{\"title\":\"게시글 제목\", \"content\":\"게시글 내용\", \"nickName\":\"유저1\", \"longitude\": 127.10459896729914, \"latitude\": 37.40269721785548}";type=application/json' \
--form 'imageFiles=@"/C:/Users/이지훈/Desktop/포폴사진/bedi/목표작성.png"' \
--form 'imageFiles=@"/C:/Users/이지훈/Desktop/포폴사진/bedi/알.png"'```
void steeple
#

I'm trying to make a ready up system for my game. At the moment, I'm just making it detect the number of players who have clicked the 'Ready Up' button. When a different client clicks the button, the network variable is overwritten, rather than added to. Ping me

    new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone,
        NetworkVariableWritePermission.Server);
private bool localPlrReady = false;

[ServerRpc(RequireOwnership = false)]
public void ReadyBtnClickServerRpc() {
    if (localPlrReady) {
        readyPlayers.Value -= 1;
        Debug.Log(readyPlayers.Value);
        localPlrReady = false;
    } else {
        readyPlayers.Value += 1;
        Debug.Log(readyPlayers.Value);
        localPlrReady = true;
    }
    
}```
tawny needle
#

Anyone else has had an issue where there is a host and a client in game and when the client leaves the host can no longer move????

teal cedar
#

Is this true?
If both the server and clients have a method with the same name and that method is marked with [ClientRpc], when the server calls that method, it will automatically execute on all connected clients. This is the mechanism by which server-client communication is achieved using Unity's Netcode for GameObjects.

willow wren
#

Are there any resources out there for best practices with Steam's Remote Play Together? I tried it with my in-development game, and it was a generally poor experience. It's pixel based graphics, so I was hoping I could reduce the streaming image by a good bit, but my monitor is the standard HD size, and that is a lot more info to stream.

There wasn't too much noticable lag, but we did loose connection a few times.

granite pike
#

How come this isnt doing anything? like when the Server rpc is called to legit do nothing but print(), it doesnt even do that??
https://gdl.space/coyufihase.cs

upper magnet
#

Has anyone here tried making a multiplayer game with quick changes in velocity like for example jumping or dashing? I'm using the NetworkTransform to sync the positions but the "Interpolate" function is way too slow, causing ramp up and ramp down in speed whenever I jump or land

#

I'm wondering if people just, don't use the network transform at all or how people are able to get good looking jumps in their multiplayer games

#

(I'm in Netcode for GameObjects)

slow zinc
#

has anyone here used EOS? im currently using Steamworks Networking for lobbies & p2p multiplayer in my game, however, the issue is this locks my game to Steam and takes away any kind of cross-platform play for anyone who is playing the game off steam. I thought about switching to EOS instead for cross-platform for any future ports of the game, and to enable myself to sell it on sites like itch.io, but im feeling a bit conflicted. if anyone has used epic online services (or has switched from steamworks to EOS) please let me know if you'd recommend it

silk sparrow
#

Anyone please tell me how to use photon in unity

#

I have setup the the script but everytime I click on okay it says photon is not setup

worn solstice
#

How would I go about implementing server authoritative AI enemies with client side prediction for scenarios like a player knocking it back?

#

Atm Im trying to have the movements predicted client side but I cant line up the ticks stored in the gamestates with the ones being received from the server

#

I.e. the gamestate stored in tick 100 on the server is stored in tick 97 on the client and Idk how to line that up

upper magnet
#

essentially predict what decision wil be made?

worn solstice
#

Im trying to predict the knockback players can apply

#

Players send a server rpc to knock the enemy when they attack but theres a substantial delay so I was trying to have client side prediction knock it back client side as well

gleaming zenith
#

My game when switching scenes with the network manager the clients consistently dont spawn some network objects does anyone know the cause of thsi?

worn solstice
#

Are you calling the spawning once every client is successfully loaded in?

#

Maybe some are joining late and missing some calls or smth

gleaming zenith
worn solstice
#

No clue I'm not too familiar with how network objects pre placed in scene behave

#

Do networkobjects still need to be spawned in even in theyre placed beforehand?

gleaming zenith
worn solstice
#

Im not sure then

#

Are they added to the network prefab list on your network manager?

gleaming zenith
#

yeah they are

worn solstice
#

Is there a way to get how a ahead clients localtime is comapred to servertime?

graceful zephyr
upper magnet
#

Like if the characters are close and move just a bit, the knockback angle changes completely

#

Why not have the client decide precisely and then send that information to the server, if you are okay with that being client authoritative

#

So client says "I hit him from this location at this angle" and then the server just makes that happen.

worn solstice
#

Yea Im messing around with different ideas, but what I had before was basically that and the time from client telling the server they connected a hit to the client receiving the resulting knockback was enough to feel a fair bit unpleasant

#

I have reconciliation working to a degree for players so the gamestates shouldnt be that vastly different for the knockback to vary, I think

#

I guess the issue Im having atm is that for client side prediction it involves the client sending inputs to the server and predicting what will happen

#

But with enemies which Im having trouble wrapping my head around how to implement this like which client should be sending the non player controlled enemy's inputs and what happens when another client knocks it back etc.

#

After messing around I think Im going to try and have it so that whoever the enemy is tracking will be the client that sends the enemys "inputs" as well as anyone knocking the enemy back

#

The server will process these inputs as they arrive into one amalgamated gamestate which it then relays to the clients who will reconcile and resimulate if needed

#

Not sure if thats coherent but fingers crossed something at least partially functional comes out of it

true raptor
#

How can i create a list or dictionary as a network variable, of my custom serialised struct?

silk reef
#

I swear I saw on unity netcode docs in 2023 you could run multipeer in the same editor, was I imagining it?

astral tree
#

Hey guys, I have a custom class that has two floats and I am trying to use it in a NetworkVariable
I already implemented INetworkSerializable:

    {
        serializer.SerializeValue(ref Value);
        serializer.SerializeValue(ref maxValue);
    }```
Then I am changing it like this :

hunger.Value.Value -= value;


However the changes are not detected immediately until I move I suppose until some network event happens.

I tried this:

hunger.Value = new Need()
{
Value = hunger.Value.Value - value,
maxValue = hunger.Value.maxValue
};

and it works but I suppose this generates garbage
Anyone has any idea?
sharp axle
worn solstice
sharp axle
worn solstice
silk reef
sharp axle
analog warren
#

hi

#

GUYS I am making a multiplayer game using photon and i need help

#

it a top down shooter

#

i just need to make a gui for diffrent players

#

i am openin the project

#

i will ss every thing

severe briar
analog warren
#

limme try

severe briar
#
public class PlayerUI : NetworkBehaviour
{
    [SerializeField] private GameObject UI

    public override void OnNetworkSpawn()
    {
        if (!IsOwner)
        {
            UI.SetActive(false);
        }
    }

    private void UpdateHealth(int current) => hp.text = current.ToString();

    private void UpdateBombs(int current, int max) => bombs.text = $"{current} / {max}";
}

Something like this, this example uses NGO, so the syntax may not be the same

I've deleted some stuff from the example to make it simpler

analog warren
#

the pov is the other's player same with him

severe briar
#

You also need to check if the player is owner

Move()
{
if(!isOwner) return;
//Move here
}
analog warren
#

ok

#

i saw the error

#

ok i changed stuff cuz its not in photon

#

i did stuff

#

i testing

analog warren
severe briar
#

Can you send the camera code?

analog warren
#

oh its uuh cinemachine

#

i feel that it was a dum idea to use photon but i did anyways

severe briar
#

Oh, I see
You need to do the same stuff, that you did with the UI
Turn off Cinemachine and camera component on non owners

analog warren
#

hmm

severe briar
analog warren
#

how to disable a component again?

#

cam.enabled = false;

severe briar
#

Just reference it, check if is owner and disable it

cam.enabled = IsOwner;
analog warren
#

public void Start()
{
if (!view.IsMine)
{
UI.SetActive(false);
cam.enabled = false;
}
}

severe briar
analog warren
#

ok i will try

severe briar
analog warren
#

ok i will test it

#

what do i do

#

tryagain doesnt work

#

ok nvm

#

i pressed x

severe briar
#

Maybe you've accidentally moved some files

analog warren
#

idk i dont remember doing that

#

i made a new folder

#

still

#

same error

severe briar
# analog warren same error

Well, I don't know.
Sometimes unity does some really weird stuff.
I've talked about it today in general-coding a couple of hours ago.
My advice is to learn git and use github/gitlab
It's really easy to pickup, but hard to master

analog warren
#

i am using one so i work with my friend at teh game

#

we wanted to use plastic scm

#

but we didnt know how it took a while to figure it out

#

turns out it needed github

#

so we used github without plastic scm

#

oh the project just opend

severe briar
#

Actually, you can use git without any cloud space like github and gitlab.
And host everything yourself.
But, in most cases, yeah, you need a github account. Also you should use a unity .gitignore file to save only essential stuff.

analog warren
#

oh it worked

#

i just used another partion in the drive and made a new folder

severe briar
#

if you need help, feel free to ping me.

analog warren
#

omg it works

#

thank you

south palm
#

how do you get a cinemachine camera to not lose its references when you spawn in a player in an fps

tiny furnace
#

i have no idea what im doing but i followed the NGO tutorial and now i wanted to connect a 2nd player to it but im unable to connect with a second instance

sharp axle
sharp axle
tiny furnace
sharp axle
tiny furnace
#

2023.1.11f1

sharp axle
#

That should work then. Have you tried making a build and connecting with it?

tiny furnace
sharp axle
tiny furnace
#

ive now built a client, while being a host in the editor, it doesnt seem to connect

#

do i need something to tell to connect or does it do that automatically?

sharp axle
red olive
#

how would I go about letting a player move? (using mirror and builtin CharacterController)
I've tried a few things, but nothing has worked, (idk if im doing something wrong)

(client doesnt have authority, if that helps...)

severe briar
severe briar
# red olive how would I go about letting a player move? (using mirror and builtin CharacterC...

Since Mirror updated their Network transform component, the logic has to be server authoritative.
So, instead of

public void Update()
{
    if(!isOwner) return;
    //Move here
}

You'll have to use ServerRpc, to send a command to the server

private Vector3 _moveDirection;

public void Update()
{
    if(!isOwner) return;
    GetInput();
    MoveServerRpc(_moveDirection);
}

private void GetInput()
{
    //Get Input and change the _moveDirection variable
}

[ServerRpc]
private void MoveServerRpc(Vector3 direction)
{
    //transform.position += direction * Time.deltaTime;
    
    //It will work, but it's better to bound to the server tickrate
    //So, instead of moving in the update method, you should subscribe to OnTick event, and do your logic here
}

I hope you've got the idea.

naive yoke
#

I know how to screenshot my game and save into local drive. Are there any documents or tutorial that allows me to upload screenshot to the hosted game/cloud server?

severe briar
naive yoke
severe briar
tiny furnace
severe briar
tiny furnace
severe briar
tiny furnace
#

i see, now i can see the other capsule but i can only controll on the host and the client mirrors the host camera?

the client also moves the same like the host does

severe briar
teal cedar
#

Is there way to spawn objects when server started? Unity netcode for gameobjects

severe briar
tiny furnace
severe briar
# tiny furnace i feel so stupid for asking that but...where and how do i put it there?

Stupid person is a person who never ask questions.
So, you are definitely not stupid, just learning.

It's called callback, you just need to subscribe to it in awake method

void Awake()
{
    NetworkManager.Singleton.OnServerStarted += OnServerStarted;
}

void OnServerStarted()
{
    //Will be called on server start
}

Also, don't forget to unsubscribe, in general.
In this case it's not necessary I believe, but I still like to unsubscribe.

void OnDestroy()
{
        if(!NetworkManager.Singleton) return;
       NetworkManager.Singleton.OnServerStarted -= OnServerStarted;
}

Sorry for formatting, tab stopped working in discord

worn solstice
#

If its a network object would you unsubscribe in onnetworkdespawn?

severe briar
worn solstice
#

Instantiating/destroy and spawn/despawn being separate things feels so weird to me

severe briar
tiny furnace
# severe briar Turn off camera on non-owners ``` camera.enabled = IsOwner; ``` Check if the pl...

no worries, i just dont get it, ive seen so many different versions of disableling the camera the past hour but i have no idea how to implement it. im using this script to control my player and camera.
https://sharpcoderblog.com/blog/unity-3d-fps-controller

do i just put this at the top
camera.enabled = IsOwner;

and this at the bottom?

{
    if(!isOwner) return;
    //Move here
}```
but whats going in the //Move here?
severe briar
worn solstice
#

Does anyone know whether theres an execution order for rpcs

tiny furnace
worn solstice
#

Like if a server receives an rpc does it process that and then whatever else it needs to do like Tick() or vice versa

severe briar
severe briar
worn solstice
#

Idk if this question makes sense

worn solstice
tiny furnace
severe briar
worn solstice
#

Will test, was just hoping someone knew so I wouldnt have to do the work myself haha

analog warren
#

so uhh

#

I am making a multiplayer game using photon and i need help
it a top down

#

the proplem is with the camera

#

it uses cinemachine

#

you might remember me from yesterday

#

the problem was the ui so i fixed it

#

then there is a problem with camera

tiny furnace
#

will a domain also work as address?

severe briar
severe briar
#

But, it may not work on unity side.
You'll have to convert it to ipv4 format

tiny furnace
tiny furnace
#

ive set the port to 4465, i tried it with a minecraft server under this port and its available from the outside but it wont work with the unity server its just not there and thus im unable to conenct to it, it still works locally

severe briar
tiny furnace
severe briar
tiny furnace
#

its set to private

#

huh, domain doesnt work only numbers apparently

teal cedar
#

Damn, im suffering with this three days. How to spawn crate when server is initialised

severe briar
tiny furnace
#

i want to set the address with an input field and found this online tho its complaining
NetworkManager.GetComponent<UnityTransport>().ConnectionData.Address="someString";

severe briar
tiny furnace
#

what does singleton do? ive seen this now a bunch of times for the starthost and so on

severe briar
teal cedar
severe briar
teal cedar
# severe briar It should.

So like this? ```
void Awake()
{
NetworkManager.Singleton.OnServerStarted += OnServerStarted;
}

void OnServerStarted()
{
If (! Isserver) return;
Transform spawn = Instantiate (object)
Spawn.gameObject.getComponent<NetworkGameObject>().Spawn;
//Will be called on server start
}

river summit
#

i got this problem where I am trying to make a chat system with photon PUN but as the player sends a msg it displays to him with his Username and msg meanwhile it displays to other players with their name and no msg this is the first time im using photon pun so bare with me bc im out of ideas

heres my code :

            GameObject Pchat = PhotonNetwork.Instantiate(PChat.name, PChat.transform.position, Quaternion.identity);

            Pchat.transform.SetParent(holder);

            Pchat.GetComponent<Text>().text = PlayerPrefs.GetString("Username") + " : " + input.text;

....................

I know the problem and its that Pchat is only defined for this client thats why it works only for me so i just need to find a way to use the sender of the msgs Username and text-msg across the network... and i have no idea how to do that i probably have to use [PunRPC] but idk how to use that

#

help!

severe briar
# river summit i got this problem where I am trying to make a chat system with photon PUN but a...

You should send a server rpc

[ServerRpc]
void SendMessageServerRpc(string nickName, string message)
{
    var chatMessage = PhotonNetwork.Instantiate(PChat.name,     PChat.transform.position, Quaternion.identity);
    Pchat.transform.SetParent(holder);
    Pchat.GetComponent<Text>().text = $"{nickName}:{message}";
}

Note, that my example uses your code and NGO syntax.
Adapt it for photon yourself, because I've never used photon before.

river summit
#

what am i supposed to assign the nickname to ? if i assign it to PlayerPrefs.GetString("Username") it wont be on the network...

severe briar
# river summit what am i supposed to assign the nickname to ? if i assign it to PlayerPrefs.Get...

It depends on how you save them.
If you're using PlayerPrefs than

[SerializeField] private TMP_InputField inputField;

void Awake()
{
    inputField.onClick.AddListener(SendMessage);
}

void SendMessage(string text)
{
    SendMessageServerRpc(PlayerPrefs.GetString("UserName"), text)
}

[ServerRpc]
void SendMessageServerRpc(string nickName, string message)
{
   //The same thing as in the previous message
}

Basically, you get the data from the player prefs locally, then send them to the server.

if you would do something like this:

[ServerRpc]
void SendMessageServerRpc(string message)
{
   var name = PlayerPrefs.GetString("Username");
   Pchat.GetComponent<Text>().text = $"{name} : {message}";
}

It will be executed on the host/server. Playerprefs would load host's name.

river summit
#

i dont think there is a ServerRPC in photon as its not accepting it ?

severe briar
river summit
#

also should the fields i use be serialized ??

severe briar
severe briar
river summit
#

ill test it and brb

#

nope doesnt work

#

now the error doesnt show but it sends the msg twice and its still not syncing the senders name and msg on the network

severe briar
river summit
#

i gtg afk brb in less than an hour or so.. srry

severe briar
river summit
#

im afraid that doesnt fix anything

severe briar
river summit
#

thanks for your help, really appreciated

sand talon
#

Is it possible to conntect to a Room Using an IP instead of a room name?

austere palm
#

hello, I recently started using netcode. I have prior networking experience with other frameworks. I was wondering what would happen If i made 200 ais in one lobby using ecs and try to sync their transforms ? would it cause too much traffic or is ecs multiplayer made for that ? as far as I see it's used for player objects. I was wondering if it's possible to do what I want

severe briar
# austere palm hello, I recently started using netcode. I have prior networking experience with...

It will depend on how much data you'll send every frame.
Position - Vector3 (12 bytes)
Rotation - Quaternion (16 bytes)

But, I don't know if unity does some optimization on this.
You can serialize values how you need, using fast buffers.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/fastbufferwriter-fastbufferreader/

Can't help you on the ecs part.
I have too little experience with it.

severe briar
sharp axle
marble geode
#

There is a weird issue with netcode 1.3 and up. If you inherent from a class that already inherit from NetworkBehavior the object thers an issue with the network object

#
UnityEngine.Debug:LogWarning (object)
Unity.Netcode.NetworkVariableBase:SetDirty (bool) (at Library/PackageCache/com.unity.netcode.gameobjects@1.3.1/Runtime/NetworkVariable/NetworkVariableBase.cs:93)
Unity.Netcode.NetworkVariable`1<UnityEngine.Vector3>:Set (UnityEngine.Vector3) (at Library/PackageCache/com.unity.netcode.gameobjects@1.3.1/Runtime/NetworkVariable```
formal dagger
#

Good evening, I started using Netcode recently and I was implementing the multiplayer logic in my game, everything was going well until then, but after some changes in a part of the code I started to have a strange bug, I will try to describe it more or less, I have 9 cards for each player,
Player 1 is the Host and Player 2 is the Client all right, there are 5 number cards and 4 symbol cards, when Player 1 clicks on a number card (toggle), it appears the number of the card in my "calculator " we can say like this, the number clicked appears in the input calc,
when I press on the symbol letter the symbol appears there and then a number then the number appears there and it looks like this example "10+10" and in my input result the result of the input calc appears, then in the result it appears "20", until then everything ok the problem is in the Client part, the codes are very similar and everything was working ok before,
when Player 2 selects a number and then a symbol, the calc text is erased, however if Player 2 presses a number and then a number again both numbers appear correctly in calc, I found it strange and started to remove the methods to see which part was the problem, and as amazing as it seems after I take the refreshResult method out,
which is responsible for executing the account that is in calc and showing the result in the result, everything is back to "working" in parts since now I no longer have the update of the result, please someone help me with this, if necessary, contact contact me on Discord, I'll send you the codes that mess with the input and the calculator and the rest...

#
using TMPro;
using Unity.Netcode;

public class RandomNumber : NetworkBehaviour
{
    public NetworkVariable<int> randomNumber = new NetworkVariable<int>(1, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
    public TextMeshProUGUI cardText;

    private bool CheckTwoPlayers = false;

    [SerializeField] private Timer ScriptTimer;


    private void Update()
    {
        if (!CheckTwoPlayers)
        {
        if (NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer)
        {
            int playerCount = NetworkManager.Singleton.ConnectedClientsList.Count;
            if (playerCount == 2)
            {
                 GenerateValueCard();
                 CheckTwoPlayers = true;
            }
        }
        }

        if (ScriptTimer.changeCards)
        {
            GenerateValueCard();

        }

    }
    private void Start()
    {
        randomNumber.OnValueChanged += OnRandomNumberChanged;
        ScriptTimer = GameObject.Find("BattleArea").GetComponent<Timer>();

    }

    private void OnRandomNumberChanged(int oldValue, int newValue)
    {
        cardText.text = newValue.ToString();
    }

    public void GenerateValueCard()
    {
        randomNumber.Value = Random.Range(1, 100);
    }

}
#
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

public class RandomSymbol : NetworkBehaviour
{

    public TextMeshProUGUI symbolText;
    private string[] symbols = new string[] { "+", "-", "*", "/" };
    public NetworkVariable<FixedString64Bytes> randomSymbol = new NetworkVariable<FixedString64Bytes>(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);

    private bool CheckTwoPlayers = false;

    [SerializeField] private Timer ScriptTimer;
    

    private void Update()
    {
        if (!CheckTwoPlayers)
        {
            if (NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer)
            {
                int playerCount = NetworkManager.Singleton.ConnectedClientsList.Count;
                if (playerCount == 2)
                {
                    GenerateSymbol();
                    CheckTwoPlayers = true;
                }
            }
        }
    
        if (ScriptTimer.changeCards)
        {
            GenerateSymbol();
        }
   
    }

    private void Start()
    {
        randomSymbol.OnValueChanged += OnRandomSymbolChanged;
        ScriptTimer = GameObject.Find("BattleArea").GetComponent<Timer>();

    }

    private void OnRandomSymbolChanged(FixedString64Bytes oldValue, FixedString64Bytes newValue)
    {
        symbolText.text = newValue.ToString();
    }
    public void GenerateSymbol()
    {
            int symbolIndex = Random.Range(0, symbols.Length);
            randomSymbol.Value = symbols[symbolIndex];

            ///symbolText.text = randomSymbol.Value;
    }

   
}
#
using System.Collections.Generic;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

public class InputCalcP2 : NetworkBehaviour
{
    
    // Referência para o InputField que você quer sincronizar.
    [SerializeField]public TMP_InputField inputToSync;

    
    private void Update()
    {
        // Se for o cliente, envia o valor para o servidor.
        if (IsClient)
        {
            SubmitInputServerRpc(inputToSync.text);
        }
    }

    // Define um ServerRpc para enviar o valor do input para o servidor.
    [ServerRpc(RequireOwnership = false)]
    public void SubmitInputServerRpc(string value)
    {
        // Agora você pode usar 'value' para atualizar seu input no host.
        inputToSync.text = value.ToString();
    }
}
severe briar
placid pulsar
#

Using the unity Relay and Lobby services cost money after some time so I was wondering if there was a way to make your own local server or something

severe briar
placid pulsar
worn solstice
#

Isnt it free as long as you stay under the limits?

#

If its just testing you should be fine unless youre blowing through 50 users worth of bandwidth somehow

placid pulsar
#

Yeah it's just for testing but idk how much bandwidth stuff takes and I prefer having a locally hosted server

#

Kind of like how you would host your own server in Minecraft java or Nitrox mod for subnautica

severe briar
placid pulsar
#

Where do I put this? I have never done any kind of networking before

severe briar
placid pulsar
severe briar
placid pulsar
#

wont i have to tell the network script what the player is

severe briar
#

You can either spawn the player using 'Player prefab' field in the NetworkManager, it will spawn the player on server start and client connection automatically, or you can spawn the player yourself using own spawn script.

placid pulsar
#

using 'Player prefab' field in the NetworkManager, where is this? do i need to download something from the package manager?

severe briar
#

If you have NGO installed it should be available as a component

placid pulsar
#

Netcode for Game Objects?

severe briar
#

Yes, but I don't know which framework you're using, just assuming that you're using NGO.

placid pulsar
#

alright thanks

placid pulsar
#

@severe briar to test this in the editor, i heard there is a package called ParrelSync and i found a link to it but it didnt seem to work when i tried adding it in the package manager. Is there another way to test other than building the entire game?

severe briar
placid pulsar
#

2022.3.7f1

#

maybe the link i got was outdated or something
i got it from a video

placid pulsar
severe briar
#

You need to open the link and download a .unitypackage file

#

Then open it and import

placid pulsar
#

oh alkright

#

thanks

#

is there any other package i should get?

severe briar
#

I don't think so.

placid pulsar
#

alright thanks

teal cedar
#

[ServerRpc (RequireOwnership = false)]
private void SpawnLootItemsServerRpc(int maxLootItems, out bool islootrare) It shows error InvalidProgramException: Invalid IL code in NetworkCodCrate:SpawnLootItemsServerRpc (int,bool&): IL_0083: cgt.un

#

Im done

severe briar
teal cedar
#

No

#

Should I?

severe briar
#

Yes

teal cedar
#

oki

#

normally out bool should work right?

#

In server rpc

severe briar
#

Oh, I know, you can't use 'out' in a RPC.

teal cedar
#

I see

#

so what now...

severe briar
#

Rewrite your code, to make it work without 'out' keyword.

teal cedar
#

sure

#

thanks

placid pulsar
#

i apparently need a network prefab list

#

i get many nullreferenceexception errors

#

but idk where to find a network prefab list

severe briar
#

Then assign each of your network objects in here.

placid pulsar
#

alright, do i add the player here?

severe briar
placid pulsar
#

i made my player a prefab before this so i cant add it

severe briar
#

That makes sense, the player prefab auto register itself.

placid pulsar
severe briar
placid pulsar
#

alright thakns

#

So when i connect as host and client, it successfully instantiates the player prefab and such but each client controls all of them

#

and they dont update to the other client

severe briar
# placid pulsar So when i connect as host and client, it successfully instantiates the player pr...

You need to check the ownership.
Also, add a network transform component.

void Update()
{
    if(!isOwner) return;
    //Move code
}

But, I don't remember if NGO's network transform is server authoritative or not.
Yeah, it is.
You may need to create a client network transform.
Just create a script called 'ClientNetworkTransform' inherit from NetworkTransform and override the bool 'isServerAuthoritative' with 'false'.
Or you can use the default one, but then you'll have to send a server rpc which will introduce a delay between the input and the action.
To deal with it, you'll have to write some kind of client prediction.

placid pulsar
#

alright thanks

placid pulsar
severe briar
placid pulsar
#

so i just copy and paste isServerAuthoritative = false;

#

on all of them

#

or do i have to code a bunch of stuff thats different for every script

severe briar
placid pulsar
#

im a beginner to coding so im not sure how to do that; is there a simpler way to do this or someplace i can learn how to do that

severe briar
placid pulsar
#

alright, thx for the help

silk reef
#

I'm trying to set up a canvas that simply holds the information about the players that are connected. What is the best approach here?

severe briar
silk reef
#

trying to make the UI for each player a networkobject is proving impossible, but it needs to be server authoritative, and i need to do a lot of networked UI

severe briar
#

You don't need to make each UI a network object.
You just have a usual canvas and script(s) to update some elements of it.

#

Oh, sorry, I've read you question incorrectly.

#

I'm a bit sleepy, sorry for that.

What kind of UI do you need?
Like a in time synced as a timer.
And a bunch stuff, that should just update something infrequently, like kill feed, score board etc.

silk reef
#

player clients will make gameplay decisions through the UI, so presenting info on choices etc

#

first thing im doing is the info about the two opponents, so username, etc

severe briar
#

So, store info about players on the server.
When someone connects update UI.

silk reef
#

what just using RPCs?

severe briar
#

Yes, it should work.

If you need some persistent data, use NetworkVariables as they automatically sync with clients.

silk reef
#

i think it makes sense, so i could have like a networkvariable storing the playerdata, and whenever it changes clients update UI

severe briar
vivid kestrel
formal dagger
#

Good evening, I started using Netcode recently and I was implementing the multiplayer logic in my game, everything was going well until then, but after some changes in a part of the code I started to have a strange bug, I will try to describe it more or less, I have 9 cards for each player,
Player 1 is the Host and Player 2 is the Client all right, there are 5 number cards and 4 symbol cards, when Player 1 clicks on a number card (toggle), it appears the number of the card in my "calculator " we can say like this, the number clicked appears in the input calc,
when I press on the symbol letter the symbol appears there and then a number then the number appears there and it looks like this example "10+10" and in my input result the result of the input calc appears, then in the result it appears "20", until then everything ok the problem is in the Client part, the codes are very similar and everything was working ok before,
when Player 2 selects a number and then a symbol, the calc text is erased, however if Player 2 presses a number and then a number again both numbers appear correctly in calc, I found it strange and started to remove the methods to see which part was the problem, and as amazing as it seems after I take the refreshResult method out,
which is responsible for executing the account that is in calc and showing the result in the result, everything is back to "working" in parts since now I no longer have the update of the result, please someone help me with this, if necessary, contact contact me on Discord, I'll send you the codes that mess with the input and the calculator and the rest... https://hastebin.skyra.pw/qogaqunufa.pgsql
https://hastebin.skyra.pw/jexafemazi.csharp

rotund pilot
#

does anybody know a good way around this

#

i kinda need this

#

or a similar system

#

basically to have a root item struct that other item types can inherit from and implement their own additional parameters depending on what that type of item needs

#

but is still transferable over the network and could still be stored generically in one array or list or whatever together

#

im racking my head and cannot figure out a way to get around it

#

is it just fundamentally impossible

#

really annoying if thats the case

#

like obviously its possible to just go and make new struct types for each new kind of item i want but for organisation purposes that is incomprehensibly stupid and a nightmare to maintain

#

i guess fundamentally the question is, is it possible to intentionally use a non-fixed data type within data that needs to be transferred over the network

#

this is netcode for gameobjects btw

rotund pilot
#

NativeArrays may be the only way to implement what im describing

#

but it seems even those need hard-coded sizes from before runtime

junior sleet
#

Maybe someone has resources on that? I can't find project examples for Netcode for GameObjects in a P2P topology. I can only find examples for client-hosted listen servers.

severe briar
# junior sleet Maybe someone has resources on that? I can't find project examples for Netcode f...

I don't think that, P2P is possible in anything but data/file transfer.
Games usually have a server - source of truth and clients.
Clients send a request to the server and the server validates it.
After validation server sends a response back to the client(s).
Otherwise, it would be a mess, because each of the clients would be the source of truth.
They will send whatever they want to other clients and other clients would do the same thing.
You won't be able to validate and sync anything.

severe briar
junior sleet
indigo sage
#

Hello, I need to know if I'm doing this right:

I have a player prefab with two attached scripts, MovementBehaviour and FireBehaviour, where FireBehaviour responsibility is to detect the fire input and perform the action, which should be stop all the character movement, rotate towards fire destination, perform the fire animation and wait for it to finish (which is a snowball-throwing like anim), enable movement again.

This is what I have so far in the FireBehaviour script:

private void Update()
    {
        if (!IsOwner) return;
        if (gameInput.Player.Fire.WasPressedThisFrame())
        {
            NetworkObject.gameObject.GetComponent<CharacterMovement>().LowerMovementSpeedServerRpc();
            NetworkObject.gameObject.GetComponent<CharacterMovement>().RotateAndLookTowardsMousePositionServerRpc();
            ThrowSnowballServerRpc();
            NetworkObject.gameObject.GetComponent<CharacterMovement>().RestoreMovementSpeedServerRpc();
        }
    }

Is it okay to do it like in steps/different rpcs? Or should it be a more composite action? As far as I understand, rpcs are reliable by default so order should be fine

Any advice on this would be grateful, thank you!

severe briar
severe briar
south palm
#

I'm using this code to spawn bullets in a Netcode for Gameobjects multiplayer fps

    [ServerRpc]
    private void ShootServerRpc()
    {
        GameObject new_bullet = Instantiate(bullet);
        new_bullet.GetComponent<NetworkObject>().Spawn(true);
        new_bullet.transform.position = transform.position;
        new_bullet.SetActive(true);
    }
#

and on the host's side it's fine
but when the client spawns a bullet, it spawns at the host's gun and then zooms over to the client's gun
i didn't even code bullet movement yet, so I suspect it's interpolating or something
any ideas why this might be happening?
bullet prefab has a network object and a network transform component

gloomy gull
#

i need a paper/description on transform predictions over a network.... or whatever it's called to hide rubberbanding, etc...thanks
specifically in realtion to a space dog fight simulation

#

any recommendations?

gloomy gull
#

GameObject go = Instantiate(myPrefab, Vector3.zero, Quaternion.identity);

#

oh and set the transform position before spawn

#

GameObject new_bullet = Instantiate(bullet, transform.position, Quaternion.identity);

south palm
#

yeah setting it before spawn fixed it, thanks

gloomy gull
#

w007

white ledge
#

is there any package Unity offers for WebSockets management like creating and sending/receiving requests?

severe briar
teal cedar
#

So weird this netcode

#

When player netcode has effect and it is active then other players can see

#

But when inactive then later activate it then no one can see except owner

severe briar
teal cedar
severe briar
# teal cedar Oh, it needs to be set through rpcs right?

I can't tell without seeing the code.

[ServerRpc]
void SpawnEffectServerRpc()
{
var instance = Instantiate(effect);
instance.GetComponent<NetworkObject>().Spawn();
//Spawns on the server and replicate to the clients
}

[ClientRpc]
void SpawnEffectClientRpc()
{
var instance = Instantiate(effect);
//Spawns locally on the clients
}

Sorry for formatting, tab stopped working in discord

digital vine
#

Hi guys, quick question. Does anyone know the code line to open steam's invite friends menu to your lobby? using steamworks

#

i've tried

SteamFriends.ActivateGameOverlayInviteDialog(lobbyID);

but it just opens the overlay without the invite menu

#

am i using the wrong lobby ID?

teal cedar
severe briar
severe briar
digital vine
rotund pilot
# severe briar Can you elaborate? Like, what data are you trying to sync?

im making a game where rooms have furniture that are sent from a server to a client, and vice versa. The rooms themselves are predetermined from a set list of models, but they have furniture which isn't predetermined.
This furniture has a bunch of different types that need different parameters associated with them. There's some things that they all have, e.g. position, rotation, etc. But, there are some category-specific parameters, e.g. boolean for the state (on/off) of lamps, string for text on a note, or (in a more extreme, but will be required, example) an image to go along with a picture frame.
if this wasn't all being networked, the obvious solution would be to just create a base furniture class and then go to town with polymorphism, but that's not an option here, and I'm trying to find an alternative.
I have 2 ideas I would know how to implement:

  1. Create one giant furniture struct that stores the category of furniture, and a bunch of parameters of different types for any kind of furniture to utilise if they need it. This sounds wildly inefficient, and i also hate it out of principle.
  2. Create a furniture struct with all the data that every furniture catagory needs to implement, and then create a bunch of new structs that all store a copy of the base furniture struct as a parameter, then create code to interpret every kind of new struct i make. This is what I am currently trying to implement, and while I still don't love it, it's way better than that other option.

For both of those solutions, I would still need to create a script that somehow splits an image up into packets and sends those over RPCs or something as well, which is then reconstructed on the receiver end somehow. I have no idea how to do that, I pray there are usable resources online to get that done. (kinda wish this was possible with netcode for gameobjects already considering it's meant to be a high level networking solution)

Solutions I don't know how to implement are a little wacky. One option would be to just completely ignore the struct idea, find some way to serialise those furniture items together as a group into raw data which I can somehow send over the network as packets, and reconstruct that on the other end, but that wouldn't lend itself to asynchronousity in loading very well, feels extremely complicated and it might also bad practise.
Another could be some sorta supported array type that allows for non-fixed lengths, like an array of binary data that could vary in size depending on how much data it needs to contain, but from what I understand, all structs sent over the network need to have a defined size before runtime.

So the question I suppose is how do I implement a better solution here? What's best practise? I've done much googling and haven't gotten very satisfying results, so any help is greatly appreciated

#

thank you so much for showing interest guys, i was afraid my problem would be too difficult for people to bother lmfao

rotund pilot
#

the idea is to do server-client, but for right now retaining host-client functionality would be nice, however it's definitely not necessary if it changes the solution to my problem

#

i definitely gave myself a huge headache trying to figure this all out the day before yesterday