#archived-networking

1 messages · Page 8 of 1

candid maple
#

is tcp a good protocol?

olive vessel
#

Well it's existed since '74 and it's still widely used so

sharp axle
forest grotto
woven kiln
#

stream.ReadPackedUInt(StreamCompressionModel.Default)

can`t readpackedint read the value 0 using 1 bit?

#
    {
        bool result = true;

        if(value == 0)
        {
            result &= writer.WriteRawBits(0, 1);
        }
        else
        {
            value <<= 1;

            value |= 1;

            uint buffer;

            do
            {
                buffer = value & 0x7F;

                value >>= 7;

                if (value > 0)
                    buffer |= 0x80;

                writer.WriteRawBits(buffer, 8);
            }

            while (value > 0);
        }

        return result;
    }

    public static uint ReadVarUInt(this ref DataStreamReader reader)
    {
        uint value =  reader.ReadRawBits(1);

        if(value == 0)
        {
            return 0;
        }
        else
        {
            value = 0x0;

            uint buffer;
            int shift = 0;

            buffer = reader.ReadRawBits(7);

            buffer <<= 1;

            value |= (buffer & 0x7F) << shift;

            shift += 7;

            while ((buffer & 0x80) > 0)
            {
                buffer = reader.ReadRawBits(8);

                value |= (buffer & 0x7F) << shift;

                shift += 7;
            }

            value >>= 1;

            return value;
        }
    }

    public static bool WriteVarInt(this ref DataStreamWriter writer, int value)
    {
        uint zigzag = (uint)((value << 1) ^ (value >> 31));

        return WriteVarUInt(ref writer, zigzag);
    }

    public static int ReadVarInt(this ref DataStreamReader reader)
    {
        uint value = ReadVarUInt(ref reader);

        return (int)((value >> 1) ^ (-(int)(value & 1)));
    }```

i have created this and has much better compression than unity native (and much faster)
#

ReadPackedUInt(StreamCompressionModel.Default) is only good for really small numbers (like 1, 2, 3, 4, 5). More than this and it is wasteful

ember kettle
#

hey so right now im spawning something on the network and assigning its position right away, but in the client it shows the item spawning in the center of the world and then flying to the assigned position due to the latency. it works properly in the end but it looks terrible lol. is there a way to spawn something on the network with an assigned spawn position so this doesnt happen?

#

oh wait im dumb, i just had to set the position to the instance of the object before spawning it 😭😭😭

wispy arch
#

Anyone know how I can get around sending a Client RPC that isnt Serializable Values to the clients?

Essentially I Spawn a Loot Drop from a dying Enemy and Assign its Item from its loot table. Ofc it works server side but I don't know how to get said Data across to the clients.

public void SpawnLootDrops(ulong player)
    {
        GameObject loot = Instantiate(
            _pickupObjectTemplate,
            this.gameObject.transform.position,
            Quaternion.identity
        );
        loot.GetComponent<NetworkObject>().SpawnWithOwnership(player);
        Pickup itemPickup = loot.GetComponent<Pickup>();
        itemPickup.item = _lootDrops[Random.Range(0, _lootDrops.Count)];
        SetLootClientRpc(itemPickup, itemPickup.item);
        itemPickup.SetSprite();
        loot.GetComponent<Rigidbody2D>()
            .AddForce(new Vector2(Random.Range(-5, 5), Random.Range(10, 15)), ForceMode2D.Impulse);
    }

    [ClientRpc]
    private void SetLootClientRpc(Pickup itemPickup, Item item)
    {
        itemPickup.item = item;
        itemPickup.SetSprite();
    }

Bascially like this, yes I know the bottom method doesnt work. That's what I would like to get working

ember kettle
#

apart from those two, you can only really send basic data types

wispy arch
ember kettle
#

yea sure

wispy arch
#

I think im just stupid. I'm trying to wrap my head around how this will even help me though. I pass the reference of the Servers Object, but how am I going to be able to set the clients.

#
    public void SpawnLootDrops(ulong player)
    {
        GameObject loot = Instantiate(
            _pickupObjectTemplate,
            this.gameObject.transform.position,
            Quaternion.identity
        );
        Pickup itemPickup = loot.GetComponent<Pickup>();
        lastSpawnedLootItem = itemPickup;
        itemPickup.item = _lootDrops[Random.Range(0, _lootDrops.Count)];
        NetworkObjectReference networkObjectReference = new NetworkObjectReference(loot);
        SetLootClientRpc(networkObjectReference);
        itemPickup.SetSprite();
        loot.GetComponent<NetworkObject>().SpawnWithOwnership(player);
        loot.GetComponent<Rigidbody2D>()
            .AddForce(new Vector2(Random.Range(-5, 5), Random.Range(10, 15)), ForceMode2D.Impulse);
        lastSpawnedLootItem = null;
    }

    [ClientRpc]
    private void SetLootClientRpc(NetworkObjectReference lootReference)
    {
        if (lootReference.TryGet(out NetworkObject lootObject))
        {
            lastSpawnedLootItem = lootObject.GetComponent<Pickup>();
        }
    }```
timber blaze
#

Hey guys, Just getting started with NGO, trying to port a project over from Photon PUN... Just wondering, how would you go about setting and sharing player data?

For example, Let's say I want to display the player's Display Name, profile image etc... Where is the best place to store and retrieve that data during a multiplayer game?

I'm also using the Lobby service, where I can store such information in the Player's custom data... just not sure how to associate which players in the game are which in the lobby

dapper plover
#

should i send timestamp or frame number?

sharp axle
sharp axle
dapper plover
#

i don't even know lol

timber blaze
timber blaze
#

Right... and I guess I'd have to store the "OwnerClientId" in the player data in order to associate each client with their corresponding player object?

sharp axle
timber blaze
#

And make that a network variable?

sharp axle
dapper plover
#

how to add simulated lag/packet loss to com.unity.transport

zenith crescent
#

using photon pun 2 how can i get players view id from the playerlist

still moat
#

This the place to ask about netcoding, and creating network objects and syncing player data?

still moat
#

I made a player object prefab that tracks the mouse and I setup the Network Manager and had an outside client connect so the Server is working its more the coding portion IM very beginner. I was able to get both mice tracking on both client and host. THE ISSUE: I made a card game in "singleplayer" ie no networking just input from the player, I watched a couple videos on Netcode for Game Objects and found the RPC docs. The HOST can move the deck and syncs movement on both client and host, the issue is the CLIENT either doesnt seem to have permission, or the server is not recongizing the input. Ive tried a bunch of different ways Client Network Transform/ Network Transform switching the two. Adding ServerRpc/ClientRpc Commands to the Decks script that they call the function that handles the movement but then I get a disconnecting error when the client joins. Any help would be greatly appricated, Im very new coding in general.

sharp axle
# dapper plover how to add simulated lag/packet loss to `com.unity.transport`
median wolf
#

Does anyone else have any issues with relay ?

#

Joining a relay allocation works sometimes

#

Other times I get this error Error joining relay allocation: Not Found: join code not found

#

Does relay cache allocations or something throwing an error if trying to join an allocation that you are already joined?

#

This error seems to arise when I leave the lobby on a client and try to rejoin it. Lobby callbacks show the player is leaving the lobby no problem

sharp axle
zinc marten
#

Is relay down? I connect and then it immidiately freezes and kicks me out with those messages

sharp axle
zinc marten
#

I tried 2 different projects and i get the same issue when it was working 20 mins ago

#

Okay nevermind something else is going on here. mb relay seems fine

dapper plover
#

man i don't know where to start

#

@sharp axle ok. thanks

dapper plover
#

@sharp axle do you have Multiplayer Tools installed? it's not working for me

#

installed 2022

wispy arch
#

Anyone know of a way to fix the teleportation of respawning enemies for clients

#

I try setting the position of where they should respawn before setting the GO active and multiple other things but they still fly across the screen and hit the player

sharp axle
wispy arch
#

Trying it on the RPC but still isnt helping

#
[ClientRpc]
    private void ReviveEnemyClientRPC(NetworkObjectReference enemy, int spawnLocation)
    {
        if (enemy.TryGet(out NetworkObject enemyGO))
        {
            NetworkTransform enemyTransform = enemyGO.GetComponent<NetworkTransform>();
            enemyTransform.Interpolate = false;
            enemyGO.transform.position = spawnLocations[spawnLocation].transform.position;
            enemyGO.gameObject.SetActive(true);
            enemyTransform.Interpolate = true;
            enemyGO.GetComponent<MoreMountains.CorgiEngine.Health>().Revive();
        }
    }
sharp axle
wispy arch
#
    private IEnumerator RespawnTimer()
    {
        while (true)
        {
            var respawnEnemy = GetPooledEnemy();
            if (respawnEnemy != null)
            {
                var waitTime = Random.Range(.5f, 1.5f);
                var randomSpawn = Random.Range(0, spawnLocations.Count);
                NetworkTransform enemyTransform = respawnEnemy.GetComponent<NetworkTransform>();

                yield return new WaitForSeconds(waitTime);

                enemyTransform.Interpolate = false;
                respawnEnemy.transform.position = spawnLocations[randomSpawn].transform.position;
                respawnEnemy.SetActive(true);
                NetworkObject networkObject = respawnEnemy.GetComponent<NetworkObject>();
                if (!networkObject.IsSpawned)
                {
                    networkObject.Spawn(respawnEnemy);
                }
                enemyTransform.Interpolate = true;
                respawnEnemy.GetComponent<MoreMountains.CorgiEngine.Health>().Revive();
                ReviveEnemyClientRPC(networkObject, randomSpawn);
            }
            else
            {
                yield return new WaitForSeconds(1);
            }
        }
    }

    [ClientRpc]
    private void ReviveEnemyClientRPC(NetworkObjectReference enemy, int spawnLocation)
    {
        if (enemy.TryGet(out NetworkObject enemyGO))
        {
            enemyGO.gameObject.SetActive(true);
            enemyGO.GetComponent<MoreMountains.CorgiEngine.Health>().Revive();
        }
    }
#

So i removed the Transform stuff out of the RPC and put it in the Main function. Still doesn't seem to work for the client. When it spawns it comes back right where it died and then flies to the correct location

sharp axle
wispy arch
#

ooof , is there another way than that?

#

Cause id have to turn off collision and whole bunch of other stuff too

#

I thought the ClientRPC would allow me to set its Position

#

So it would automatically match the Server

#

wait

#

what if i turn off network transform and set the position and then turn it back on

#

ima try that

#

Nope didnt do anything lol

sharp axle
# wispy arch ooof , is there another way than that?
wispy arch
#

Im essentially doing the same thing but a really dumbed down version

dapper plover
#

i've never blanked this much on something programming related

wispy arch
#

No matter how much I fiddle with this it doesn't work

dapper plover
#

what's the model called where the server looks at old data to determine if a client's shot hit someone?

#

god this stuff is complicated

median wolf
sharp axle
median wolf
#

lookup Client server reconciliation and interpolation

sharp axle
#

You'll need to figure out exactly what the clients need to know according to your game design

timber blaze
#

Hoping someone can help me with this.. I'm trying to manually spawn my palyer object... the docs say to use GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId); but If I run this on the client (so that the client can spawn their own player object) I get an error saying that Client's can't spawn objects

sharp axle
timber blaze
#

OK great. makes sense

dapper plover
#

should i be sending packets in LateUpdate() ?

unkempt nexus
#

Hey everyone, another 'teleport' question...

#

I spawn a clientnetworktransform on the host, it's controlled by anotherplayer... on spawn it interpolates from 0,0,0 to where it's suposed to spawn, i try to 'teleport' it but it throws me an error: 'Teleporting on non-authoritative side is not allowed' - is there no way to do this ? - i tried this from the host, from the owner, - i then tried changing the clientnetworktransform to a networktransform, and i keep getting the same error. Anyone can shine some light in this ?

sharp axle
unkempt nexus
#

Ty for the reply

#

Where do you set the CanCommitToTransform bool ?

sharp axle
regal oar
#

Hey so I am planning on making a very small multiplayer game and I was wondering if I should go with photon or fishnet. Photon fusion looks really easy to work with but I have heard the fishnet can support more ccu so I’m trying to figure out which one to go with. I was wondering what are some pros and cons of both of them and which one a complete beginner to networking should choose. Thanks!

median wolf
#

How do people handle the host disconnecting ?

#

or even a client disconnecting for that matter

#

but client side

#

im having trouble finding a callback for the timout within network manager

#

ive tried using unity multiplayer tools to simulate a network error and nothing happens

#

Lobby continues to ping on the server with no exceptions

#

The only time i can make an exception throw to handle a client disconnect client side is when the internet connection is straight up turned off. Then transport throws an error that im able to capture

#

How does one tap into the timeout/ping of network manager

wet compass
#

is there a way to pass a reference to a networkbehaviour via serverrpc?

#

is my best bet to pass its NetworkObjectId?

wet compass
#

thanks a bunch

sharp axle
zenith crescent
#

https://hastebin.com/ofetigoviz.cpp

hi so i am having a little bit of trouble, i have a script called instantiate players which instantiates them across then network then sets there view id in a list and randomly assigns a tag, and this script works great, but im having a problem with is the EnableUi script is suppost to just simply wait 3 seconds when the scene loads and then activate a ui for 3 seconds depending on the tag which was set in the previous script, but when i run the game all of the clients see the UI HiderUI. and unity is setup perfectly both are disabled and the script is on the gameobject

#

im using photon pun 2 btw

woven kiln
#

I can`t build game with dots

#

```PackageCache\com.unity.transport@fe9ce94216\Runtime\Utilities\ManagedCallWrapper.cs(22,16): Burst error BC1099: Calling conventions other than 'C' are not supported for calli. Found: Default

at Unity.Networking.Transport.ManagedCallWrapper.Method(void* functionPtr, void* arguments, int argumentsSize) (at .\Library\PackageCache\com.unity.transport@fe9ce94216\Runtime\Utilities\ManagedCallWrapper.cs:22)
at Unity.Networking.Transport.ManagedCallWrapper.Initialize() (at .\Library\PackageCache\com.unity.transport@fe9ce94216\Runtime\Utilities\ManagedCallWrapper.cs:31)

#

have this error

#

how do i fix it?

woven kiln
#

Is it possible to fix if i fork the main repository of unity.transport?

weak plinth
#

Just a quick question so I'm clear on this: collision detection is purely server authorative by default right? So callbacks like OnTriggerEnter and OnCollisionEnter are only computed on the server?

sharp axle
craggy sand
#

Hi! Is there any package for DOTS netcode profile like NetStatsMonitor or something like this? As I understand multiplayer tools package is for game objects only

dapper plover
#

any resource on where to read and write packets? FixedUpdate() vs Update() vs LateUpdate()?

sharp axle
dapper plover
#

hm ok. thanks. i already went through one tutorial

woven kiln
compact shuttle
#

How do I teleport the player with NetworkTransform (which is client authorative).
The player moves using CharacterController

#

Client Authorative network transform

public class ClientAuthorativeTransform : NetworkTransform
{
    protected override bool OnIsServerAuthoritative()
    {
        return false;
    }
    
    
}

and player controller

    private ClientAuthorativeTransform networkTransform;

    public override void OnNetworkSpawn()
    {
        // Check if local player spawned
        if (!IsOwner) return;
        // get client authorative transform and teleport
        networkTransform.Teleport(new Vector3(0, 0, 100), 
                Quaternion.identity,
                transform.localScale);
    }
#

The player does not seem to teleport.

#

Upon further inspection I get an error with content being Exception: Teleporting on non-authoritative side is not allowed!

sharp axle
compact shuttle
#

Awesome.
This worked.

    private IEnumerator Teleport()
    {
        yield return new WaitForEndOfFrame();
        networkTransform.Teleport(new Vector3(0, 0, 100), 
            Quaternion.identity,
            transform.localScale);
    }
#

Cheers! ♥️

#

But I'm guessing doing a custom network manager would be much better than Unity's standard one.

#

That is so strange though, that you have to wait a frame for ownership to change after NetworkSpawn

dapper plover
#

Null is supposedly "unreliable", but I can't find how to make a reliable packet

olive vessel
dapper plover
#

oh interesting that's a diff site

olive vessel
#

Well I am on the docs site for Unity Transport

#

Passing in null likely uses the default values given a struct cannot be null

#

Whatever .Null is will be some set defaults

dapper plover
#

ok, i see

#

thanks

dusty narwhal
#

Question: I am working with the netCode package for multiplayer. I put the player prefab into the networkManager, But it creates the instance of the prefab at (0,0,0) but the transform position of the prefab is elsewhere. I'm not sure how I fix this
Edit: I got it. just had to override the at onnetworkspawn: public override void OnNetworkSpawn(){

dapper plover
#

@olive vessel I copy/pasted this code from https://docs-multiplayer.unity3d.com/transport/current/pipelines/index.html#use-the-reliability-pipeline:

m_ServerDriver = NetworkDriver.Create(new ReliableUtility.Parameters { WindowSize = 32 });
m_Pipeline = m_ServerDriver.CreatePipeline(typeof(ReliableSequencedPipelineStage));

and it's saying the first line is Obsolete

olive vessel
dapper plover
#

@olive vessel ok thank you very much

#

lol i think i found the answer in the 3rd latest post

#

(nvm) that wasn't it

dapper plover
#

got it

modest solstice
#

hey I'm trying to give someone a playfab item through script, anyone know how to do that?

woven kiln
#

Does anyone has a good crc32 for burst? with SIMD?

red kindle
#

Hi, what's the best way to do multiplayer for a 2d soccer game that will fit 16-32 people?

woven kiln
red kindle
woven kiln
#

You can do local multiplayer if you want

#

or peer to peer

#

it will use one of the peers as server but players can host too

red kindle
#

Will I be able to add a search engine for such servers?

woven kiln
#

a matchmaking?

#

yes, but it is not part of netcode for entities

red kindle
#

So i would need a script?

woven kiln
#

yes

red kindle
#

okey, thx

zenith light
#

Hi, just wondering, is UnityEngine.Networking package still around?
I'm using mirror networking and I'm trying to use synclist to sync structs with 2d arrays in it.
From searching online, mirror can't sync arrays and needs to use NetworkArray<> from UnityEngine.Networking.
After trying the method, it says NetworkArray namespace can't be found and I can't find where to add the networking package.
How to solve this problem or are there any workarounds?

austere yacht
sharp axle
zenith light
#

Is it recommended to use netcode or mirror?

still moat
#

If I made a game in singleplayer and I want to make it multiplayer, do I have to make two versions of the same script? one that handles singleplayer and one that is networked?

#

For example playermovement, does the game object need to have two scripts one for monobehavior and one for networkingbehavior?

austere yacht
austere yacht
austere yacht
still moat
#

I built it from the ground up as singleplayer, its a card game so the movement is just based on weather or not the user is clicking and holding on the card. I got the network manager setup and added player objects and those seem to work, I can start the Host join as a client. The Host can move the cards and it updates to the clients, but none of the client movement is coming over.

austere yacht
#

You will end up rewriting everything if you started with no provision for multiplayer needs

still moat
#

Would it be possible to attach another movement script to the game object that uses serverRPC and calls the functions with the script that is actually handling the movement?

austere yacht
#

in theory you can patch individual parts to work over a network but this will become an unholy mess really fast

#

so if you plan to add multiplayer to anything like an actual game (complexity wise) you need to rewrite most parts to not melt your brain

#

Often enough you also will find that your (single player) game can’t realistically be a multiplayer game (design wise)

zenith light
still moat
sharp axle
still moat
#

Im very confused now, this my understanding. 1. Make a game object 2. Assign a script that allows the user to move the object around by clicking and holding with their mouse. 3. Add a network Object script to game object. 4. Prefab the object. 5. Assign the prefab in network manager. This is where Im confused. 6. Somehow call that network object from another script and instantiate on the server instance. 7. Test. I am thinking I am going wrong at step 2 or step 6. Or all of them. When I make the script do I have to start with it being Networked Behavior?

sharp axle
still moat
#

THANK YOU, I dont know why that isnt first thing that pops up when looking for anything Unity, Netcode.

#

Thats excatly what I was looking for!

sharp axle
#

That particular page was just added today, lol

still moat
#

Sweet, ChatGPT sorta hits it wall when I got to networking because from what I read Netcode for Game Objects came out in 2022 but ChatGPT only knows up to 2021.

dapper plover
#

is it possible to sync a variable between all clients and the server?

#

that represents milliseconds since the game started

dapper plover
#

thanks. i don't think i'll do it anymore

regal oar
#

Should I build my game first and then convert it to multiplayer or build my game with multiplayer?

sharp axle
regal oar
sharp axle
#

That would be easiest, yes

regal oar
still moat
#

Glad it was only the base of the game (90%) but now I wont get farther and be like welp

olive vessel
#

Well using ChatGPT to make any sort of code is likely a bad idea

#

When it was first released, we saw so much code that either didn't compile or crashed Unity

sharp axle
#

ChatGPT is just good enough to fool you into thinking it knows what its talking about.

regal oar
still moat
still moat
zenith crescent
#
using Photon.Pun;

public class EnableUI : MonoBehaviourPun
{
    public GameObject hunterUI;
    public GameObject hiderUI;

    private void Start()
    {
        if (!photonView.IsMine)
            return;
        if (gameObject.tag == "Hunter")
        {
            hunterUI.SetActive(true);
            Invoke("DisableHunterUI", 5f);
        }

        if (gameObject.tag == "Hider")
        {
            hiderUI.SetActive(true);
            Invoke("DisableHiderUI", 5f);
        }
    }
    private void DisableHunterUI()
    {
        hunterUI.SetActive(false);
    }

    private void DisableHiderUI()
    {
        hiderUI.SetActive(false);
    }    
}

i need help this script is on each player object, and when it enables from another script using playerview.gameobject.getcomponent.enabled that gets each viewid from each player it runs but only displays on the masterclient, and i think its because all the players are instantiations of 1 prefab and every client has the same script i dont know how i can make this run on only the client who owns the gameobjects and the script. each player has there own HunterUI and hiderUI gameobjects but it wont enable them for the client only them master basically

#

using photon pun 2

royal cypress
#

anybody come across an easier way to call APIs from unity

#

i'm using web requests right now and its makin my head hurt lol

wet compass
#

is there a way to add a networkbehaviour on runtime to both clients and server? I am adding it locally at both places atm but idk if it is creating different ones as opposed to 1 "linked" networkbehaviour, additionally, is there a way to specify ownership when creating/adding a new networkbehaviour?

still moat
wet compass
#

I have a working project with server authoritative stuff, I am running into an issue though when trying to switch up / add network behaviours to my player object.

#

I am currently adding the networkbehaviour on server and then calling a clientrpc which adds the same networkbehaviour component on client side but it feels messy and running into some smaller issues which might not help in the long run

still moat
#

welp im out of answers

wet compass
#

kk ty though, ill read up a bit though to see if im missing something

#

to be more specific, i have an autoattack abstract class that inherits from networkbehaviour, and my player prefab has a reference to that and I'm trying to switch it up on spawned player

#

I'm considering designing it a bit different to work around that if I don't get it working smoothly

teal obsidian
#

It was banned from stackoverflow for giving repeatedly wrong answers and being extremely confident about those wrong answers

still moat
#

Im making a card game 😦

teal obsidian
#

So then learn how to write code using your brain

#

You're not doing yourself any favors

teal obsidian
#

You mean web APIs?

#

Then yeah web requests are your only option. Unless you want to write your own TCP mechanism in native C to do it with producing minimal garbage

woven kiln
#

Does anyone has a SIMD crc32 with burst?

wet compass
#

is there a way to set a networkobjectreference to null? sort of like its initial value? I would think it has an initial value of 0 at NetworkobjectId. Basically im using a networkvariable<networkobjectreference> as a syncd target and trying to set it to null. currently also have a networkvariable<bool> istargeting to use that to know when it is not targetting something, but id like to be able to handle it with only one var by setting networkobjectreference to 0 or null somehow.

wet compass
#

is there any specific reason why a serverrpc cant seem to use Resources.Load correctly?

wet compass
austere yacht
hot venture
#
[PunRPC]
    public void Damagee()
    {
        targetti.GetComponent<Player>().currentHealth -= attackDmg;                
    }

this is the RPC fonction

if (basAttackScript.spawnedArrow.transform.position == TargetCanvas.transform.position)
        {
            PW.RPC("Damagee", RpcTarget.AllBuffered, null);

            if (targetti.GetComponent<Player>().isDEATH)
            {
                score();
            }
            
            PhotonNetwork.Destroy(basAttackScript.spawnedArrow);
        }

I call the rpc here, it works but only i can see that targetti's currentHealth decreased. the other player who is targetti cant see the difference. Any help 😵‍💫

timber blaze
#

Anyone know how to serialize a NetworkList<T> when it is part of a custom network variable struct?

Using serializer.SerializeValue(ref MyNetworkListVariable) does not work

austere yacht
clever verge
#

hey
I am trying to connect to Netcode server hosted on a different system
The IP address in the Unity Transport is the public ip address
for the clients
but it fails to join
but when I have them on the same network
and give the local ip address
they connect
what am I doing wrong?

austere yacht
clever verge
#

@austere yacht oh

#

So basically the setup goes like

#

Multiplay is the hosting service

#

Matchmaker initializes a server instance

#

We connect to the IP port of this server instance

#

using Relay

#

and then

#

send rpcs using netcode o.o?

#

Im sorry for confusing you

#

I tried the different system approach to test out

#

remote connections

austere yacht
#

if the server is hosted in the cloud you don't need a relay

clever verge
#

ooh

#

how do I connect to the cloud instance then?

austere yacht
#

relay is only for host based multiplayer (one of the players is the server)

clever verge
#

The match maker gave me a

austere yacht
clever verge
#

multiplayassign with ip and port

#

but when i try to connect to this ip address, it doesnt do anything

#

i've hosted on it on unity's multiplay

austere yacht
#

technically then this IP should be a virtual machine with your server running

clever verge
#

yea

#

so I just do a unity transport connection to this ip right?

#

no need of using relay?

#

or do I have to do a createallocation like in the relay service

austere yacht
#

idk how unity cloud works specifically, but in theory, you should be able to connect directly, but maybe unity wants you to use the relay anyway

clever verge
#

alright thanks alot 🙂

#

i think i understand how it should be setup now

#

ty again 😄

austere yacht
#

in services like playfab it takes quite some doing (config/api wise) on the server before your clients can connect smoothly

clever verge
#

i tried photon fusion hosted on playfab multiplayer servers

#

was able to set it up

#

but wanted to try out unity's services as well

austere yacht
#

the complicated bits are in the dynamic provisioning of servers and security

#

you can make stuff 100x easier if you ignore security

clever verge
#

i feel(personally) that unity's ux was better than playfab

#

in updating a server and all

austere yacht
#

well, unity's is more targeted and newer

clever verge
#

yea

#

alright have a great day ahead 🙂

ashen mountain
#

What method or class do I use to check if a host/server is running on a said IP address ??

Using Netcode..

sharp axle
ashen mountain
olive vessel
#

Well that is the way of checking if you can connect

#

By connecting

ashen mountain
#

So something along the lines of
if (network.StartClient())

is the way you would check it?

sharp axle
#

basically, yea

ashen mountain
#

Okay that's funny to me for some reason..

Thanks for the help..

dapper plover
#

is it impossible to have 2 clients and 1 server running on one PC?

#

since the 2 clients both have 127.0.0.1 and same port

olive vessel
#

No, you can do that

#

That's the connection address, each client will have it's own port

wicked mural
#

How to fix this error ? (I'm using Netcode)

#

this happens when I change my IP to static

#

the port that is required is open

dapper plover
sharp axle
sharp axle
wicked mural
#

the port is open in the router

dapper plover
#

😕

#

can someone help me with client side prediction & server reconciliation ?

  1. Client applies user input, saves the frame number and new position into a dictionary, and sends the user input along with frame number to server
  2. Server applies the given user input, then sends back the new position and given frame number
  3. Client then does this: new position = current position + server position - frame number position
#

but in my game at the start the client position goes to infinity in a few seconds

storm summit
# dapper plover can someone help me with client side prediction & server reconciliation ? 1. Cli...

I don't quite follow your step 3, looks like a mixture of positions from various points? With client side prediction you don't need to apply anything from what you've received from the server if it all matches up, you just run your guy locally until you detect a difference with what the server has, then start the server reconcilliation.

I'll outline a general flow.

  1. Client applies user input. Cache the input + frame data (positions etc) on client side for this frame. Also send the input + current frame number to the server. Lets say it's frame 50 on the client. (Which is a probably a bit a head of the server, lets say server is frame 45)
  2. Server received this input for frame 50. When Server gets to frame 50 it applies input, saves the frame data and sends this back to Client.
  3. Client receives Server's frame 50 message (Lets say client is now at frame 55), compare this server data with what we locally cached on the client for frame 50.

If the frame matches there is nothing to do, we're in sync. Job done!

If the server frame and client frame at 50 have different data/positions then trigger a server reconcilliation!

Restore your objects state to that of Server Frame 50.
Now we need to run the client back up to frame 55 as that's where the client was and may have already send some more inputs to the server
Run through the cached frame data for each frame from 50 to 55, reapplying the inputs, if any for these frames again.

Hopefully you're back in sync again!

dapper plover
#

well i read it twice

#

sheeeet

#

can we go back to my number 3 (sorry)
frame 56 xyz = frame 55 xyz + frame 50 xyz from server - frame 50 xyz cached

#

feel like that didn't make any more sense

storm summit
#

ok i get that yeah.

#

if you're flying to infinity and its at the very start maybe one of those positions if coming out as NaN, havent cached anything, or recieved a server frame etc?

dapper plover
#

in ur example do u really keep track of the server's frame number?

storm summit
#

not sure what you mean? I dont store it anywhere, the server has no need to store old frames. It just sends the number with the frame message to the client so it knows what local frame to compare it against

dapper plover
#

I’m so bad at thinking about time

#

Time and family trees I just blank on

#

i think the only difference between what we do is step 3 - you "reapply inputs" (which i can't wrap my head around) and i try to take some kind of delta (which makes sense depending on my mood)

#

oh i think i found something!!

dapper plover
sharp axle
# dapper plover can someone help me with client side prediction & server reconciliation ? 1. Cli...

Welcome to this Unity Tutorial where we go over Determinism, Fixed Tick Rate, Client Prediction, and Server Reconciliation. Deterministic Programs and Fixed Tick Rate are more theory but really important to understand in order to implement Client Prediction & Server Reconciliation. I then go into how to code Client Prediction & Server Reconcilia...

▶ Play video
ashen mountain
austere yacht
# ashen mountain I wish there was more people who provide information and explain it like it does...

This is such an advanced topic that a little tutorial will never get you anywhere. The implementation will be so different from project to project that you need to be able to come up with solutions yourself, that means you need to work with different kinds of resources (conferences, papers) and cobble together ideas from scattered articles. Most of the publicly available info on the subject can be found in a few gdc talks and articles linked here https://github.com/ThusSpokeNomad/GameNetworkingResources

GitHub

A Curated List of Game Network Programming Resources - GitHub - ThusSpokeNomad/GameNetworkingResources: A Curated List of Game Network Programming Resources

timber pebble
#

is it hard to try and create a peer to peer multiplayer system?

sharp axle
timber pebble
sharp axle
timber pebble
timber pebble
#

awesome, thank you

sharp axle
#

It depends on your skill level and what you want to implement. But basic functionality is relatively simple

timber pebble
normal estuary
#

Does anyone know when OnNetworkSpawn() actually gets called for an object?

I have a strange situation where:

  • Most of my networking exists from the very first second of the game, with DontDestroyLoad on nearly everything
  • OnNetworkSpawned is correctly called for all objects (dynamic + in-scene). That (I think) is called once host starts (or client starts)
  • I call the classic NetworkManager.Shutdown method once everyone disconnects
  • This correctly stops the host and all clients (looking at the Unity inspector)
  • I boot up another game from my lobby + relay. Game is created, host is correctly started. All objects are still there and everything works as expected EXCEPT OnNetworkSpawned() is no longer called on my objects.

Anyone had similar experiences?

sharp axle
normal estuary
#

GlobalObjectIdHash is the same. The network object does not get destroyed or anything. Also, it's a prefab correctly assigned to the network prefab list. (so yeah, an in-scene placed prefab)

The only difference running it for the first time vs. the second time for this object seems to be first time round OnNetworkSpawn() is called for it, also making the Unity inspector thing look different, whereas second time around it's as if the fact the host is started is being plainly ignored by the object

normal estuary
# sharp axle For it to be called again on the host, you would need to reload the scene

When you say reload the scene, do you just mean switching to that scene again? Because I do that

So flow is:

  • Menu scene (everything there, nothing is "started"
  • Goes to game scene, everything is running correctly.
  • Players quit, everything gets stopped. Back to Menu scene
  • Goes to game scene again, network manager has host running, but this network object does not get OnNetworkSpawn() called at all, it just stays there just like it does in the menu scene
sharp axle
#

You are switching scenes on the host as well?

normal estuary
#
            NetworkManager.Singleton.Shutdown();``` in order
sharp axle
#

is that NetworkManager.SceneManagement?

normal estuary
#

Also, player prefab does not have any issues. it works correctly. the only issue is around this network object

normal estuary
#
    {
        NetworkManagerObject.Instance.DestroyObject();
        SceneManager.LoadScene(0);
    }```
sharp axle
#

that is what should be syncing sceneloading with the clients

normal estuary
#

omg 😄 didn't know this existed!! I'll definitely give it a shot

#

thanks so much!

normal estuary
#

I can confirm this worked!

Thanks a lot @sharp axle I also recommend the others check that out, as well as NetworkManager SpawnManager

subtle depot
#

private void Start()
    {
       camera = Instantiate(cam, player.position, player.rotation);
    }
    void FixedUpdate()
    {
        

        if (!IsLocalPlayer) return;

        if (!IsOwner) return;

        camera.transform.position = player.transform.position;   ```
#

heres part of my code for my network manager player prefab

#

when i spawn 1 camera for 1 player it works great

#

but when i make a second player the first camera breaks

#

not sure why as the camera should always be the one that it made

dapper plover
subtle depot
#

Camera camera;

    private void Start()
    {
        player = GetComponent<Rigidbody>();
       camera =  Instantiate(cam, player.position, player.rotation);
        camera.GetComponent<camera>().setplayer(this.gameObject);
    }
    void FixedUpdate()
    {
        

        if (!IsLocalPlayer) return;

        if (!IsOwner) return;

        camera.transform.position = player.transform.position;```` i have this and it works however theres 2 cameras, and both players see out of the most recent one
#
{
    GameObject player;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(player != null)
        {
            transform.position = player.GetComponent<Transform>().position;
        }
    }
    public void setplayer(GameObject p)
    {
        player = p;
        return;
    }
}
#

this is the simple camera function

#

theyre not even networkobjects idk how both screens can see it

sharp axle
wicked mural
#

How to connect via an external IP in netcode ?

#

I put the IP address 0.0.0.0, there are no errors, but the client cannot connect

sharp axle
dapper plover
#

maybe instead of packet latency i could use client frame number delta divided by 60hz tick rate

subtle depot
#
        if (transform.parent != null)
        {
            if (transform.parent.gameObject.GetComponent<movement>().dropbutton() && usable) //if the player that posseses this gun clicks Q and the gun is equiped
            {
                rb.constraints = RigidbodyConstraints.None;                                 
                rb.collisionDetectionMode = CollisionDetectionMode.Continuous;                //for collision
                transform.SetParent(null);                                                    //should remove the gun from the palyer but it doesnt work
                box.enabled = true;                                                           //collision stuff
                rb.isKinematic = false;
                StartCoroutine(turnoff());                                                    //cooldown on picking up gun
                rb.AddForce(Vector3.up * 200);                                                //little throwing effect
            }
        }```
#

how come I cant remove my gun as a child from my client player

#

it works fine with host player

#

I assume it is because it is a child of the client object, which doesnt have permission to edit hierarchy. not sure how to get around that though

versed lily
#

Hello - I'm getting started with Unity Netcode and could use some help understanding what the basic idea is. I'm working on a 2-player strategy card game.

In addition to the Player classes which are NetworkObjects, I've got a Game object that has a Network Object attached to, but itself does not inherit from NetworkBehavior. When I make a call on the Game object, it's not made on the corresponding Game object on the other connection.

How can I ensure that calls get made on each client's instance of the Game object; or, alternatively, do I need to use a different approach? Thanks!

sharp axle
sharp axle
versed lily
sharp axle
versed lily
#

so, this is a turn based game, so my gut says RPC is functionally going to be the way. But I guess I'm looking for a kind of more general understanding of how the flow is supposed to look. Right now I have a button that calls StartGame() on my Game object, and that does some stuff. Great.

One thing I notice is that, I keep on my Game object a list of all Players - in my onNetworkSpawn on the player object, it calls a method on Game that adds itself to that list. My host sees this - and I can note that my list of Players now has 2 (or more) clients - so that call is being communicated at least from the Client to the Host without any RPC magic or Networked variables...

sharp axle
versed lily
#

got it.

#

when I connect as a client, it's creating that Nth player object locally on the host, and that's the version that's communicating back to the hosts copy of Game. So it's only through the connection that that's happening on both sides (presumably by some under-the-hood RPCs I can't see?). So basically instead of calling StartGame directly, I need to invoke it through an RPC?

#

lol literally all i did was change it to [ClientRPC] StartGame_ClientRpc() and it works*. Amazing.

ionic wind
#

How to download Netcode for GameObjects?
I am trying to use the link provided in the guide however it says "Page not found".

Also, would it be recommended to use UNet (although deprecated) if I want a common solution for WebGL and VR platform?

olive vessel
#

No, there’s no good reason to use a deprecated old networking solution

mortal ivy
#

hii , can anyone tell me why my player is not comming when i start the game

sharp axle
mortal ivy
#

yes i have clicked on host and its say no dispay to show because no player is there and player has camera

#

if i directly put player prefab there instead of in netwok manager then it work fines

sharp axle
dapper plover
#

Harder to come up with lag compensation solution for projectile collision than raycasting

raven bear
#

Guys got a quick question, I have players able to SetTiles on a tilemap during runtime, can I spawn these on the network the same way as anything else or is there a different method

#

also if I have a world that is painted on a grid how do I sync it between clients

sharp axle
wooden ferry
#

Anybody knows Unity Netcode here? I am struggling with NetworkList sync. Somehow it breaks on client but only on first load. If I add 1 item to NetworkList on host, connect client and then increase value of that item it duplicates it on client. So client's list now has count 2. If I close the client and then connect again, it works fine. No idea why it's only happening on first client load and why NetworkList doesn't sync correctly.

ionic wind
sharp axle
ionic wind
#

Is there any updated documentation which I am missing since the website says there is no support for WebSockets and we have to implement it using third party libraries..

versed lily
#

unity Netcode, when I Start as a Host, am /I/ the server, or does it create a server and simultaneously connect me as a client?

sharp axle
versed lily
# sharp axle Host is both a client and the server

sorry just to clarify, I'm wondering if they can be understood as a singular entity. Like when I hit "Start Host" on one instance and "Start Client" on another, under the hood the other instance is connected TO the host, the host's instance IS the server instance; or does the game see it as 1 Server with 2 Clients attached?

sharp axle
versed lily
#

OK. it'll still run clientRPCs?

versed lily
#

and if I want to raise raise an event for the clients, the way to do that is to call a clientRPC method that invokes the event locally, I can't raise the event directly?

sharp axle
versed lily
#

thanks for all your answers! I have a ton more but don't want to overload you, i'm still trying to grok how to organize around this workflow and getting there little-by-little.

dark bough
#

Hi does someone ever use Lobby for unity ? i got an error trying to launch the sample

sharp axle
# dark bough Hi does someone ever use Lobby for unity ? i got an error trying to launch the s...

Check the readme at the top here. Lobby events are still in beta.
https://github.com/Unity-Technologies/com.unity.services.samples.game-lobby

GitHub

A sample showcasing a minimal implementation of a lobby experience using the Lobby and Relay packages. - GitHub - Unity-Technologies/com.unity.services.samples.game-lobby: A sample showcasing a min...

analog tundra
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System;

// Original code is from https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Post.html
public class AI_SQLTools : MonoBehaviour
{
    string url = "http://appticalillusions.com.linux318.unoeuro-server.com/addData.php";

    public IEnumerator AddSQLEntry(string _time, string _loudness)
    {
        WWWForm form = new WWWForm();
        form.AddField("time", _time);
        form.AddField("loudness", _loudness);

        using (UnityWebRequest www = UnityWebRequest.Post(url, form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log("Form upload complete!");
            }
        }
    }
}
``` I get a 406 error every time. How can I fix this?
brave bronze
#

👀 does photon only work when you're connected to the internet? (might be a very stupid question)

tired osprey
#

Ill preface this by saying Ive never worked on networking before
and im currently looking at learning fishnet, although im open to other suggestions
but the problem here is i dont quite understand some of the terminology
fishnet provides a networking solution, and as i understand it also an option to play the game locally
however, i dont quite understand how this network is constructed, is it a single global server?
or is it a server you can run on the same as machine your own client (LAN), or alternatively on a dedicated device (that has no client instance)?

take the example of a minecraft server, you can host a LAN game, play singleplayer or play on a dedicated server (which takes an individual to setup the server for his friends)
or is it more like a chatroom with a single global server?

i dont know if im making any sense here, please ask for further explanation if needed

cyan tiger
#

if the game im coding doesnt allow syncing transform does syncing int to getchild it later is actual best option?

versed lily
#

[UnityNetcode] When I put ClientRpcParams as an argument to a ClientRPC method, does the networking layer auto-sense this and restrict propagation to only the indicated clients, or do I need to test for that in the ClientRPC method myself? If it's done automatically, does ClientRPCParams need to be the Nth argument, or just anywhere in the list of args?

edgy tiger
#

Does anyone have a tutorial on round systems?

#

Specifically for photon

weak plinth
#

why is my networkanimator only playing the first frame of animations?

weak plinth
weak plinth
#

bump

still hare
#

did you forget to stop running your animator code on remote players?

weak plinth
#

Has anyone tried using netcode for gameobjects for a game that is playable both offline and online? It seems like using things like NetworkVariable offline is producing a number of warnings and errors, but I'd like to avoid having duplicate variables in my scripts to handle both modes.

#

Is there maybe a way for NetworkVariable to be usable offline without issues, or perhaps a better way to solve this?

weak plinth
still hare
#

they don't have an offline transport as far as I know

weak plinth
versed lily
#

the host can be localhost

still hare
#

you can start a host with no internet

weak plinth
#

oh perfect, that should simplify things quite a bit. Thanks!

versed lily
#

quick q - can a networkbehavior be passed as an argument in an RPC call?

weak plinth
still hare
#

if you do not have an understanding of how the NetworkAnimator syncs the animation state to players, you might have a setup that just does not work right now

weak plinth
weak plinth
still hare
#

is your server / client authority set up properly?

weak plinth
#

i also tried using [ServerRpc] over my activate animation method which produces the same result

weak plinth
#

nevermind yes it is working

#

i call AddPlayerForConnection when a player joins

still hare
#

I mean is your NetworkAnimator set to the correct sync mode (server authoritative / client authoritative)

#

if you are changing it on the client it should be client authoritative

weak plinth
#

it is set to client to server

still hare
#

I don't know how the NetworkAnimator works internally, but it could be that it just syncs parameters and triggers

#

so it really could be that your .Play is breaking it

#

could you swap your animation controller out for a new testing one and see if you can get it to sync with some simple parameters?

weak plinth
#

alright

still hare
#

Seems from the documentation like they want you to use parameters

versed lily
sharp axle
weak plinth
#

netAnimList[index].SetTrigger("Character Run");

#

gives me this error

#

Parameter 'Hash -1548500351' does not exist. UnityEngine.Animator:SetTrigger (int)

sharp axle
# weak plinth gives me this error

Because trigger properties have this unique behavior, they require that you to set the trigger value via the NetworkAnimator.SetTrigger method.

weak plinth
#

netAnimList[index] is a NetworkAnimator

sharp axle
weak plinth
sharp axle
weak plinth
#

but now i get this

#

NullReferenceException: Object reference not set to an instance of an object Mirror.NetworkAnimator.SetTrigger (System.Int32 hash) (at Assets/Mirror/Components/NetworkAnimator.cs:425)

sharp axle
clever verge
#

Hello, I am trying to understand how reconnection is supposed to be handled in a server client model

#

I have a PlayerPrefab, and on disconnection would like to preserve this spawned prefab

#

And upon reconnection, would like to assign it back to the original player

clever verge
#

Also an additional question

#

Do I set the player prefab in the network object and spawn/despawn it when player connects/disconnects? With the "Dont Destroy with Owner" enabled off?

#

Right now I was able to do reconnection in a very wonky way

#

Where I have a NetworkList<sting> with my unique ID and on joining the room I see if my unique ID already exists in the room

terse hedge
#

Hey guys, i was wondering how optimised unity netcode's racing game sample may be for mobile.

Anyone has an idea about it?

clever verge
#

If it does, I request the ownership for the old NetworkObject

#

This seems to be working but I feel there has to be a better solution or way to handle reconnections

clever verge
#

I have also integrated the lobby system for a private game. Once all players connect do I push them to a matchmaker queue called "PrivateGame" and then allocate the server? Or do I have another way to allocate and let only my lobby players to get in

sharp axle
dapper plover
#

I’m working on Lag Compensation and I ran into a problem. On the server I instantiate a “RewindHitbox” game object and then immediately shoot a Raycast. But the problem is apparently at least one FixedUpdate needs to run for a raycast to hit a newly moved object.

#

I might have found it

#

But that seems very expensive to do

sharp axle
#

That should work. Just remember that its just a reference and its not sending any data along with it

dapper plover
#

Debug.DrawRay is a little cool

cyan tiger
#

is it worth replacing ints with sbytes for networking

sharp axle
olive vessel
#

The answer for Anuked is probably no given what we know about the rest of the game...

#

I am terrified they're doing networking, yet not at all surprised

clever verge
timber blaze
#

Anyone know if there is a service within UGS suitable for storing public player data? I know that there is cloud save, but that seems more like private data like game saves or progress etc.

What I’m after is a place to store things like player display name, Elo ranking etc. and have it publicly accessible by other players in the game.

versed lily
#

Hi - question about multiplayer workflow. When my player does an action that affects the gamestate (say, sells a weapon at a shop - removing the item from inventory and adding the money, and adding the item to the shop inventory) I have it set up so that the player in the UI triggers a ServerRpc which does validation, checks any game rules, then applies the result to the server instance of the data. OK, great. What's the ideal method for syncing that data back to the player? (let's assume network vars are out). Is the common practice to have essentially a companion clientRpc to every serverRpc that receives the confirmed changes back from the server and applies them? ie I might have SellItem_ServerRpc(PlayerID, ItemID) as well as a SellItem_ClientRpc(PlayerID, ItemID) that is essentially identical?

timber blaze
versed lily
#

Cool, thanks. Yeah it's turn-based so I can fade seconds of lag if need be.

#

I kind of settled on a slightly different approach: the ServerRpc does it's things - in my case, usually manipulating lists - then sends back the full set. Then on the client side, I recalculate what items were added to the list and which were removed and then reexecute the data update.

#

a little pedantic for a game at most 4 people will ever play, but I figure, i'm learning.

timber blaze
#

Nice. I even go so far as to use a naming convention like:

RequestMethodName_ServerRpc
ReceiveMethodName_ClientRpc
ApplyMethodName

Call the server RPC from the client, who calls the client RPC who calls apply on whatever local scrip needs applying.

versed lily
#

oh I see yeah the apply method does your business end so it's identical and you don't need to repeat yourself.

versed lily
timber blaze
#

Well the host is a server and a client, so he can call the server RPC does the validation in your case and whatever logic you want to do there, then also gets the client RPC like everyone else. So if you’re doing the same logic inside the server RPC and inside the client RPC, then in the client RPC you would just check if !NetworkManager.Singleton.IsServer and then do the logic, that way you avoid the double ups

versed lily
#

so - even more simply: if the ServerRpc validates against it's own data, but then assumes that it will update itself in the ClientRpc call, so don't do any actual state change in the ServerRpc?

#

or to be able to switch back and forth (between server/clients or host/client), you only call that actual data change function in the serverRpc if it's not a client. otherwise assume the client will do it for you.

timber blaze
weak plinth
#

I'm making a 1v1 fighting game, currently there's only one scene that's the battle arena. I made it so that when one player dies, the scene gets reloaded with NetworkManager.SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);. This works, but I notice in the editor every time I load the scene another NetworkManager object is spawned under the DontDestroyOnLoad hierarchy. Is this something that doesn't matter, or should I be looking to change this? If there are problems having more than one NetworkManager in a scene, how would I go about fixing it so there's only ever one?

#

Perhaps instead of reloading the scene to begin a new round, I should just reset the player health and positions and begin a new round that way?

sharp axle
weak plinth
versed lily
timber blaze
sharp axle
hybrid berry
#

Hey all. I want to build my first multiplayer Unity game, but I'm struggling to find a suitable solution for a Unity game with a dedicated server. The game will be turn-based, so I'm not looking for the most performant solution - just some recommendations on a good entry point into multiplayer networking.

All of my experience with backend/frontend is through my career as a dev - so I've only ever used .NET/Node.js API's and HTTP for servers. I'd like to learn more about what the accepted Unity equivalent is for a dedicated server and where to deploy.

Thanks very much in advance 🙂

weak plinth
#

For anyone using netcode for gameobjects, how are you handling player spawning? My gut tells me I should have one object that represents the client (i.e. account data), and one that represents the player (i.e. their character), but the network manager seems to want players to only have 1 "player" object

sharp axle
woven kiln
#

Is anyone building a dedicated server with ecs?

versed lily
#

Can someone tell me why only the local function (the first one) - is executing and neither of the RPC calls - are getting made? The initial call to LogServer is being made by a client and I don't even see the results applied locally let alone along a network

#

also yes this is within a NetworkBehavior class.

clever verge
#

Hello could you create a private matchmaking queue using Attributes?

#

WIth no relaxation? I want people who have the attribute to join others with said attribute

#

basically i would like my matchamker to say something like

#

The roomcode of AllPlayers in the Match must be Equal to "1234"

#

The 1234 is entered dynamically

#

found it 😄

#

its in the equality rule check

#

ty

timber blaze
sharp axle
#

RPCs are not being called

sharp axle
acoustic torrent
#

Hello!
I'm reading the doc of NGO and I just unable to find any specification about recommended/max player per server counts written anywhere. I saw a unity vid (on official YT channel) saying it's recommended for 16 player (2-3 month old vid). Is it true?

What BattleBit remastered uses for handling like 254 player per server?

olive vessel
#

You'll find a point where you reach a bottleneck and maybe can't squeeze any more out of it

acoustic torrent
olive vessel
#

I believe Unity does frustrum culling in builds, so things off screen aren't rendered

errant heath
#

hey, I am pretty new to photon and I can't find out when I create my player it is not active in hierarchy
this is how i am creating my player

private void CreatePlayer()
{
GameObject player = _prefabPool.Instantiate("Player", Vector3.zero, Quaternion.identity);
player.SetActive(true);
}

#

I can also provide more info on this if required

livid wigeon
#

Hi, I'm trying to sync player movement in multiplayer using network variables instead of network transform. Anyone with any insight or tips? I'm using character controller and sending the input on the network variables but it's not very precise and the mirrors end on slightly different positions

sharp axle
# livid wigeon Hi, I'm trying to sync player movement in multiplayer using network variables in...
GitHub

A collection of smaller bite-size samples to educate in isolation features of Netcode for GamesObjects and related technologies. - com.unity.multiplayer.samples.bitesize/Basic/ClientDriven at main ...

weak plinth
#

here is the code of player:

using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;

public class CursorPlayer : NetworkBehaviour
{
    public TMPro.TMP_Text playerNameText;

    [SyncVar(hook = nameof(OnNameChanged))]
    public string playerName;

    [SyncVar(hook = nameof(OnColorChanged))]
    public Color playerColor;

    private void OnNameChanged(string old, string @new){
        playerNameText.text = playerName;
    }
    private void OnColorChanged(Color old, Color @new){
        playerNameText.color = playerColor;
    }

    [Command]
    public void SetupPlayer(string name, Color color){
        playerName = name;
        playerColor = color;
    }

    public override void OnStartLocalPlayer()
    {
        string name = "Player" + Random.Range(1, 999);
        Color color = Random.ColorHSV(0, 1, 0, 1, 0, 1, 1, 1);
        SetupPlayer(name, color);
    }

    private void Update() {
        if (!isLocalPlayer) return;
        
        playerNameText.gameObject.SetActive(false);
        Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = pos;
    }
}
hybrid berry
hybrid berry
sharp axle
hybrid berry
# sharp axle Unity has a Dedicated Server Service called Multiplay

This is what I'm leaning towards atm, but I'm unsure about a lot of things. Would you typically deploy the same project as a headless build, or a separate project entirely? & if you wanted to develop using a server on a local machine first to cut costs, what would look different code-wise between hooking up to Multiplay/hooking up to a local server? Appreciate if these q's are quite basic and/or dependant on the project, I'm pretty inexperienced

woven kiln
hybrid berry
hybrid berry
sharp axle
hybrid berry
sharp axle
hybrid berry
#

One more Q - if you use the same solution for both the server/client code, how can you make sure to keep all of the server logic separate from the client and vice versa? I've seen examples of people using directives and hash ifs everywhere - but that seems like it can get pretty messy.

weak plinth
sharp axle
#

though honestly it feels more trouble than its worth

hybrid berry
# weak plinth i dont understand wdym

Using player movement as an example:

Update()
  if (client)
    RequestMove()

RequestMove()
{
  // client does stuff
}

#IF SERVER
OnMoveRequest()
{
  // server does stuff
}
#ENDIF
weak plinth
#

how onmoverequest is being called? 😄

hybrid berry
hybrid berry
sharp axle
weak plinth
#

i'm have mirror networking as my networking library (is someone noticed tihs? 😄)

hybrid berry
weak plinth
#

how does rpcs works in networking

#

i'm newbie to mirror

sharp axle
#

clients call the ServerRPC, the server runs the ServerRPC. The server will call the ClientRPCs and the clients will all run them

hybrid berry
sharp axle
weak plinth
#

😕

hybrid berry
#

its just clicked

#

I had in my head both RPCs only existed in the docs because they were using P2P for the guides, so of course all clients needed the server RPCs

sharp axle
#

parameters are sent between the 2 as data

#

Technically, the clients only need the ServerRPC signature defined since they are not running it. But again more trouble than its worth trying to strip that out

hybrid berry
weak plinth
#

is this way to do movement? (im just looking for example)

#

dont care that this is not cde about mvement

sharp axle
sharp axle
weak plinth
hybrid berry
sharp axle
sharp axle
hybrid berry
sharp axle
#

lol, Networking is hard

hybrid berry
#

when you said the clients only need the ServerRPC signature defined, why would they even need that?

#

yeah man

#

its blowing my mind trying to get my head around it

#

not quite as straightforward as web dev

sharp axle
#

in PlayerMove(Vector3 direction), direction will get serialized and sent to the server

hybrid berry
#

oh, so it would look something like this in the case of 2 separate projects?

assuming this is the server:

[ServerRPC]
OnMoveRequest(ServerRpcParams request)
{
  // server does stuff
}

And then the client

Update()
{
  RequestMove(dir)
}

[ServerRPC]
RequestMove(Vector3 dir)
{
// empty?
}

[ClientRPC]
Move(ClientRpcParams response)
{
  // client does stuff once the server responds
}

am I getting that right for how the client/server would interact?

#

and in the case of server/client being on the same project, RequestMove would be replaced with OnMoveRequest, with additional checks for if build is the server

sharp axle
#

Basically. the Signatures will need to be the same so both the server and client would have
[ServerRPC] RequestMove(Vector3 dir, ServerRpcParams params) {}

hybrid berry
#

And RPCs have to make a call somewhere to the opposing RPC? what would you use for something event based?

#

sorry for picking your brain so much, you just know your stuff

sharp axle
# hybrid berry sorry for picking your brain so much, you just know your stuff

lol, no worries. I took almost a 6 month of banging my head against this during the beta to get my head around this.

For event type calls, you could either use empty parameter like [ClientRPC] StartMatch() or you could use Custom Messages
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages

hybrid berry
sharp axle
# hybrid berry cool, this is exactly the type of thing I was looking for. im really concerned a...

If you're feeling spunky then check out the Boss Room sample by Unity. But it is not for faint of heart. Its a bit too complex for me
https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture#clientserver-code-separation

hybrid berry
#

i'll give it a go - and likely come running back soon when I have no idea what's going on haha

hybrid berry
marble urchin
#

Greetings, I'm developing a multiplayer card game using Lobby and Relay. I want the host to be the "source of truth" for all the cards. It's a realtime multiplayer version of Solitaire (i.e. Dutch Blitz or Nertz) so it's not turn-based. Because players are playing to the same "foundations" I need to be able to have the "server" determine if plays are legal or not.

But just starting out, I want the server to initialize the cards for all the players. I've defined a PlayerCards class as follows:

public class PlayerCards
{
    public string PlayerId { get; private set; }
    public Suit Suit { get; private set; }
    public DrawPile DrawPile { get; private set; }
    public List<Card> DiscardPile { get; private set; }
    public TradingPile[] TradingPiles { get; private set; }
    public CastlePile CastlePile { get; private set; }
...
}

I am hydrating that in my GameManager's OnNetworkSpawn() method (for the host only) and I want to propagate it out to the clients. I'm wondering the best way to do that? Should I use a ClientRpc method and setup a bunch of serialization? Or is there a better way?

Thanks!

sharp axle
hybrid berry
drifting bobcat
#

Hey, noob here, right now my netcode syncs to clients once every second. I'm worried this is not enough for a fast-paced multiplayer game that is similar to smash-bros which i am making. Is there a way to either make netcode for game objects sync to the client faster or to negate this problem?

sharp axle
sharp axle
drifting bobcat
sharp axle
hybrid berry
sharp axle
bitter mango
#

Hey is this where i can ask about like setting up servers for multiplayer?

#

please @ me when you respond :)

formal hound
#

Hey y'all, quick question on if there are any lifecycle / order-of-execution reference diagrams for NGO? I've referenced the standard unity order of execution diagram on several occasions and it's really helpful. I'm not new to networking in games per se, but I am still getting started with NGO, coming from Mirror, though it's been a solid year or so since I have don anything with that even

#

if not, i can definitely continue to just sift through the docs. But thought it would be helpful to have. Google searches haven't turned anything up

formal hound
#

Yes! that is exactly what I am looking for, for the most part anyway, thank you. Can't believe I missed that Facepalm

bitter mango
#

Anyone aware of this error? getting it while following this video
https://youtu.be/KHWuTBmT1oI

A step by step guide to make your first VR multiplayer application with Unity and Photon.

▶ Get access to the source code: https://www.patreon.com/ValemVR
▶ Join the Discord channel: https://discord.gg/5uhRegs

Download the Hand Presence Unity Package :
https://drive.google.com/file/d/1xFBs6vA_p9EHLHcwjYIxGHcnHqatxJjz

TIMESTAMPS:

0:00 VR Set...

▶ Play video
formal hound
#

At what point in the video are you hitting the error? And are you trying to perform operations on the Client somewhere outside of the two callbacks mentioned in the error? Basically based on the error, you're trying to perform some kind of operation on the Client before it's ready and should move that logic to one of the callbacks mentioned in the error.

But if you're getting the error even after doing that or you're not trying to do anything to the client but still getting that error, then you'd probably need to provide more context and code samples

bitter mango
#

i presume its why my Oculus quest build and the Unity editor build didnt join a server together

#

is ther a way i can show the entire log?

formal hound
#

what does the stack trace say for that error?

bitter mango
#

sorry im unfarmiliar with the term

formal hound
#

it's the part of the unity console below the log messages. It should have a trace of where the error originated from and gives you file names and line numbers

#

^ the area in the orange border is the stack trace

bitter mango
#

Ah!

#
UnityEngine.Debug:LogError (object)
Photon.Pun.PhotonNetwork:JoinOrCreateRoom (string,Photon.Realtime.RoomOptions,Photon.Realtime.TypedLobby,string[]) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetwork.cs:1850)
NetworkManager:OnConnectedToMaster () (at Assets/NetworkManager.cs:29)
Photon.Realtime.ConnectionCallbacksContainer:OnConnectedToMaster () (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:4126)
Photon.Realtime.LoadBalancingClient:OnOperationResponse (ExitGames.Client.Photon.OperationResponse) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:2737)
ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback (ExitGames.Client.Photon.StreamBuffer) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:872)
ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:583)
ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1771)
Photon.Pun.PhotonHandler:Dispatch () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:226)
Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:145)
formal hound
#

can you paste your network manager script?

bitter mango
#
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;

public class NetworkManager : MonoBehaviourPunCallbacks
{
    // Start is called before the first frame update
    void Start()
    {
        ConnectToServer();
    }
    void ConnectToServer()
    {
        PhotonNetwork.ConnectUsingSettings();
        Debug.Log("Try Connect to server...");
    }

    public override void OnConnectedToMaster()
    {
        Debug.Log("Connected to server!");
        base.OnConnectedToMaster();
        RoomOptions roomOptions = new RoomOptions();
        roomOptions.MaxPlayers= 10;
        roomOptions.IsVisible= true;
        roomOptions.IsOpen= true;

        PhotonNetwork.JoinOrCreateRoom("Room 1", roomOptions, TypedLobby.Default);
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("Joined a room.");
        base.OnJoinedRoom();
    }

    public override void OnPlayerEnteredRoom(Player newPlayer)
    {
        Debug.Log("A new player joined the room.");
        base.OnPlayerEnteredRoom(newPlayer);
    }
}```
uncut bluff
#

hey guys any one had a problem were the canvas on the client position changes when it connects?

hybrid berry
#

got some q’s. for a turn-based card game, is there any real need for network prefabs? seems like a more intuitive way will just have the client handle any animations, and the server handle any state logic through network variables.

sharp axle
hybrid berry
sharp axle
hybrid berry
# sharp axle They will need a Network Object component though

yeah, makes sense. i’m wondering if i should be spawning every card through the server, though, to keep the server truly authoritative. but my instinct is to have the server tell the client to spawn a certain card as it’s drawn, and have the actual spawning done by the clients, who can then control the animations etc

sharp axle
flint scarab
#

hello

marble urchin
hybrid berry
#

im not sure what the code would look like given that I'm still planning things and experimenting with networking, but that would be my next go

weak plinth
#

From what I'm seeing on the forums, Unity recommends that you don't write to a NetworkVariable<T> before the OnNetworkSpawn event occurs. I'm finding this a bit tricky, in that I want to set the initial values of my objects before spawning them, which is giving me a bunch of warnings. Does anyone have a good solution for dynamic network initialization to get around this issue?

#

i'm so noob, that i can't event make chat

#

i have this every time trying to send message

#

and message is not adds to chat

#

here is code for sending messages to chat:

[Command]
    public void SendChatMessage(string message, string author){
        if (!chat) {
            Debug.LogError("Chat field is not assigned!\nMessage will not be delivered");
            return;
        }

        if (author == null){
            chatText += $"{message}\n";
        }
        else{
            chatText += $"<{author}> {message}";
        }

        chat.text = chatText;
    }
#

and here is code from chat input:

public class ChatInput : MonoBehaviour
{
    public SceneScript sceneScript;
    private TMPro.TMP_InputField input;

    private void Start() {
        input = GetComponent<TMPro.TMP_InputField>();
    }

    void Update(){
        if (Input.GetKeyDown(KeyCode.Return)){
            sceneScript.SendChatMessage(input.text);
            input.text = "";
            sceneScript.chat.gameObject.SetActive(false);
        }
    }
}
sharp axle
weak plinth
sharp axle
# weak plinth Does this event still exist? I'm seeing it listed in a couple places online but ...
GitHub

Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer. - com.uni...

hybrid berry
#

@sharp axle in the boss room architecture, the devs talk about the issues they had with trying to achieve client/server code separation (https://docs-multiplayer.unity3d.com/netcode/current/learn/bossroom/bossroom-architecture/index.html#clientserver-code-separation). They came to a lot of the same conclusions we discussed yday, such as asmdef stripping and ifdef classes not being worth the added complexity. They ended up using client/server classes, each with references to the other.

#

had a Q about how you might achieve that, wondering if you might have an idea. The devs mention "use partial classes when separating by context isn't possible". How could you do this without partial classes? Don't networkbehaviors need to have the same signature (ie PlayerController on both client and server, rather than ServerPlayerController on the server and then ClientPlayerController for the client)?

sharp axle
hybrid berry
hybrid berry
#

Are there any good resources for learning how to setup a very basic lobby/quickplay? The issue I'm having is my network is being initialised on application start. This means that everyone that connects is stuffed into the same server. Ideally, I want the server to always be running, but clients only connect when they're searching for a game. Is this the way to handle it?

#

Also: I'm aware multiplay has a lobby/matchmaking service that handles a lot of this, but that won't help me learn how they're handling it and I'd like to avoid costs until I'm confident I have a strong enough prototype ready 🙂

sharp axle
hybrid berry
#

how do games handle this in general? when you're first loaded in, you'll be on a server somewhere, for your account info etc. then when you join a game, what actually happens? is another server spun up just for that lobby?

sharp axle
#

The Unity Lobby service can be tested that way. The free tier is more than enough

sharp axle
hybrid berry
sharp axle
#

The relay service is the same but it will automatically pick the best region for your connection

hybrid berry
#

god that makes so much sense, ty

sharp axle
#

Lobbies have no concept of region. but that can be added to Lobby data if needed

hybrid berry
#

so really, when clients usually think of a game server being down, to a point where no-one can join a game or even log on sometimes - that wouldn't ever really be 1 individual server that's down. it's more like the whole fleet is offline?

sharp axle
#

Sometimes an AWS datacenter catches fire and takes out the entire east coast

hybrid berry
#

same for most major MOBAs or even competitive FPSs - most recently I remember OW2 having a pretty horrendous login queue.

sharp axle
#

Yea. Live service games are just the new MMO

hybrid berry
#

Not sure why I'm worrying about that - if I've ever got to a point where that's an issue, then I'll be breaking out the champagne lol

#

have never been very good at taking anything a step at a time

sharp axle
#

lol, its a good problem to have

hybrid berry
#

if I can't understand it all immediately, I give up

#

I'm still a little bit lost. Thinking about pretty much any game, once you've been authorised and logged in, you have access to, for example:

  • online friends online/offline status
  • in game shop
  • chat functionality
  • account management

some of these are inefficient to rely on a Rest API for - chat functionality for example. So, you're in a server somewhere, before you're actually in a game server. when you do actually enter a game, you still have access to some things that you had before - like chatting to friends that aren't in your game server. how does this kind of thing get handled?

sharp axle
hybrid berry
#

got to say I'm happy to hear it though, makes sense to me that it's all APIs. my head would have exploded if there was some sort of server-nesting, where you're both in a parent-server able to communicate with other people in your region and in a DGS when you're in a match

#

thanks again taku

#

feel like I've learnt more from you in the last couple of days than I have all year lol

sharp axle
#

I mean technically they are parallel servers just all in the Cloud. Its just that the Chat server, Lobby Server don't know or care about the Game Server.

hybrid berry
marble urchin
flint scarab
#

hello guys

#

can anyone help me am trying to make a killer or imposter

#

i have a list of players photon views

#

will show you the code now

#

`

Game Manager Script```cs
using UnityEngine;
using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;

public class MyGameManager : MonoBehaviour
{

PhotonView view1;


private static MyGameManager _instance;


public static MyGameManager Instance { get { return _instance; } }


public List<PhotonView> listOfViews = new List<PhotonView>();

private void Awake()
{
    if (_instance != null && _instance != this)
    {
        Destroy(this.gameObject);
    }
    else
    {
        _instance = this;
    }
}

void Start()
{
    view1 = GetComponent<PhotonView>();
    Debug.Log(PhotonNetwork.LocalPlayer.NickName);
    MakeARandomPersonASus();
}


public void MakeARandomPersonASus()
{
    view1.RPC(nameof(ResetKiller), RpcTarget.AllViaServer);
    Debug.Log("im in make a random person sus");
    int randomInteger = Random.Range(0, MyGameManager.Instance.listOfViews.Count);
    Debug.Log(randomInteger + " randomInteger");
    //MyGameManager.Instance.listOfViews[randomInteger].GetComponent<controll>().isKiller = true;
    // MyGameManager.Instance.listOfViews[randomInteger].GetComponent<controll>().Sword.SetActive(true);
    Debug.Log(MyGameManager.Instance.listOfViews);
    Debug.Log(MyGameManager.Instance.listOfViews.Count + " players in the list");
    Debug.Log("some one is killer now");
    view1.RPC(nameof(IamTheKiller), RpcTarget.AllViaServer, randomInteger);
    Debug.Log("i did called im am the killer rpc");
}


[PunRPC]
void ResetKiller()
{
    foreach (PhotonView id in MyGameManager.Instance.listOfViews)
    {
        id.GetComponent<controll>().isKiller = false;
        id.GetComponent<controll>().Sword.SetActive(false);
        Debug.Log("im set to false now");
    }
}
#
    [PunRPC]
    void IamTheKiller(int randomInteger1)
    {
        Debug.Log(randomInteger1 + " randomInteger1");
        Debug.Log("im in im a killer rpc");
        MyGameManager.Instance.listOfViews[randomInteger1].GetComponent<controll>().PrintMyName();
        MyGameManager.Instance.listOfViews[randomInteger1].GetComponent<controll>().isKiller = true;
        MyGameManager.Instance.listOfViews[randomInteger1].GetComponent<controll>().Sword.SetActive(true);

        //MyGameManager.Instance.listOfViews[randomInteger1].GetComponentInChildren<controll>();//.SetActive(true);

        
    }
}
#

`

This in PlayerScript ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;

public class controll : MonoBehaviour
{
PhotonView view;

void Start()
{
view = GetComponent<PhotonView>();

if (!MyGameManager.Instance.listOfViews.Contains(view))
{
MyGameManager.Instance.listOfViews.Add(view);
}
}

void Updater()
{
//Player Controlles just nevermind about it
}
}

#

and the problem is the killer is random for every player
i cant figure out what is happining it just somtimes everything is random and somtimes it works for every one exept the killer he dont see the sword with him he see it with anyone else
its super random and bad

#

like this the killers isnt one for all of them i dont know why

weak plinth
#

photon network issue

#

when i leave room i cant join back to the lobby

#

i tried for hours to find out why

#

there is no help

#

nvm i found the reason

#

here is the code, if you have the same problem

PhotonNetwork.LeaveRoom();
PhotonNetwork.Disconnect();
PhotonNetwork.offlineMode = true;
PhotonNetwork.LoadLevel("Main");
#

but no errors when re-joining room, but it says lobby is still false. photon is so annoying sometimes

weak plinth
#

oh yeah

       public override void OnDisconnectedFromPhoton()
        {
            PhotonNetwork.offlineMode = true;
            SceneManager.LoadScene("Main");
        }

this will fix also

sharp axle
# flint scarab can any one help guys

I don't use photon but it looks like your game manager is running on every client so every client gets a different random number. You will need the server to make the only random number and send that to the clients as a network variable.

flint scarab
sharp axle
hybrid berry
flint scarab
#

if (PhotonNetwork.LocalPlayer.IsMasterClient)

#

and gameManager Object has a photon view btw if its matter

flint scarab
#

should i put if (PhotonNetwork.LocalPlayer.IsMasterClient)
{MakeARandomPersonASus() }

hybrid berry
flint scarab
#

No problem

sharp axle
flint scarab
#

but he shouldnt know us between bots and npc`s

marble urchin
sharp axle
flint scarab
#

@sharp axle
i think i know the problem but dont sure
i think at the time this function ( MakeARandomPersonASus) called
there were no one in listOfViews and i thinks this is the reason becuase i got a debug.log(listOfViews.Count)
and it print 0
i thought of a solution
that i do this
IEnumerator MakeARandomPersonASusTimer()
{
yield return new WaitForSeconds(1);
if (listOfViews.Count > 1)
{
Debug.Log("dsabasdf");
MakeARandomPersonASus();
}
}
and it just doesnt work and dont really do call MakeARandomPersonASus()

marble urchin
# sharp axle Dumping it into json is a bit inefficient but if it works it works. As long as i...

Not even json - lol. Just a delimited string and it's only at startup. Really, the only reason I need to do it at all, as opposed to having each player initialize their own card data, is to make sure the shuffled deck is in the same order on all clients. I supposed I could just send a seed to use when shuffling. Theoretically all the players would end up with the same results in that case.

Once the game is setup I will use events to handle when cards are dragged from one pile to another. This way I can animate the action on each client.

flint scarab
hybrid berry
flint scarab
#

Hello guys, i have a simple problem
and its huge for me i spend 3 weeks trying to fix it
i want to randomlly chose imposter
and this killer should have a sword the thing is every player has a sword but its not enabled and if you are the killer its will get enabled for you
and with Photon Rpc it will be public to other players

------------------------------------------------------this is my scripts :
Game Manager Script This script is in empty object with a photon view : || https://paste.ofcode.org/GSbuW3MteCGDttxYPus9ug ||
Player controll Script this script is in every player : ||https://paste.ofcode.org/UTsCWpKSkX6UnYXV4bWUZ3||

i dont really understand the problem
itss just the killer is random for every player
i cant figure out what is happining it just somtimes everything is random, and somtimes it works for every one exept the killer he dont see the sword with him he see it with anyone else
its super random and bad
like this the killers isnt one for all of them i dont know why

-- normal players should know the imposter the sword should be enabled and everyone see it--

still hare
#

I don't use photon but I am sure they have some kind of client id

#

You would need a dictionary of client ids and players instead of a list

flint scarab
#

i tried that method @still hare

#

it dosnt work there is alot of glitches in it

still hare
#

Then you probably didn't do it right...

flint scarab
#

exactly

uncut bluff
#

hey guys I am confused on how to disconect a client, rn am doing this ```cs
public void Disconnect()
{
NetworkManager.Singleton.Shutdown();

}
void Cleanup()
{
if (NetworkManager.Singleton != null)
{
Destroy(NetworkManager.Singleton.gameObject);
}
}```

#

but then when I try to get in again I get this

#

[Lobby]: LobbyConflict, (16003). Message: player is already a member of the lobby

lucid fox
#

Hey i am new to multiplayer game dev and I wanted to use Netcode for Game Objects for the first time. My question is :
Should I make my new game from scratch and implement Netcode after or should I implement the netcode networking as im making the game ?

sharp axle
sharp axle
hybrid berry
#

Got a Q about lobby service. Docs say that "When a player creates a lobby, they automatically become the host."

Is having the client host a lobby inappropriate? how should you handle this when using a DGS once the game starts? At the moment, I'm doing something like this (for a turn-based 1v1 card game):

  • When a player quick plays, they will search for a suitable lobby. If none exists, they will create one.
  • If they find a suitable lobby, both players will register as clients and be connected to a server, and the game will start.
sharp axle
hybrid berry
hybrid berry
#

are there any examples of NGO being used in separate client/server projects? my gut tells me its impossible - the FAQs mention NGO supporting a dedicated game server model, but suggests that the server build still needs to be the same project as the client build.

#

I know I've mentioned similar things before, but I'm hopeful I can keep my client and server projects completely separate. I don't want to have any server code exposed on the client build, and the other solutions like code stripping or partial classes all just feel a bit messy

lucid fox
#

Hey does anyone know about a Netcode for Game Objects TUTORIAL using a DEDICATED SERVER? Every tutorial i found on the internet were using the host-client method but i want to have the game data on a server.

hybrid berry
hybrid berry
# lucid fox Hey does anyone know about a Netcode for Game Objects TUTORIAL using a DEDICATED...

We're finally doing it, we're hosting our own dedicated server on a cloud platform! Now anyone will be able to join, from anywhere in the world.
Digital Ocean provides us with the Linux machine, and we use SSH to connect to it!

If you're new to the whole cloud platform shenanigan, use the same provider I do for clarity, oh and guess what, if y...

▶ Play video
sharp axle
sharp axle
hybrid berry
sharp axle
hybrid berry
#

I'm confused about when clients/servers should be created. I'm taking a look at the MatchPlay sample (https://docs.unity.com/matchmaker/en/manual/matchmaker-and-multiplay-sample) - and indeed clients/servers are created at launch (see: https://github.com/Unity-Technologies/com.unity.services.samples.matchplay/blob/0225d6c89a5f951350609921607457324d8f847c/Assets/Scripts/Matchplay/ApplicationController.cs#L31).

Do I want this to be the case? I had assumed, with Matchmaker, you would not do this until a game was found.

GitHub

A Matchmaking with Multiplay Unity example project. Implements the Unity Matchmaking and Multiplay SDK to create an end to end matchmaking game experience. - com.unity.services.samples.matchplay/Ap...

sharp axle
flint scarab
#

Hello guys i have a problem
im trying to make a random killer chose
and make this killer has a sword
but the problem is when i enable the sword for the killer its get enabled for everyone in killer view
and it dont get enable for crewMates(the players who are not the killer)

hybrid berry
sharp axle
#

Hello guys i have a problem

unreal sky
#

eyo

#

so i noticed that, in my game, when two players (one host, one normal) are in a game, the host overwrites one of the player's networkvariables, but just that one, its others are completely safe.

#

the client player, oddly, is completely incapable of modifying that variable, even though it modifies its others just fine

#

the ones that work are booleans that track certain inputs
the one that doesn't tracks horizontal input

#

new data: even when the client is the only player (by using a server with no player), it still doesn't register changes to its variable

sharp axle
unreal sky
#

all my others work just fine that way with default settings

#

its just the float, not the bools

#

why would this be happening?

hybrid berry
sharp axle
hybrid berry
#

feel like an idiot, ty

sharp axle
#

lol, a lot of the Unity Samples feel overengineered

unreal sky
#

is there any difference between float networkvars and bools?

#

thats the only thing i can identify

hybrid berry
unreal sky
hybrid berry
unreal sky
#

oh

unreal sky
#

they're the exact same

#

default settings

#

in the same serverrpc

#

made with the same constructor for networkvar

#

here:

#
using UnityEngine;
using Unity.Netcode;

public class WASDMovement : NetworkBehaviour
{
    public NetworkVariable<bool> Example1
    public NetworkVariable<float> Example2;

    void Update()
    {
        ExampleServerRpc();  
    }

    [ServerRpc]
    void ExampleServerRpc()
    {
        Example1 = false; ///Works just fine
        Example2++; ///Doesn't work
    }
}
#

only difference is that the bools are modded in a switch case

#

¯_(ツ)_/¯

hybrid berry
unreal sky
#

whoops

#

nice catch

#

but the error is that example2 aint changing

#

i debug.log its value

#

and it returns 0

unreal sky
#

alright

#

an hour of debugging later

#

turns out

#

the reason that my other network vars work

#

is because they don't

#

seriously

#

i found a bug in netcode

#

the crap aint working like it should

#

it doesn't even register the variables as true

#

even though they 'act' like they're true

#

and sometimes it just doesn't work at all

#

so yeah

#

ima need to rework some stuff

sharp axle
unreal sky
#

what i had was that i had a new NetworkVariable<float>(x)

#

but ig that shouldn't be workin

flint scarab
sharp axle
unreal sky
#

damn

unreal sky
sharp axle
#

Those run on the server but that's not where you initialize network variables. That's only done when they are declared

unreal sky
#

ok fixed that

#

but then

#

it still doesn't let me modify the float

sharp axle
#

Hello guys i maked a sword and put this

unreal sky
late vapor
#

Does anyone have any idea if the Steam sdk lets you use their peer to peer network without having a steamworks account ?

sharp axle
#

if Example2.Value++ isn't working then thats a bug and should be reported

unreal sky
#

i'll try

#

but you see, it only works when the player is a host

unreal sky
#

so why would that be?

sharp axle
unreal sky
#

basically

#

the player has bools tracking its WASD movement

#

when you push/let go of one of the keys, the corresponding bool is toggled

unreal sky
unreal sky
#

ty everyone <3

versed lily
#

I have some events (System.Action's) that I want to trigger cross network. Currently I stick these in ClientRpcs and trigger them each locally, but I have found the need to trigger one in the midst of a serverRPC. What's the preferred way to Invoke events on clients from within a server call?

sharp axle
versed lily
versed lily
#

ty

hybrid berry
#

Is there a way to test Matchmaker integration locally? It's tedious having to deploy new builds to Multiplay every change

ashen mountain
sharp axle
hybrid berry
hybrid berry
sharp axle
#

Matchmaker with Relay is on the roadmap I believe

unreal sky
#

heyae

#

*heya

#

im bacc lol

#

was wondering why rigidbody2ds don't work on network

#

they just allow clipping

sharp axle
# unreal sky was wondering why rigidbody2ds don't work on network
hasty hazel
#

Hello, I'm using mirror and I'm getting an error like 4 mins in on the tutorial

#

Does anyone know how to fix those errors

spring crane
#

Do you have some transport on the NetworkManager gameobject? They are usually separate components

#

Mirror discord server should be able to help you better

vocal bane
#

It says UnityTransport could not be found even though it is a component of the network manager object.

NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(
  allocation.RelayServer.IpV4,
  (ushort) allocation.RelayServer.Port,
  allocation.AllocationIdBytes,
  allocation.Key,
  allocation.ConnectionData
);

Here are the directives:

using System.Collections;
using System.Collections.Generic;
using Unity.Services.Authentication;
using Unity.Services.Core;
using Unity.Services.Relay;
using Unity.Services.Relay.Models;
using Unity.Netcode;
using UnityEngine;

I am really confused..

hybrid berry
# vocal bane

what @sharp axle said. Also, just FYI for the future - any "type or namespace name" errors won't have anything to do with whether or not a component exists. That would always be a NullReferenceException

tribal coral
#

Hi!

So I decided to get multi-player going using Photon Fusion, the goal is to get a single server going.

Ny game is in super early prototype, so I don't see a massive problem going forward, I just need to re-write the code it seems.

Are there any rules as to how to proceed this?
Should networked items (players, intractable objects, etc) only contact the non-networked items, like ui/hud, static objects.

Any push in the right direction would be greatly appreciated, I just need some general rules 🙂

#

I got networking working, player movement and such work, but the issues comes as soon as a 2nd player joins, and the game start sending information between the player(s) and the ui/intractable objects

sharp axle
tribal coral
#

Server, I was thinking of renting a small server

#

Photon Fusion is free up to 20 players at the same time, 16 people on a server i believe, so I was thinking of just renting a server and have it available for testing

#

I'm a fast learner, but don't know where to start, started looking into it yesterday, so would be awesome with a push in the right direction so I know where to look 🙂

hybrid berry
tribal coral
hybrid berry
#

If you're designing anything competitive, server-authoritative is the way to go, and in general (at least to me) feels like a much smarter way to handle networking.

disclaimer: I have also only just started, so don't take my word for anything - @sharp axle is the resident expert when it comes to pretty much anything networking ^^'

tribal coral
#

If that makes any sense

hybrid berry
# tribal coral I see, I'm not making anything competitive, server-authoritative just sounds bet...

In that case, these are useful links for understanding the differences between DGS (dedicated server), listen servers (client-hosted), and P2P.
https://unity.com/how-to/intro-to-network-server-models
https://www.youtube.com/watch?app=desktop&v=YbIeN3CYr_M

Peer-to-peer (P2P) and dedicated game server (DGS) models are both popular choices for hosting your game server. But which one is right for you?

Disclaimer: “Peer-to-peer” can be interpreted in different ways and can reference the hosting model or the replication model. This discussion is about hosting and, in this context, it can be called “c...

▶ Play video
tribal coral
tribal coral
sharp axle
#

I focus on Unity Netcode but most of the concepts are the same across most of the popular frameworks like Photon and Mirror

tribal coral
#

It just seemed that people overall agreed that photon worked the best

sharp axle
tribal coral
sharp axle
tribal coral
sharp axle
tribal coral
#

Unity Netcode it is!

vague sequoia
#

Hi all,

So, I'm playing around with Netcode, and hitting something of a snag with Network Variables. I'm making a very simple tank vs tank game to try everything out and us as a learning experience.

At the moment I'm trying to get a scoring manager to work.

Here is the code I'm using, I'm sure I'm doing something really simple and silly wrong, but I can't see it.

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

public class ScoringManager : NetworkBehaviour
{

private NetworkVariable<int> playerOneScore = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<int> playerTwoScore = new NetworkVariable<int>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);

public Text txtPlayerOneScore;
public Text txtPlayerTwoScore;

public override void OnNetworkSpawn()
{
    txtPlayerOneScore.text = playerOneScore.Value.ToString();
    txtPlayerTwoScore.text = playerTwoScore.Value.ToString();

    playerOneScore.OnValueChanged += (int previousValue1, int newValue1) =>
    {
        txtPlayerOneScore.text = playerOneScore.Value.ToString();
    };
    playerTwoScore.OnValueChanged += (int previousValue2, int newValue2) =>
    {
        txtPlayerTwoScore.text = playerTwoScore.Value.ToString();
    };
}

// Update is called once per frame
void Update()
{
    if (!IsOwner) return;
    if (Input.GetKeyDown(KeyCode.E))
    {
        playerOneScore.Value++;
    }

    if (Input.GetKeyDown(KeyCode.R))
    {
        playerTwoScore.Value++;
    }
}

}`

At the moment I'm 'manually' increasing the scores with keypresses. The score sync over the networking just fine and update the score counters.

The problem is, I can only increase the scores on the 'Host' version of the game.....(cont)

#

.......And not the client. It behaves as though the keypresses aren't recognised on the client game.

Anyone have any ideas? 😕

hybrid berry
vague sequoia
#

Aaah okay, I think I understand that part. I think I've been misunderstanding the 'owner' part (thinking it was a local thing, whereas if I understand correctly now, the host will always be the owner as it's the first game to start and declare the variable?) Think it's my own fault for skipping ahead in the vid I'm following. lol. I'm guessing an RPC will be needed to write to it (that's a bit later in the video. lol.)

sharp axle
vague sequoia
#

Gotcha, thanks fellas 🙂

hybrid berry
#

@sharp axle could you walk me through something on the Matchplay sample project? (https://github.com/Unity-Technologies/com.unity.services.samples.matchplay/blob/master/Assets/Scripts/Matchplay/Server/ServerGameManager.cs)

StartGameServerAsync (line 45) is hit from the bootStrap scene on app start. There is a comment that addresses a problem I mentioned yesterday - testing matchmaker locally/not through a Multiplay hosted server. I don't really understand how it's doing that - it seems to just skip initialising Matchmaker, but the rest of the application is still dependant on it?

GitHub

A Matchmaking with Multiplay Unity example project. Implements the Unity Matchmaking and Multiplay SDK to create an end to end matchmaking game experience. - com.unity.services.samples.matchplay/Se...

sharp axle
#

walk me through something on the Matchplay sample project?

hearty zealot
#

Hi guys, I receive this error in the client (and not in the host for some weird reasons) when the client connects to the host.. but I literally have 0 prefabs spawned in the scene when the client is connected to the host

sharp axle
hearty zealot
#

I have only a network object in the scene which is the Relay (that I use to connect the client to the host with a join code so that they can play together) and I don't understand how it could cause an error

#

The Relay script loads the "Game" scene for both the host and the client when a client inserts the join code (it's a 1v1 game)

#

And does that calling a ClientRpc to unload the current scene and load that

#

Ok I've put a DontDestroyOnLoad on the Relay script, and now it gives me an error like that but with another hash

#

And for some weird reasons the relay is destroyed on the client (which is the one that gives me the error)

#

The Relay has a reference to other objects.. do those objects also need to be NetworkObjects? (they're just a button and the text field where the user inserts the join code)

#

The hash code that's in the error is the same as the Relay's one..

#

I mean the relay is not a prefab.. wtf

#

Ok I had to also put the Relay inside the network prefab list of the network manager (even though it is not a prefab)

#

But now the relay is destroyed when I change the scene even though I put a DontDestroyOnLoad on it

hearty zealot
#

Is there any way to spawn a network prefab from a ScriptableObject?

sharp axle
hearty zealot
#

Well I am using them to avoid using singletons

vocal bane
#

I am getting this warning when I run this function, idk what the warning means.

    public async void CreateRelay()
    {
        try
        {
            Allocation allocation = await RelayService.Instance.CreateAllocationAsync(49);

            string JoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);

            Debug.Log(JoinCode);

            HostID.GetComponent<Text>().text = "ALPHA V0.1 - HC: " + JoinCode;

            NetworkManager.Singleton.GetComponent<UnityTransport>().SetHostRelayData(
                allocation.RelayServer.IpV4,
                (ushort) allocation.RelayServer.Port,
                allocation.AllocationIdBytes,
                allocation.Key,
                allocation.ConnectionData
            );

            NetworkManager.Singleton.StartHost();
        }
        catch (RelayServiceException Error)
        {
            
            Debug.Log(Error);
        }
        
    }
sharp axle
vocal bane
hasty hazel
#

I'm using a cinemachine camera in my 3rd person throwing type game, except when I have 2 players, they both only look through that one camera. How would I go about fixing this?

sharp axle
# hasty hazel I'm using a cinemachine camera in my 3rd person throwing type game, except when ...

You need to make sure the camera is disabled on the remote player objects. Here is how they did it in the Unity Sample
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/d37c360bc8cdbbbf680e2afc5963571e20f28ffd/Basic/ClientDriven/Assets/Scripts/ClientPlayerMove.cs

GitHub

A collection of smaller bite-size samples to educate in isolation features of Netcode for GamesObjects and related technologies. - com.unity.multiplayer.samples.bitesize/ClientPlayerMove.cs at d37c...

long totem
#

Hello, I'm not really good at english so sorry first,
I'm using Photon and I can't give a nickname to player.
This code gives NullReferenceExpection error. I'm sure the object which has this code has Photon View component. What can be reason?
GetComponent<PhotonView>().Owner.NickName = "player1";
User connects to master, lobby and room before this.

tribal coral
#

Mornin!

I'm working on Netcoding, and got a question about cameras, each player should have a camera, but how do i correctly assign a camera to a single player?

Should each player object have a camera? Should there be one MainCamera in the scene?

austere yacht
tribal coral
austere yacht
tribal coral
#

Got it, my camera got a few scripts etc attached, so could I also in theory attach a camera to each player and deactivate it, when the player spawns, grab your own camera and activate it?

austere yacht
#

That works too, it’s just more wasteful in terms of having copies of unused stuff

tribal coral
#

Fair

#

Thank you for your answer! I'll give it a look 😄

#

Or, what if I create a camera prefab with all my things on it, and then instantiate that camera when the player spawns? Would that be the same as having the camera on every player?

austere yacht
tribal coral
#

I see, ok thanks!

tribal coral
sharp axle
tribal coral
# sharp axle Check out the link I posted yesterday. This is how a Unity sample uses the 3rd p...

I got that working, and all characters move with their own camera and such as I want, perfect!
Let me just make sure I got the right idea as to what is going on.

When the player spawns, it disabled both the controls and collider.

Then in OnNetworkSpawn it activates my controls if that player is the client (the one controller the player that spawned), then if the player is NOT the owner, it will disable the controls (??), the character controller, but activate the collider.

If however, the player is the owner of the player spawned, it will enable the controls, set the cinemachine follow to the right target (which in my case is an empty on the player character).

The whole SetSpawnClientRPC thing I don't really get

sharp axle
tribal coral
sharp axle
long totem
hybrid berry
tribal coral
#

I got character customization in my game, what is a good way to synchronize what the player is wearing?

The players has modular components where only 1 is active at a time

#

Changing on one client will change the other player aswell

#

I got a list over the active items, so if there's a way for me to send that list to the server, that would be great

#

But from what I've read about NetworkVariable, i cant really do that

#

NetworkList?

sharp axle
tribal coral
#

I see, so a list of indexes that gets syncronized, that list will be read by each player in the session and activate/deactive the item accordingly?

sharp axle
#

right

tribal coral
#

And just to make sure.

Let's say I got 3 players, player 1, 2 and 3.

Player 2 changes hair from index 1 to index 2.

When player 2 saves changes, a call or whatever will tell player 1, 2 and 3 on the server that something changed, and that something should be updated.

Player 2 might send their ID to tell the others that they did a chance?

Then player 1 and 3 will then run a method on Player 2 gameobject that will activate/deactive the changes?

#

Or am i completely off?

sharp axle
tribal coral
#

Thank you for your answers 🙂

flint scarab
#

Hello brothers

#

can i stream and receive Renderer.material of objects in OnPhotonSerializeView?
and if i can how, what is the code i should put
for example any game object state

can be streamed with ---> stream.SendNext(GameObject.activeSelf);
And readed by --> GameObject.SetActive((bool)stream.ReceiveNext());

flint scarab
#

why am i even explaining that

sharp axle
flint scarab
#

I want to change the t shirt color by pressing button

#

And i want to send the new color to other clients

#

Will it change for all because i didnt test it yet

sharp axle
flint scarab
#

how

#

rpc?

#

rpc as what i know will make all the clients have that color not only send it

tribal coral
#

So, I figured how the Client (people joining server) can change their look and it will update for everyone. the server/host only

But how can I do the same change when the host does the change?

#

_allChildObjects is a 800 long list with every possible modular piece of my character (Should probably turn this into a Scriptable Object), ActivateItem(GameObject) will take that GameObject, figure out where it fits in and deactivated the old one, and activates the new

#

From my understanding, ClientRpc is a call/message or whatever, sent from the client (player who joined) to the server (player who first joined/The host of the server).

ServerRpc should sent a class/message FROM the server (first player/the host) to every client, but this does not work, and I'm not sure why

sharp axle
#

You could also make the int[] into a NetworkList and give the client authority over it

#

That would save on bandwidth as only list changes would be sent

tribal coral
#

It's getting late, and I'm running out of steam for today, so my brain ain't working right, so sorry if it's super obvious x)

tribal coral
#

Yea I'm gonna continue tomorrow, my brain is fried lmao

#

Thank you so far, got a lot done today!

#

Oh, that reminds me, is it possible to spawn your own character prefab?

As in, what if I have a scene that allows the player to modify their player prefab, then when they join a server, what the player created in the menu will be used?

#

I imagine I can just customize a character how I like and spawn it like it is

#

Players won't be able to customize in game, but that's fine

sharp axle
tribal coral
#

I'll just re-write how my customization work to be more multiplayer friendly overall

#

I got the most important part working like I imagined, the player customization ain't the most important thing now

uncut bluff
#

hey guys after starting the network manager host can I change it to another player if the original host disconnects?

sharp axle
uncut bluff
#

ah ok so the aproach is: go back to the lobby and the new apointed lobby master can start hosting

#

is this correct?

uncut bluff
#

btw I am trying to see how can I kick a player from the game from the lobby, the player id has a diferent Id from the network manager id, is the best aproach the host send a RPC message to the client with the same lobby id to disconect?

sharp axle
uncut bluff
#

ok thanks for the input

hybrid berry
#

Proper noob Q - the NetworkManager forces clients to load the scene the server is in on connect. Is it desirable to turn this off? I've been debating it, since for most of the user's journey up until they get into a game, I've currently kept my server in an Init scene rather than matching the client's scene.

sharp axle
sharp axle
#

It won't let me post Discord links but there is also a Server dedicate to Netcode for GameObjects.

hybrid berry
sharp axle
#

Full Disclosure: I'm a mod there

hybrid berry
sharp axle
#

I dunno. It kinda feels like self promotion. or something

empty night
#

does firebase firestore follow the first set of rules (realtime database) or the second (storage) , I think its the second
https://www.youtube.com/watch?v=PUBnlbjZFAI

All data stored in Firebase is by default readable and writable by any authenticated user. While this is great for getting started, productions apps require stronger security. Thankfully, Firebase has your back with Security Rules. They provide a declarative way to specify who can access certain data and what schema that data should have. Take a...

▶ Play video