#archived-networking

1 messages · Page 14 of 1

ripe yarrow
#

Why is it sometime the player will spawn at position 0,0,0 and not at there target destination?

#

am i not supposed to pass through vector3?

radiant dome
#

Hello guys,i need an help with a game i am developing,if you know how to implement interpolation in a multiplayer game write me please

ripe yarrow
weak plinth
#

So I'm working on a multiplayer game is there a way to improve the lantency of my game when using Netcode?

sharp axle
weak plinth
sharp axle
violet island
#

You can also set the delivery packets to be unreliable if they are sent a lot, so if the player is lagging they wont have to receive old ones as I understand it.
By default they are reliable, that means every packet is guaranteed to be delivered.

[ServerRpc(Delivery = RpcDelivery.Unreliable)] //Movement is updated many times a second, package reliability not needed
    private void HandleMovementServerRPC(string SuggestedAnimation, Vector2 suggestedVector, float suggestedSpeed)
    {
        animator.Play(SuggestedAnimation);
        rb.MovePosition(rb.position + suggestedVector * suggestedSpeed * Time.fixedDeltaTime);
    }
#
        //Starts host if info valid
        manualHosting.onClick.AddListener(() =>
        {
            getConnectionInfo((bool isInfoValid) => {
                if (isInfoValid)
                {
                    //Disconnects from other server
                    Disconnect();
                    //Start client
                    NetworkManager.Singleton.StartHost();

                    //Remove start menu UI
                    allUI.SetActive(showUI = false);

                    startMenuState = StartMenuState.manualHosting;
                }
            });
        });

    public void Disconnect()
    {
        NetworkManager.Singleton.Shutdown();
    }

I got a problem where I sometimes I have a host or client already running.
I shut down the NetworkManager, then I want to start another connection.
The problem is that the shutdown is delayed and it happens after I tell it to start hosting or being a client.

I'm trying to simulate someone swapping servers or starting a new one

sharp axle
balmy sierra
#

So I'm going to make a singleton that is a "Data Manager" which holds a dictionary of a dictionary prefab with a unique key for each player, making it so you can get the players key, then get the value from their specific dictionary (and make it so if you rejoin etc your data is the same etc).

This data manager is going to be only made once a lobby is made and is going to have server authority, making it so only the server can change stuff on it (the clients can call RPC's for changing stuff like cosmetics or something, like keeping track of score).

How would I "Make" the data manager?
I mapped out the scenes etc and the flow state for the data manager, upon creating a lobby I want the data manager to be created upon loading into the "lobby" scene and having it so if clients connect they get a synced data manager

Would I use the network manager I made to make it so upon hosting a lobby you create a data manager?
Would I make it so upon leaving you remove it?

I'm only asking instead of experimenting and googling because I'm uncertain about how to approach this and feel like someone may have experience enough to recommend one way or another

sharp axle
#

Player Manager

vocal yoke
#

Hey, I have problem, I'm trying to create chat system but it doesnt really work as intended althrough code seems to be fine

    public void SubmitText()
    {
        string str = inputField.text;
        str = str.Replace(" ", "");

        if (inputField.text != null && str != "")
        {
            string newStr = "<color=orange>" + playerNetwork.playerName + "</color> " + inputField.text;
            SendMessageServerRpc(newStr);
        }
    }
    public void PrintMessage(string str)
    {
        TextMeshProUGUI newText = chatQueue.Peek();
        newText.gameObject.SetActive(true);
        newText.text = str;
        newText.transform.SetSiblingIndex(0);
        chatQueue.Dequeue();
        chatQueue.Enqueue(newText);
    }
    [ServerRpc(RequireOwnership = false)]
    public void SendMessageServerRpc(string str)
    {
        ReceiveMessageClientRpc(str);
    }
    [ClientRpc]
    public void ReceiveMessageClientRpc(string str)
    {
        PrintMessage(str);
    }

message is send to all clients on server but its not received by local player instance but its only received by instance of player thats send message but in other clients side?
Its weird and I dont understand it, anyone had similar issue?

sharp axle
vocal yoke
#

i mean PrintMessag doesnt really matter because if i put for example print(this.gameObject.name); before it like that

    [ClientRpc]
    public void ReceiveMessageClientRpc(string str)
    {
        print(this.gameObject.name);
        PrintMessage(str);
    }

it somehow still only print one name

#

it looks like it only invoke in one player instance across all clients and its weird

sharp axle
vocal yoke
#

yes it is, yet it doesnt work

sharp axle
#

If you're making a network variable then you'll need to use a Native Container like NativeArray or NativeList
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/arrays/#native-containers

Arrays of C# primitive types, like int], and [Unity primitive types, such as Vector3, are serialized by built-in serialization code. Otherwise, any array of types that aren't handled by the built-in serialization code, such as string], needs to be handled through a container class or structure that implements the [INetworkSerializable interface.

nova linden
#

How can I effectivley syncronize a lot of data ? I want to make my enemy behabe realistic therefor im going to use a boss simulation but i do not know how i could sync these massive enemy swarms without lag

austere yacht
nova linden
#

Is there any other solution i could use for the enemies?

nova linden
#

how do games like battlebits sync so many players ?

vagrant island
#

🤔

zenith crescent
#

[Netcode] [DestinationState To Transition Info] Layer (0) sub-table does not contain destination state (0)! i cant find anything on google about this but im getting this error with the ownernetworkanimator

austere yacht
sharp axle
nova linden
# sharp axle What is the problem you are having? and what solutions have you tried?

The enemies in my game are pigeons and birds are kinda like a swarm inteligence so i wanted to simulate the big bird groups with a boids simulation the problem is sending location data for arround 500 birds is probaply way too much and its probaply even too much for just 100 birds. I did not attempt to code the birds as i wanted to find the best solution for the data problem first.

sharp axle
nova linden
#

thei need to be able to be shot down and attck you so Dots it is

#

im just worried that the game will have a lot of lag when i send so much data

sharp axle
#

NFE has built in client prediction and a priority system for sending packets. It should be ok

rain fern
#

I need urgent help. This is fucking my brain so hard.
I'm trying to use netcode for gameobjects to make a multiplayer game, but the transforms aren't syncing well.
I've attached the script and a video with an example of my problem

#

I wanted to use Rpcs so that the server with be the only one with authority, but that was happening, so I tried using the exact same script that I had for MonoBehavior and tweak it just enough so that it would work on multiplayer with client authority, but I encountered the same exact problem and I have no idea what is causing this

white igloo
#

I got a question about Networking apps:
Which app/program is the best to use. I would like to have unlimited CCU, so many people can play the game.
Photon has limited, that’s bad. What bout mirror? Any other suggestions?

sharp axle
sharp axle
rain fern
# sharp axle You're gonna have a hard time trying to retrofit networking into a single player...

I ain't. I wrote the original script as a MonoBehavior, but I always intended to make a multiplayer game, not a singleplayer one. I have tried rewriting it using ServerRpcs and with a non-authoritative Network Transform but I was having that result. I thought that maybe my problem was related to calling two different Rpcs working with the same components, so I tried using a client authoritative version with a Client Network Transform, which is almost all the same same as the original one but the MonoBehavior now being a NetworkBehavior and the IsOwner.
I also tried disabling interpolation since I have had problems with it before and it actually worked, so I tried setting interpolation on and position threshold to 0 and that also worked, but when I try that in the non-authoritarive script it adds an unbelievable amount of delay between the moment I press a key and the moment something actually happens

#

I still want to find another way to fix this since I don't want to give any control to the client

nocturne vapor
#

hey, hwo would I go about syncing a large array between the server and the clients with NGO? NetworkList is a peace of garbage and makes more problems than anything else

nocturne vapor
#

nvm I ditched the array idea completly, I found a better approach

zenith crescent
#

is it triggers causing it? i have a trigger but im calling it from the network animator

white igloo
sharp axle
white igloo
sharp axle
white igloo
zenith crescent
#

[Netcode] [DestinationState To Transition Info] Layer (0) sub-table does not contain destination state (0)! still stuck on why this is happening

i have a normal animation state setup just transitions i double checked nothing is abnormal but i get this error anytime a animation plays is there a simple setting im forgetting

#

when its just the host i dont get the error

#

i made a more basic version and got this error:
[Netcode] [DestinationState To Transition Info] Layer (0) does not exist!

sharp axle
zenith crescent
#

it is

sharp axle
zenith crescent
#

yes

sharp axle
#

Do you have multiple animators?

zenith crescent
#

just one

#

public class OwnerNetworkAnimator : NetworkAnimator
{
    protected override bool OnIsServerAuthoritative()
    {
        return false;
    }
}
``` this is the script its just the basic ownernetworkanimator i dont get why its doing this
#

is there a difference in the unity 2022 lts vs the 2021 in how animations work

#

im using the newest version

sharp axle
zenith crescent
#

is this defined as fresh lmao

#

everything works the animations sync perfectly the error effects nothing its just annoying

#

it only debugs if im in developer mode on error logs

white igloo
#

I want to create a game with mirror networking. When it would be finished, can I hire someone who rewrites it for steam. So people can play it on steam. Is that possible?

spring crane
jagged fulcrum
#

Hello everyone, I want to send a request to a custom backend when the game is closed.

I have tried using the OnApplicationQuit() and WantsToQuit() methods, but they don't seem to work.
It seems that there is not enough time for the game to send the request when the closing sequence is initiated, which is why this process doesn't happen, and I'm unable to send any message to the backend.

However, as we know, many games are able to perform this action. For example, even if I force-close the game from the task manager, the game still sends web requests before shutting down.
How can I solve this issue or what approach should I take when faced with such a problem?

#

This is the code of the request I sent when the game was closed

nova linden
sharp axle
# nova linden do you know a good tutorial for dots and nfe ?

The YouTube channel Turbo Makes Games is the best and only resource I've found for Dots. There is even less regarding NFE.
I'm currently working on some videos basically walking through the Netcode samples on github
https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/NetcodeSamples/Assets/README.md

GitHub

Contribute to Unity-Technologies/EntityComponentSystemSamples development by creating an account on GitHub.

prisma garnet
#

hey guys can anyone familiar with photon pun here tell me how should i make a game manager, i am not talking about the code itself more like, how to make one object control things like game time, game end, game events and stuff like that, i already asked on photon server but i am waiting 10 hours and nobody answers

covert gull
#

Anyone have any available benchmarks on Photon Fusion vs FishNet? I'm leaning towards FishNet as I've used it before and it's free essentially; however, I'm wondering if I'd have better luck using Photon Fusion for an FPS game

zenith crescent
#

how can i add force to another clients rigidbody from another

#

im using non server authoritive movement so when i do serverrpc the client can hit the host but not the other way around

#

using netcode

sharp axle
zenith crescent
#

i already tried just calling a clientrpc will calling a clientrpc from the serverrpc be different?

sharp axle
faint plaza
#

should you use unity's new multiplayer system for a commercial product yet? or is it still being worked on

zenith crescent
#

its released

#

no longer experimental

zenith crescent
sharp axle
zenith crescent
#

so i should make the client call a serverrpc then in that call a clientrpc to the one client i want and make it add force?

zenith crescent
#

when doing a client rpc do i need to get the object and components or can i just do rb.addforce using the reference i have in the scritpt, every player has this script

#

@sharp axle

#

this clientrpc is called from this serverrpc

sharp axle
# zenith crescent when doing a client rpc do i need to get the object and components or can i jus...

clients don't have access to ConnectedClients[].
You'll need to send a NetworkObjectReference of the player you want to move
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#networkobjectreference

Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects

zenith crescent
#

ik i havnt changed it yet but do i need a reference at all

#

im guessing not

#

what im saying is when a clientrpc is ran on a client do i need to get the component rigidbody or jjust use the rb reference in the script

sharp axle
#

If you have the client Id then you can just send the clientRPC directly to that client

zenith crescent
#

and use the scripts references

#

?

sharp axle
#

Yea. once its running on the client just call getComponent()

zenith crescent
#

ok if i already have a reference do i need to do getcomponent

#

or can i use this

sharp axle
#

That should be fine.

zenith crescent
#

ok thank you

#

just transitioning from pun 2 and with that u need to get the components seperately

#

confusing

#

did not work

zenith crescent
#

i tried this and it does not work no force is added but the debugs are correct @sharp axle

sharp axle
#

What is movement there?

zenith crescent
#

a reference to the playermovement script to get the rigidbody

#

no errors

sharp axle
zenith crescent
#

only the client im sending the clientrpc to is running it though no?

#

the ids lineup the correct client is running the clientrpc

sharp axle
#

ah, you're that two functions there

zenith crescent
#

im getting the id from this and calling the serverrpc with the client id i want to have force added

sharp axle
#

That should work

zenith crescent
#

no movement when i try it

#

keep in mind im using the ownerNetworkTransform

#

and network rigidbody

sharp axle
#

yea. thats why you need the clientRPC.
are XYZ values correct?

zenith crescent
#

yes when i had a different rpc setup the host could get hit by the client and the xyz was correct

#

so yes

#

im bad at explaining

#

why is it so hard to make a client add force to another client damn

#

@sharp axle do u have any idea why its not workinmg

sharp axle
#

not really. Its just not meant to be doing what you are trying to do. Its meant to be server authoritative.

zenith crescent
#

do i need to get ownership add the force then give it back

#

it works with the normal networktransform

#

the serverrpc only one

#

but server authorative movement i added was SUPER laggy so i wnet back

#

rigidbody serverauthoriative movement seems to be bad

#

or atleast my implementation

sharp axle
#

yup. thats the trade off

zenith crescent
#

terrible

sharp axle
#

The real solution is to make a client prediction system

zenith crescent
#

all i need is this one thing to add force and i can keep client side movement 😭

#

can i get ownership then add force

#

then give ownership back

#

in netcode does the networkobject script keep a reference to the original owner

sharp axle
#

nope, it doesn't. but your code there should work. You'll need to make double sure that you have the correct rigidbody

zenith crescent
#

how would i get the right rigidbody from just an id in a clientrpc

#

if i cant use connnectedclients[id].playerobject

sharp axle
#

just call GetComponent<rigidbody>()

zenith crescent
#

im not in the script with the rigidbody

#

its referenced

sharp axle
#

thats probably your problem then

zenith crescent
#

ok so i put this in the script with the rigidbody:

and the server rpc is in the playerstats :

#

u mean like this?

#

i can call a rpc on a different script with a reference correct?

#

this does not work either

#

it is running on the correct client

#

why cant it add force to itself?

#

its done 5 times in the same script

sharp axle
zenith crescent
#

so can i use the first solution of just the server rpc and put that

#

tried both neither worked

#

might need to do networkTransform and make it all server authoriative and make player client prediction

#

ugh

zenith crescent
#

@sharp axle found a workaround, i already have the isTagged network variable that is synced and works properly ill just make it so when its true it adds force locally idk why i overcomplicated things

woven cliff
#
        List<ulong> playerIDs = NetworkManager.Singleton.ConnectedClientsIds.ToList<ulong>();

        Debug.Log(playerIDs.Count.ToString());
        foreach (ulong playerID in playerIDs)
        {
            Debug.Log(playerIDs.ToString());
            Spawn(playerID);
        }
#

what did i do wrong?

#

the list lenght is the same as the player amount

#

but all of the ids are 1 or so i think cus idk how to read this really

#

pls ping if you respond

#

nvm

#

it works but there is a issue somehwere else i find it

#

someone pointed that out already

#

the issue is somewhere else

#

im finding it now

#

i found whats not working

#
[ServerRpc]
    public void StartGameServerRpc()
    {
        List<GameObject> spawnLocations = new(GameObject.FindGameObjectsWithTag("SpawnLocation"));
        List<ulong> playerIDs = NetworkManager.Singleton.ConnectedClientsIds.ToList<ulong>();

        foreach (ulong playerID in playerIDs)
        {
            Spawn(playerID);
        }

        gameStarted = true;

        void Spawn(ulong playerID)
        {
            int spawnLocationID = Random.Range(0, spawnLocations.Count);
            Vector3 spawnLocationPosision = spawnLocations[spawnLocationID].transform.position;
            Debug.Log("PlayerId: " + playerID.ToString() + " was spawned at spawn: " + spawnLocationID.ToString());
            NetworkManager.Singleton.ConnectedClients[playerID].PlayerObject.transform.position
                = spawnLocationPosision;
            Debug.Log("the posision of the spawn is: "+ spawnLocationPosision.ToString());
            Debug.Log("the posision of the player is now: " +
                NetworkManager.Singleton.ConnectedClients[playerID].PlayerObject.transform.position.ToString());
            spawnLocations.RemoveAt(spawnLocationID);
            Debug.Log("the count of the spawn list is now: " + spawnLocations.Count);
        }
    }
#

everything seems to work fine but the player with the id of 1 isnt moved

#

it has a clientNetworkTransform

woven cliff
#

pls ping if respond

sharp axle
woven cliff
#

thats pretty stupid but alr i guess i do a clientRPC

sharp axle
# woven cliff not even the server can?

You can be server authoritative or client authoritative but not both at the same time. There can only be one source of truth. Otherwise you end up with race conditions if the server and client try to move at the same time

woven cliff
#

alr then

white ledge
#

can someone guide me about how can I make a local multiplayer game in unity which run over a LAN?
I am working with netcode but it's not providing me functionality to make rooms or lobby kind of functionality
for this its asking me to use unity gaming services like Relay and Lobby but these are making my game gloabl multiplayer
whereas I want my game to work over a LAN only

sharp axle
silver fox
#

Hi, does anyone now how to get the content of a string inside a Cloud Firestore document without nowing the name of a document? (1A2B3C4D-5E6F7G8H-9I0J1K2L should be a random ID)

An example path is:
**mails **(colection)
|- 1A2B3C4D-5E6F7G8H-9I0J1K2L (RandomID) (document)
|- **messages **(colection)
|- **message1 **(document)
|- text: "smth"

vagrant garden
burnt tiger
#

I'm running NGO and trying to build a player class system.
I have a Player prefab that I spawn in, then I want to attach a Class (Warrior, Mage, ...) visual prefab to the player, but not sure how i'd communicate that via networking.
My first though is to Instantate the Player then the Class then parent the Class to the player, however that doesn't appear to work over the network, any thoughts on how I could do this?

woven cliff
#

how do i get the player object of the client the code is ran at

sharp axle
past sparrow
#

Can someone please help me get backfill tickets to work in the Multiplay Matchmaker service? I'm trying to implement server backfilling but users can't return to the same server if they were disconnected. I'm using Matchplay sample (https://github.com/Unity-Technologies/com.unity.services.samples.matchplay) but re-implemented it with FishNet networking library.

GitHub

A Matchmaking with Multiplay Unity example project. Implements the Unity Matchmaking and Multiplay SDK to create an end to end matchmaking game experience. - GitHub - Unity-Technologies/com.unity.s...

#

I am starting backfilling loop with BackfillTicket.Id retrieved from the allocation payload. Default-Queue backfilling enabled and Equality rule enabled for userGamePreferences data in all players. Users can join once server already started. But can not re-join through Matchmaker if they were disconnected. Do I need somehow update backfill ticket when user leave?

silver fox
shrewd junco
#

also this definitely wasnt networking related, i just really wanted to correct that advice

silver fox
#

Thanks

shrewd junco
silver fox
#

ok, ty!

jagged fulcrum
vagrant garden
#

Note that even then you won't get a 100% guarantee. It will send over TCP but if the packet is lost the TCP connection will already be terminated, so in case of packet loss it will never arrive.

jagged fulcrum
vagrant garden
#

No most games don't do that

#

Some do it simply to allow for faster disconnect instead of using a timeout

#

Sending data is pretty much never done.

#

If you do absolutely have to do that use a separate process for this. So that if they terminate the app you have as much time as you want to interact with your backend.

#

It is common to have a launcher and a game process for instance.

jagged fulcrum
#

Frankly, what I wanted to do was send a request to the backed service when the user exited the game and indicate that the user exited. But as you said, sending data in an escape sequence is unreasonable.
But I still haven't figured it out, how can I notify the backend that the user has exited the game?
For example, by setting up a socket structure, I can send a request per second in the backend, the backend processes this request and understands that the user is still in the game, if the request does not come, the user is not in the game and acts accordingly.

I have such ideas in my mind, but I'm thinking how can I do this without using the socket and listening infrastructure.

#

How do you think I should proceed?

static badge
#

Got a question about NGO of which I couldnt find answers in the docs.
The .OnValueChanged action called when NetworkVariables are changed, is it invoked only on clients or also on the server? And im not talking about host mode

#

Same with NetworkManager.Singleton.OnClientDisconnected ...

#

Am I missing something in the docs?

#

I cant be testing every event on execution side

sharp axle
sharp axle
static badge
#

thx

sly pawn
#

Is it common for multi-player fps games to do both tcp and udp protocols?

sharp axle
vagrant garden
jagged fulcrum
#

How can I check that a player is already connected on a client using the authentication service? I don't want a player to log into the same account through 2 different clients.

sharp axle
jagged fulcrum
# sharp axle Probably use Cloud Save to save logged in status

How will I check that the player has exited the game? After all, I need to notify the cloud save side that the user has exited the game.
But I can't control the exit status of the game. Methods such as OnApplicationQuit do not work in communicating with these api services.

sharp axle
jagged fulcrum
sharp axle
jagged fulcrum
# sharp axle No its part of NGO

I made a lobby system using Lobby Service. Therefore, there is no NGO connection in my project at the moment. I plan to switch to NGO when the lobby functions and controls are completely finished. Can I do this without using NGO?

sharp axle
jagged fulcrum
sharp axle
dim jolt
#

How do the length in ms that it took for a server to recieve a serverRpc from a client after its invoked, been struggling this for HOURSSS

#

i need this so that i can adjust a projectile position based on the time difference in ms so that the bullet is synced

dim jolt
#

what im doing rn is taking the server time on the client, sending it to the server, and then subtracting the servers server time from the recieved server time

#

is that accurate?

#

im tryna adjust the projectile position on the server

sharp axle
sharp axle
dim jolt
#

especially with gravity

#

where gravity is -9.8m/s im taking the value of gravity and multiplying it by the calculated latency (serverTime - RecievedServerTime) and it ends up very loww when spawning it

dim jolt
#

nvm im dum

burnt tiger
#

Anyone managed to get Unity Transport 2.0 running?
Keen to check out the websocket stuff they have

white ledge
spring crane
stuck anchor
#

What's the best way to handle projectile shooting for a 2d top down game using Netcode for Gameobjects? I'm using rigidbodies on the projectiles but they are lagging, for the client they despawn way before they visually hit the enemy

#

I thought about shooting a dummy projectile locally, but I don't know how to "connect" it to the server side bullet so it gets destroyed when the server bullet hits something, also I don't know how to hide the server bullet for the local player

sharp axle
stuck anchor
#

If the server object has no visuals, how will other players see eachothers projectiles?

#

Just by calling a ClientRPC that someone shot a bullet and spawn it locally for the others aswell?

stuck anchor
#

I want to make players faster when they are close to eachother, why does this script only work on the host?

#

The other player's speed stays normal while the host gets faster

sharp axle
stuck anchor
sharp axle
stuck anchor
#

I'm so confused rn

sharp axle
stuck anchor
#

I can try that but why does that script not work?

sharp axle
pallid ether
#
public override void OnNetworkSpawn()
    {
        if (IsServer)
        {
            var rpcParams = new ClientRpcParams
            {
                Send = new ClientRpcSendParams
                {
                    TargetClientIds = new[] { MatchManager.PlayerB.ClientId }
                }
            };
            FlipClientRpc(rpcParams);
        }


    }

    [ClientRpc]
    private void FlipClientRpc(ClientRpcParams clientRpcParams = default)
    {
        if (IsOwner) transform.Rotate(0, 0, 180f); //player does own
    }

can someone explain why transform.Rotate() doesnt work? I get an error saying "Deferred messages were received for a trigger of type OnSpawn with key 16, but that trigger was not received within within 1 second(s)." if i try to rotate from the clients editor it works fine

#

i also tried calling Rotate from OnNetworkSpawn as client and nothing happens

pallid ether
#

so i moved the clientrpc call to start and it works but im still getting the error

hybrid slate
#

Is there a JSON-RPC library out there for Unity?

elfin sandal
#

Ok so I have this system here which moves the player cs private void FixedUpdate() { if (!IsOwner) return; PhysicsServerRpc(); } [ServerRpc(RequireOwnership = false)] void PhysicsServerRpc() { rb.AddForcAtPosition(Force, pos); }So the issue is that the host can move its gameObject, but the client can't. The gameObject has a network object a network transform and a network rigidbody thingy on it.

shrewd junco
elfin sandal
shrewd junco
#

Do you have a network transform, or did u use some client network transform?

shrewd junco
#

Or maybe show the full script, because i think there might be some other code causing this issue then thats not being shown

elfin sandal
elfin sandal
old bane
#

briefly looking around it seems theres several methods for hooking up multiplayer, i am a pretty noob dev, looking to hook up basic multiplayer for pvp and coop game play 2-4 ppl any suggestions on assets that would simplify this?

sharp axle
elfin sandal
#

So I am confused how I should do input?, So I managed to sink up the moving gameObjects using network transform and server rpc's. But now that I wan't to make the player control the gameObjects using this: ```cs
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");

elfin sandal
shrewd junco
elfin sandal
#

simply like this? cs movement.x = Input.GetAxis("Horizontal"); movement.y = Input.GetAxis("Vertical");

shrewd junco
#

You set networkvariables slightly differently, and u want to make sure only the owner is trying to set them

#

you should experiment with network variables first to understand how they work, the doc has great examples

shrewd junco
elfin sandal
#

and inputs working now, wooo^^, thanks mate

shrewd junco
#

np

elfin sandal
# shrewd junco np

hey can I ask you one small other question is there any obvious reason why my mutliplayer doesn't work when trying to play with people on another internet

tidal cape
#

Hello guys, I just have a problem with NetManager script (2022.3.3f1, NetCode for GameObjects 1.5.1) I can't for the life of me add the player prefab in the network prefabs list. It's a known issue?

shrewd junco
shrewd junco
#

one should be created for u at the assets folder by default, but if not you can still create your own

tidal cape
#

I understand that I have to add the playerprefab into the network prefab list in the network manager, I cannot do that for some reason.

shrewd junco
#

i plug this asset into the NetworkManager

elfin sandal
#

hey is there any obvious reason why my mutliplayer doesn't work when trying to play with people on another internet

sharp axle
tidal cape
#

I resolved it by using NetCode for GameObject 1.2.0

near pebble
#

Hello freinds,
I'm looking into the netcode for game objects stuff and I'm looking at messing around with some client only objects but I've ran into this:
Where despite IsOwner being false it still enters the code block, am I missing something here ?

near pebble
#

Nevermind it eventually decided to read it correctly 👻

sharp axle
stuck anchor
#

How can I despawn an object on collision with a player? I can't just destroy it via GetComponent<NetworkObject>().destroy because only the server can do this, so how do I pass a gameonject as a serverRPC parameter?

stuck anchor
#

I use this script that is attached on the player, but it only works for the host player gameobject and I cant figure out why

#

When an enemy collides with another player other than the host it seems like the OnCollisionEnter wont even get called

forest badger
#

How would I be able to use a dedicated server to host my game? Like how do I set it up and is there any third party services used such as mirror

nocturne vapor
#

this way you don't have to pass a gameobject, since you are executing it on the gameobject you want to destroy

stuck anchor
stuck anchor
#

I don't get why OnCollisionEnter is only called on the Host, I've tried moving the collision logic to the enemy (Server Side) but that also only works for the host

nocturne vapor
#

And you have a debug console on/in the client? Otherwise I couldn't explain why it wouldn't call collisionentered

stuck anchor
#

I use the game build as the host and unity's editor as client

nocturne vapor
#

Hmm that is odd. Depending on what you are doing you could try using a triggercollidrr instead

#

That is what I mostly do, my weapons have trigger collider which I activate and deactivate depending on the state of the attack, it works for me on clients and the host

sharp axle
# stuck anchor I don't get why OnCollisionEnter is only called on the Host, I've tried moving t...

If you are using Network Rigidbody, then only the host/server will get collisions. Triggers will still work on both
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/#networkrigidbody

There are many different ways to do physics in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.

stuck anchor
tame meteor
#

i am using netcode, i have a tool network prefab and a ragdoll (also a network prefab, with multiple rigidbodies). How am i supposed to parent the tool to the hand of the ragdoll ? (it doesn't allow me because i cannot parent a networkobject under a non-networkobject). (but i also can't make the hands networkobject, because then the prefab would have nested network objects)

nocturne vapor
#

Everything else would result in a nasty solution. I even tried havig a point on the hand which the objekt tracks, but that results in latency problems, have it local and you are good to go

south mauve
#

Hey guys where should I start to learn networking I got pointed over here but I'm ngl I don't understand what you guys are talking about 😓 should I use fishnet?

nocturne vapor
#

If I were you I would use NGO or Mirror. NGO is the official unity one and has good documentations, as long as you stick with it. Codemonkey has great videos on how to start and the docs are great as well

If you want to go with third party go with mirror it is used a lot, has a big community and a lot of ressources. Afaik are Mirror and NGO similar enough to learn either one and just transfer the conecepts (the keywords will be different tho)
So use Mirror if you want great ressources or NGO if you'd like to use the unity one and have great ressources but not as many

#

One NGO issue is that you only can use ressources from 2021+ but you will find older deprecated awnsers

#

I've never really worked with mirror tho

latent cairn
#

I read NGO is built for small scale multiplayer, but technically it can handle a lot of players too.
So, what is the worst that could happen if 200+ players join at the same time to the server with NGO?

nocturne vapor
#

that depends on how complicated your game is, but 200+ moving networkobjects will result in massive latency

#

but if you are thinking on 200+ players on one server you will be better off writing your own solution, which can handle load balencing, anyway

tawdry blaze
#

I am super new to unity networking.. I want something like this, A player will be in a room but in VR, another player will change the environment or interact from a computer. How do I achieve this.... from where do I start?

nocturne vapor
#

could you eleborate what you mean?

#

this could be as simple as chaning the scene

tawdry blaze
# nocturne vapor could you eleborate what you mean?

So, A player will be in a room (or scene) where he will be a in VR mode and look around. Another player will be on a computer who will change the walls and paintings of that same room. The player who is in VR will be able to see the changes

nocturne vapor
#

That is kind of tricky, if you are new.
So first you need someway to decide beforehand who id the vr/desktop player. You need to give them a different player prefab or have the same with some internal logic to switch. After that it mostly sounds like spawning networkobjects. You may need a few networkvariabled but nothing too fancy.
How about implementing the core gameplay first. So two players on desktop which can manipulate the walls, you can achieve that part with the docs I think
And think about the vr part later, when you allready have somekind of structure. For example some kind of logic which changes the player prefab when in vr

#

Don't think about the whole thing just yet. Start by solving a small problem, like getting a multiplayer game run at all -> having a player to spawn/manipulate objects -> snyc it properly -> vr implementation

sharp axle
tame meteor
#

I have an issue trying to implement item data synchronization. I have an ItemBase class, than i have some other classes that inherit from it. Firstly the player has a networkvariable of type FixedString64 that is basically the name of the class derived from the ItemBase. Than i have an ItemManager singleton, which contains links between the prefabs for the items and the FixedString64 type name. Some items have consumption property etc. I also need to synchronize these. I tried using INetworkSerializeable and i just cannot, because there is no struct inheritance and i cant use a base struct type for the player item variable. I thought of jsonserializing some properties in a FixedString, but i cannot find another workaround outside that and making a struct with all the possible properties for the items.

sharp axle
tame meteor
#

the item manager only holds the prefabs for the items

#

not the consumption data, that needs to be synced

sharp axle
#

I see. I use scriptable objects for my item managers

tame meteor
#

the items are also mono, not networkbehaviours, so i cannot use networkvariable

mighty lake
#

Do networkvariables sync before the execution of OnNetworkSpawn()?

#

For instance, before P2 joins, P1 made the NetworkVariable integer value to 1. When P2 joins, will they see the value already changed to 1?

shrewd junco
mighty lake
#

How do I make a networked equivalent of Time.deltaTime?

Simply putting NetworkManager.LocalTime.TimeAsFloat seems to just blast things away when I try to move them by code

#

it's like they're super fast

nocturne vapor
#

don't know what you are trying to, but why not just use the delta time of the host? I don't know if there is something similar, it wouldn't make much sense, since delta time is the time between frames and that is not global, the host could play on 60fps while a client may be playing with 240fps, they would have different delta times. If you use the host one it wouldn't matter tho, since if you do the math for one second of movement, the deltatime falls out

#

it works because of what you are trying to say by mutliplying with deltaTime, "i want to move k units in the directions x, y, z per second"

mighty lake
#

Oh sorry I forgot to tell

#

I'm working on a tick-based character controller

#

when I multiplied everything by Time.deltaTime the speeds weren't consistent on different frames per second

nocturne vapor
#

I'm using a client autoritive network transform and just multiply with the local deltatime on the client. Everything else was too much latency for my taste, maybe someone else can help you.
And yes you multipy by Time.deltaTime so it is not different with different fps

vagrant garden
muted olive
#

i have a problem with photon networking, when i get a list of all the players using PhotonNetwork.PlayerList() it sends back the player but then when i get the UserID of the player most of the time it returns null and other times it only returns the master client, does anyone have a fix?

spark copper
#

Guys, what does exactly is NetworkBehaviourId? Is it the same thing as NetworkObjectId? Ultimately, my question is, if i want to have the server tell the client "this is the NetworkBehaviour", how should i do it?

spark copper
#

@sharp axle Ooh thank-you i missed that, exactly what i need !

hearty aurora
#

Does anyone know why unity would be unable to connect to 000webhost from a different location? it works fine at home, but if I would go to, for example, the library, unity doesn't want to connect. if I put the link straight into google it works though.

#

(I know this isn't the exact place for this question, but I don't know where else to ask.)

white igloo
#

idk what to do. yes the player has network object. whats wrong?

spring crane
hearty aurora
amber void
#

ive recently started using coherence networking and i get the issue where i have two players in the same lobby, but their character controllers are swapped (player 1 controls player 2 and vice versa). does anyone know how to fix this?

#

ive come across this issue while using other networking software as well, but im stumped on how to fix this issue in coherence

vague coral
#

I'm getting the strangest ClientRpc bug where a few of my functions will only ever execute on the host and never any connected clients. Its consistently a select few but I can't tell any difference in the code compared to other ClientRpc calls

First debug log image is host, second debug log image is connected client

vague coral
#

I'm calling it from the host

#

its inside a NetworkBehavoir object as well, same object as all my other ClientRpc functions

#

whats even more strange is that the first time the function is called (spawning the player the first time), it actually does fire on the client, but any time its called again for respawning it doesn't happen

#

The function is only ever called from that one line of code though

#

so maybe its like..... hung or something? The client isn't frozen its executing everything else fine but idk if this could be something about having only one function running at a time

sharp axle
vague coral
sharp axle
vague coral
#

No, this is on a central game manager object

#

its still calling all other ClientRPCs, like the Damage one which you can see in the images debug logs on both sides

sharp axle
#

Dunno. Check the network Profiler to see the rpcs getting sent and received

mighty lake
#

There's a problem with my spawn system

Left side = host
Right side = client

Client's body is doubled and the movable body isn't visible to host's POV

    public override void OnNetworkSpawn() {
        base.OnNetworkSpawn();
        GameManager.RegisterPlayer(GetComponent<NetworkObject>().OwnerClientId.ToString(), this);
        SpawnPlayerServerRpc();
    }

    [ServerRpc(RequireOwnership = false)] private void SpawnPlayerServerRpc()
    {
        if (!IsServer) return;
        if (spawned.Value == true) return;
        spawned.Value = true;
        SpawnPlayerClientRpc();
    }

    [ClientRpc] private void SpawnPlayerClientRpc()
    {
        body = Instantiate(bodyPrefab, Vector3.zero, Quaternion.identity).GetComponent<PlayerNetwork>();
        if (IsOwner) SetupLocalPlayer();
        RequestSpawnServerRpc();
    }

    [ServerRpc(RequireOwnership = false)] private void RequestSpawnServerRpc()
    {
        body.GetComponent<NetworkObject>().SpawnAsPlayerObject(GetComponent<NetworkObject>().OwnerClientId, true);
    }
#

adding if (IsClient) return; to RequestSpawnServerRpc() solves the duplication but now they can't see each other because the networkmanager can't spawn the networkobject because it doesn't recognize the hash

#

How my planned architecture should work:

  • NetworkManager spawns empty player instance prefab that has the PlayerInstance script (the one that spawns the actual body)
  • Inputs and local player initialization happens at the player instance's PlayerInstance script
    Why separate inputs and the bodies from their instances? I made a "dynamic" object controlling system that uses an interface called IControllable so whatever is in PlayerInstance's controlledObject shall be controlled by the local player. This is so I can make it easier to implement vehicles later on.
  • Actual bodies of the players are mere "puppets" and are controlled by those instances
  • PlayerNetwork handles the synchronization of the bodies
mighty lake
#

Help would be immensely appreciated, I've been scratching my head over this for a day

weak plinth
#

hello is there problem here ? to load scene to all players photon.pun

if (PhotonNetwork.IsMasterClient)
{
string MapName = DropDownMap.options[DropDownMap.value].text + "Online";
PhotonNetwork.LoadLevel(MapName);
}

edit ( i should've called this line "PhotonNetwork.AutomaticallySyncScene = true;")

verbal palm
#

can anyone tell me what is the better networking system photon or mirror or if any one wanna suggest something i wanna make arcade style car game

crude viper
#

can anyone help me out? Ive been working on an android app that is pretty much all just UI, and i was just working on some scripts and now, for whatever reason, i cant click anything in-game

i think it might be related to multiplayer but i literally have no idea what's causing the issue, what should i do?

#

kinda freaking out :,)

#

like everything was fine and then, next thing, im compiling the game for the 1000th time and now its like the game isn't even listening to any inputs

sharp axle
vagrant garden
marble raven
#

I'm making a MOBA game and ran into a problem that the client when attacking creates a lot of projectiles without taking into account the attack cooldown and i cant understand why. On host everything works fine. I using Netcode For GameObjects.
Full code (if it can help)

vagrant garden
#

You should check for CanStartAttack on the server and handle to cooldown there. Not only will that likely solve your issue it will also protect you from cheaters spamming an attack RPC and ignoring the cooldown.

marble raven
vagrant garden
#

I guess there is a fundamental question on whether you want server or client authority.

#

Most MOBAs (LoL, DOTA) use server authority. So the only thing the client does is send the inputs (where to move, what attacks) to the server and the server runs the full gameplay code

small hamlet
#

Hello, im making a turn based 2 player game, need help/suggestion regarding pause mechanic.
I'm using photon pun 2 for networking

Game needs to be paused for both players when
A) either player has weak internet connection
B) either player has minimized the game/on application lost focus

Issues I'm struggling with

A) how do I know if other player has weak connection

B) how do I check if the other player has regained stable connection? Can't recieve RPC callbacks if game has timescale=0 using pause mode which I realised too late. So that brings me to my third point

C) how do I pause the game on the go when either condition is satisfied, like in middle of a coroutine and tweens

mystic knot
#

I'm working on a 3d multiplayer game using Photon Fusion, but the rotations aren't being shared even though my player has a Networking Rigidbody, anyone know why that could be?

mint sundial
#

what is it mean can you help please guys?

#

how can i solve it

nocturne vapor
spring pilot
#

Hey guys, I'm trying to get some netcode working for guns, does anyone know how to send a list of floats (for timing the shots between ticks) from client to the server?

white igloo
#

i dont see the gun from my opponent.
after removing the network object from my gun. i dont get this warning but dont see the gun?

nocturne vapor
#

You can't spawn a networkobject as a child from another networkobject

white igloo
nocturne vapor
shrewd junco
spring pilot
# nocturne vapor There are networklists if that helps

I found a work around, basically I coded a little decoder doohickey that just converts a string into a list of floats, but now I have another problem, why is Update called once per frame on the owners side but only once every tick on everyone elses 🙄

#

(I mean Update in network behaviour)

nocturne vapor
# white igloo i saw that thanks. but im not seeing the gun

Oh you removed it than it only spawns localy, probably on the other client.
You can have the parent object to be a networkobject and handle the spawning in clientrpcs on every client locally, the transform can be synced as well this way

white igloo
shrewd junco
nocturne vapor
#

Oh yea that is the latency problem. It needs to be client authoritive in order to work properly

shrewd junco
spring pilot
#

Does anyone know how to call a function as the owner once every tick update and NOT every frame update?

#

sorry I really don't know networking

nocturne vapor
#

Can't help you never experimented with that sorry. Never even noticed a difference

spring pilot
#

damn. 😔

white igloo
shrewd junco
nocturne vapor
shrewd junco
# white igloo

Then your gun should be client network transform as well

white igloo
shrewd junco
#

On mobile it's hard for me to see your setup from the screenshots tbh

white igloo
#

yes i spawn playerprefab

shrewd junco
#

That should be fine then since it's under the player prefab

#

It would spawn the same any other object

#

Although I wouldnt have it under the cam

white igloo
shrewd junco
#

Depends what the sphere is, but sure

white igloo
shrewd junco
#

Your camera may act weird in multiplayer, so you may have to disable it for other players

nocturne vapor
#

Isn't the cam disabled on the other players? Which would make it impossible to see it?

shrewd junco
#

Not by default, you have to disable it yourself

nocturne vapor
#

I thought he did that otherwise it makes sense he can't see it because he has the same perspective on client and host

shrewd junco
#

The perspective mightve been fine still

white igloo
#

after puting the gun under sphere. i see the gun from opponent. but when i look up and down. the gun doesnt follow it

nocturne vapor
#

They should really add the camera thing in the getting started part in the docs
It is so easy to miss and causes a lot of problems

shrewd junco
nocturne vapor
nocturne vapor
white igloo
#

or in playercontroller

nocturne vapor
#

Depends where you want to place it, I would put it in the player controller, since it is not part of the logic for the gun but controlling the player

#

Just set the gun rotation to the camera rotation. That what you did before when having it as a child of the camera

shrewd junco
spring pilot
#

basically

#

I store a list of floats

#

these represent different time intervals between ticks when a gun was fired

#

and then uhm

shrewd junco
spring pilot
#

yeah on the other client it lerps between them basically

spring pilot
shrewd junco
#

just use the given functionality, store it in a network list or variable then

spring pilot
#

but I need to clear the string once every tick update on the owners side not the server side, but in networkbehaviour update is called once per frame and NOT per tick (on the owners side)

shrewd junco
#

you cannot store a string in a networkVariable, itll have to be like FixedStringXBytes

spring pilot
#

god damnit

shrewd junco
spring pilot
#

I want the network code to work well even at a very low tickrate like 10TPS

#

so I store a bunch of floats which are basically timestamps between ticks to know when to fire the gun on the other clients side

#

idk I didn't find another way to sync gunshots online

#

so this is the thing I came up with

shrewd junco
#

its likely you really just want networkvariable or list, which will update when the value is changed and also send an event

spring pilot
#

I swear I tried using a list before and it gave me compile errors its like a separate thing a network list right?

white igloo
shrewd junco
nocturne vapor
white igloo
spring pilot
nocturne vapor
white igloo
nocturne vapor
white igloo
nocturne vapor
#

"Camera" is the class
"Camera.main" is the reference of the current active camera
And "Camera.main.transform" gives you the transform of the camera

nocturne vapor
#

Can you send the script? I know it works for a friend in unity 2021.3

white igloo
nocturne vapor
#

I'm german as well
You have: camera.main.Transform.position
It needs to be:
Camera.main.transform.position

white igloo
#

still doenst work but new errors nice

nocturne vapor
#

Ok well than nvm
Thought it just uses the main camera doesn't seem like it. I honestly would have to experiment as well

nocturne vapor
#

Oh the vertical axis is line 65 not line 69

nocturne vapor
#

It tells you that the code in line 89 isn't supported anymore, so probably just comment it out

spring pilot
#

Hey guys I'm still having this problem, as the owner of a network behaviour, how can I call a function after every tick?

#

like how do I as the owner of a network behaviour keep track of ticks?

spring pilot
tight bison
#

so theres this object in my scene that i wanna deactivate im using netcode the servers already in the scene its not spawned by anyone so ig the server owns it i think only the server can disable it if someone else tries to do it it doesnt work is there a way i could somehow request the server to delete it and then update it for all players?

rain fern
#

I'm using the Lobby Service and I have this code to get a list of lobbies:

public async Task<Lobby[]> ListLobbies()
    {
        Debug.Log("Gonna List lobbies");
        try
        {
            QueryLobbiesOptions options = new QueryLobbiesOptions
            {
                Filters = new List<QueryFilter>{
                    new QueryFilter(QueryFilter.FieldOptions.AvailableSlots, "0", QueryFilter.OpOptions.GT)
                },
                Order = new List<QueryOrder>{
                    new QueryOrder(false, QueryOrder.FieldOptions.AvailableSlots),
                }
            };
            Debug.Log("Options instantiated");
            QueryResponse queryResponse = await Lobbies.Instance.QueryLobbiesAsync(options);
            Debug.Log("Got lobbies list with size " + queryResponse.Results.Count);
            return queryResponse.Results.ToArray();
        }
        catch (LobbyServiceException ex)
        {
            Debug.LogError("Failed at Listing Lobbies + " + ex);
            return null;
        }
    }

For some reason, Unity itself is crashing at QueryResponse queryResponse = await Lobbies.Instance.QueryLobbiesAsync(options); when there are available lobbies

sharp axle
white ledge
#

I am making a basic FPS game for learning multiplayer
I am facing an issue whenever other person(client) hit and kill the host player
relay server turn off game for all
how can I fix this issue
like how can I migrate host
or is it a good approach to destroy a player completely or just have to despawn it?

nocturne vapor
sharp axle
white ledge
tight bison
#

also does anyone know how can i load the main menu for every player on game end or disconnect?

sand talon
#

any idea why my POST request is not working?:

IEnumerator SendAPIPOST(string jsonOBJ)
    {
        string postData = jsonOBJ; 

        using (UnityWebRequest www = UnityWebRequest.Post("https://localhost:7248/api/values", postData))
        {
            www.SetRequestHeader("Content-Type", "text/json");

            yield return www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.Success)
            {
                string responseBody = www.downloadHandler.text;
                Debug.Log(responseBody);
            }
            else
            {
                Debug.Log("Request failed with error: " + www.error);
            }
        }

    }

API:

[HttpPost]
        [Consumes("text/json; charset=utf-8")]
        public async Task<ActionResult<string>> Post([FromBody] MyDataModel data)
        {
            if (data != null)
            {
                string response = $"Received: Name - {data.Name}, Age - {data.Age}";

                return response;
            }
            else
            {
                return BadRequest("Invalid data received");
            }
        }

whatever i do, i get the "HTTP/1.1 415 Unsupported Media Type" error in unity

vale palm
#

Hey guys! I'm new to Unity but experienced in C#. I'm using Netcode for Game Objects, Lobbies, and Relay to network a simple turn-based game.

ServerRPCs receive and validate player actions and update a NetworkVariable<GameState> to sync clients. GameState implements INetworkSerializable, and has complex logic in NetworkSerialize - it's sort of a heterogenous circular linked list of structs.

This is not a lot of code and I feel I'm on a good track - but the process of starting two players, connecting, attaching debuggers, Debug.Log-ing etc is extremely tedious, and doesn't lend itself to detailed experimenting.

So I have a few questions, and welcome any guidance:

  1. Are there are any good resources on testing netcode? Anything with a faster feedback loop than building & running multiple players?
  2. For testing INetworkSerializable specifically, is it possible to get a BufferSerializer instance realistic enough to use in a "serialize -> deserialize -> assert" test? I can't instantiate one because the constructor that takes an IReaderWriter is internal, and I can't extend the struct because it's sealed. I could implement IReaderWriter myself, but it's large, and at that point I lose confidence that the test behavior will match runtime.
  3. Is there a better place to ask in-depth questions like this? The official forums seem kind of dead, but maybe stack overflow, GitHub issues...?

Thanks for reading and for any help you can provide! (originally asked in #archived-code-advanced)

shrewd junco
# vale palm Hey guys! I'm new to Unity but experienced in C#. I'm using Netcode for Game Obj...
  1. parrel sync is pretty good, there is also the unity multiplayer play thing but havent used it.
  2. not entirely sure what you want to test with INetworkSerializable but maybe you can subscribe something to a network variable
    GameStateVariableName.OnValueChanged += SomeMethod;
    method
    void SomeMethod(GameState oldValue, GameState newValue)
  3. The Unity Multiplayer Networking discord in the pins has more activity than here. Though overall, since theres many things to use like mirror, pun2, and ngo, the community is probably spread thin
vale palm
shrewd junco
rapid carbon
#

why doesnt it update when helath is changed?

shrewd junco
hollow crystal
#

My player keeps on teleporting to walls and sticking in corners until I click on it in heirarchy/inspector, then it works fine

#

any reason why this might be happening? (player is physics based) (Netcode for game objects)

sand talon
mint sundial
#

in unity mirror networking how can i assign authority to non player object?

crude viper
#

anyone know if this code would work? im kinda new to this
I'm trying to give player "roles" in my game.

    {
        // Add the connected client to the list
        NetworkClient client = NetworkManager.Singleton.ConnectedClientsList[clientId];
        connectedClients.Add(client);

        // Check if the number of connected clients is equal to or greater than the desired number of clients to assign roles to
        if (connectedClients.Count >= numberOfClients)
        {
            // Shuffle the connected clients list
            ShuffleClientsList();

            // Assign roles to the selected clients
            AssignRoles();
        }
    }

    // Called when a client disconnects
    private void OnClientDisconnected(ulong clientId)
    {
        // Remove the disconnected client from the list
        NetworkClient client = NetworkManager.Singleton.ConnectedClientsList[clientId];
        connectedClients.Remove(client);
    }```
marble raven
#

How can I get an object that was spawned at StartHost or StartClient?

drifting niche
#

anyone have any idea what could be causing this error when trying to connect to steamworks?
k_ESteamNetworkingConnectionState_ProblemDetectedLocally

google tells me it usually has something to do with a version mismatch, so I made sure both clients are running the exact same build
a few comments also made me think it's an error you get when you try to connect both a client and a host on the same network, so I hotspotted my phone to my laptop to try that instead. no success
it seems its a super obscure error code that doesnt have much documentation

#

full log here

rapid carbon
#

ps:i m not getting response from photon disc pls help

forest badger
#

how do i get steam profile picture with steamworks?

marble raven
#

Hi, I need to associate an HUD with a character. To do this I use my method (which returns the Player type) to return a local player object.

public static Player OwnPlayer()
    {
        return Singleton.LocalClient.PlayerObject.GetComponent<Player>();
    }

In Player, I Instantiate the character and write it to a variable. In the Player panel script (when connected), I write the player to a variable and pull the character from there to display his data on the screen.

private void OnPlayerConnected(ulong playerID)
    {
        if (player != null) return;

        player = NetworkOwnManager.OwnPlayer();

        Debug.Log("Finded: " + player);
    }

On the server (host) everything works fine, but on the clients the link to the spawned character comes out null. Did I do something wrong?

Player class: https://pastebin.com/zkK3SHFS

drifting plaza
#

yeah, p2p cuts out the middleman, which would result in lower latency. Does lag compensation refer to a specific method?

plucky bramble
#

no theres multiple methods for lag compensation

#

for grenades you can most likely look up rocket / bullet lag compensation methods

drifting plaza
#

okay, thanks a bunch for your time. I now have a solid idea of how to do this, just have to figure out the lag compenstaion part.

plucky bramble
#

but p2p is a communication type, yes a side effect is lower response for things like that but its not the main purpose of p2p

drifting plaza
#

truthfully, 50- 100 ms of latency would be acceptable in my case

#

is that what i can expect from server authortative?

plucky bramble
#

depends totally on where your server and client are

#

if they are in the same room expect <10ms

#

if they are in asia and us >200ms

drifting plaza
#

ok, thanks a bunch

plucky bramble
#

one method that you can use:

  • Sync a timestamp on client and server
  • Server tells client the grenade was thrown at timestamp x
  • Client simulates the flying curve with the offset of the current time to the set timestamp x (like skip the ms that were missed)
plucky bramble
# drifting plaza ok, thanks a bunch

instead of the synced timestamp you can use the ping if your networking library tells you that and check when the packet arrived, move timestamp back by the ping, a bit more unprecise but possible

drifting plaza
#

so, since the client would be ahead of the server, you're moving the client's grenade back to match the server?

plucky bramble
#

lets assume 50ms ping and 0 processing time

#

Client that throws grenade: timestamp 0, animation runs normally
Server gets the packet after 50ms: starts the animation 50ms in and tells clients a grenade was thrown 50ms ago
All other clients get the packet after 100ms: Starts the animation 50ms (what the server said) + ping ms in

drifting plaza
#

makes sense I think

plucky bramble
#

also the client that throws originally is a prediction, if the server has any other data the client should correct with a rollback, but thats more advanced 😄

drifting plaza
#

oh you mean, server side reconcilliation?

plucky bramble
#

dont know that term 😄

drifting plaza
#

That was my plan for covering the physical movement of the players

#

(last question) I don't want to waste any more of your time, but what do you mean when you say starts the animation 50 ms (what the server said) ?

plucky bramble
#

the server knows it received the package after 50ms

#

so it tells the clients "i got the grenade package 50ms ago, please offset the grenade throw by that + your ping"

drifting plaza
#

oh okay, thanks!

#

so the pro of this approach is that the grenade is essentially in sync in every client's position

plucky bramble
#

yep, but its a bit complicated 😄

#

also what plays in your favour would be a granade throw animation

#

so the granade is not actually flying while the clients sync up and you dont skip airtime

runic crest
#

Help-me for Unity Netcode for Entities!

hallow basalt
#

I would implement multiplayer before you build to many systems/features. Preferable if you start from beginning but sometimes you might want to build a prototype and then add multiplayer support to reduce cognitive load. Esp if your prototype/feature is not working out and you want to scrap it. Not all systems would be treated the same obviously like some things really do not have much need for multiplayer and are client side only or what not.

#

If your following tutorials it might be easier to build said system from tutorial and then see how you would rewrite it for multiplayer after? It’s always easiest to implement from start and keep adding network events or what not as you go. It all piles up quickly if you don’t I think.

somber drum
#

Plan in the beginning

fallow adder
#

what do people use to make users accounts in some sort of could service and save/load whatever data I want from them admittedly I didnt look up anything yet but would like to hear whats good for others to maybe save some trouble

sharp axle
drifting plaza
#

If a client instantiates a network object, is that network object automatically instaniated for all other clients or no?

nocturne vapor
drifting plaza
nocturne vapor
#

I mean it can't be synced if the server doesn't know about it

drifting plaza
#

Yeah, I had assumed that but I saw something that made me question it

#

Is there any reason to make something a network object if you won’t be directly sending any rpcs to or from it?

nocturne vapor
#

this is how I spawn stuff, it requires you to write 2 more classes tho

[ServerRpc(RequireOwnership = false)]
    void buildServerRpc(Vector3 pos, Quaternion rot, string name) {
        //Item is a class which holds a prefab and some values, ItemDict is a global Item Dictionary
        Item currentItem = ItemDict.instance.getRegisteredItem(name);
        GameObject toSpawn = Instantiate(currentItem.prefab, pos, rot);
        toSpawn.GetComponent<NetworkObject>().Spawn();
    }
nocturne vapor
drifting plaza
drifting plaza
nocturne vapor
#

it depends on what you are trying to achieve, but that should be fine for most cases

#

the network transfrom is just a shortcut

nocturne vapor
#

no problem

drifting plaza
# nocturne vapor no problem

Oh sorry I do have one last question. In your spawn approach, does the same gameObject on two different clients scene have the same reference or the same NetworkObjectid?

nocturne vapor
#

I never tested it, but it should be, I mean I'm just spawning on the server and let the NetworkObject handle the rest

#

I never really had to mess arround with objectids

real ingot
#

Yo! Just wanna know more about networking and multiplayer. Do you need steam to do multiplayer? If not what is the difference between steam multiplayer and some other multiplayer?

nocturne vapor
# real ingot Yo! Just wanna know more about networking and multiplayer. Do you need steam to ...

to answer your question you don't need steam
more detailed:
The kind of multiplayer
The first quesion you need to ask is what kinda of mutliplayer you want, centralized on a server (dedicated) or decentralized with players creating their own servers/lobbies (p2p)
There is a little more too it, but lets leave it at that for now, in this state you also need to decide what kind of game that is, but thats another topic
I will talk more about a lobby system now

getting it to run locally
The next thing you've got to do is implement your prefered networking solution in your game, since you are on a unity discord I will provide a link to unitys own networking solution
https://docs-multiplayer.unity3d.com/netcode/current/about/

When you get that working you get to a point where you can join the host in lan (local area network, for most people this will simply be their home network, so everything below your router)

making it publicly availabe
The first and simplist option is too simply go to your router and open the port your game uses, but that's less than ideal, if your focus is that your customers can host lobbies, that was okay maybe 20 years ago, but it is not nowadays
The second option is VPNs like hamachi, again it was okay a long time ago, but not anymore
The third option is the most widely used in commercial/indie games, a relay server

relay servers
relay servers are what allows you to not focus on server hosting, while allowing the players not having to engage with technology
this is the point where SteamMatchmaking, Epic Games, Unitys Relay service and so many more come in, simply implement their protocol in your game which is usually simple, there are great tutorials out there for this and you are good to go

Alternatives
-Server hosting, there is always the option to host yourslef
-A server build publibly avialable, so players can host on dedicated servers

Learn more about the available APIs for Unity Multiplayer Networking, including Netcode for GameObjects and Transport.

#

scratched the edge of discords message length on that one
Steamworks docs, if you decide to go that way: https://partner.steamgames.com/doc/features/multiplayer
A good video on how to implement it, with ngo: https://www.youtube.com/watch?v=9CYsQ2Rsr2c

Advatage/Disadvantage of steamworks
There are no running costs involved, since you pay upfront (100$) to even be allowed to release the game on steam and they take a 30% cut of the game sales
If this is a pro or con depends on your view, it was well worth it to me
You can however test with AppID 480, so you can checkout if this is worth it you, I myself developed for 50hours with it, before finally buying an appid

#

hope this answers your questions

real ingot
#

That answered all my questions and questions that I didn't ask but wanted to know. Thanks!

real ingot
#

What is the best net to use. Like netcode, photon, Mirror, Fishnet etc. Which one is really good for a game where all players play in the same world

forest badger
real ingot
#

what about the region servers? How do they work? Does every region has one server for each of them?

forest badger
#

or a special netcode like photon

real ingot
forest badger
#

if youd like to host only in europe for instance then thats fine

#

people from north america could join

#

but they would be getting high ping

real ingot
#

how would you host?

forest badger
#

you can even host it from your computer

#

but that wouldnt be stable if you have too many players

real ingot
#

aight

real ingot
#

what's the best one to use

#

most people use netcode as much as I know

forest badger
#

small game id recommend photon

#

photon is the best one in your list there

real ingot
#

aight thanks

mint sundial
#

hello

#

how can i do convert string to csteamid?

#

i want to do join with id or code system

nocturne vapor
mint sundial
#

more friendly because in this case id is like 10-15 letter

nocturne vapor
# mint sundial how can i normalize it like a 4-letter code

with steam alone? you can't
do you have access to the steamworks community?
https://steamcommunity.com/groups/steamworks/discussions/5/3033726413410711157/

There are however somethings you can do, set the name of the lobby as a code, having a simple server running somewhere, which gets a lobby id and returns a 4 digit code, a simple hashing function, but be aware on how to handle collisions, but these doe seem lilke they are not worth it

#

you could also try, using a different numbering system, the CSteamID is in base10 I think, I could test a quick programm to convert to a custom numbering system with 32 digits

nocturne vapor
# mint sundial how can i normalize it like a 4-letter code

https://pastebin.com/4HdWxGgn
maybe this helps, this is a custom base64 system, which cuts down your lobby code to 4 letters. Because it seems like a lot of the CSteamID is just always the same, I don't know tho, you have to test it

This is python, for easy testing, the same concept should apply to csharp

mint sundial
#

thanks I'll take a look

#

but link not opening

real ingot
#

Need to ask. Can multiplay unity gaming services be used for an open world server where all players are in the same world? As much as I read it's mostly for matchmaking like battle royale games. Correct me if I'm wrong

sharp axle
real ingot
#

If I'm right UNet is best for above 100 players in one server but what is the best place to host the dedicated server?

olive vessel
real ingot
#

Another question. As much as I know there are 2 netcodes: entities and gameobject. Gameobjects netcodes is for simpler game and entities is for more pvp games where you need to predict an attack. Should I use both in my project or only have one installed?

olive vessel
#

Erm no

#

GameObjects is for GameObject architecture, Netcode for Entities is for DOTS

sharp axle
drifting plaza
#

!code

raw stormBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

drifting plaza
#

For sake of the question, will "Time to detonate!" Debug always be reached before the NetWorkManager.Destroy line from the client's pov? https://hastebin.com/share/wexiwivero.csharp

#

Assuming detonateServerRpc is called first

#

Because the way I see it is that detonateServeRpc is called, it sends the Client Rpc which has x latency, then completes the NetworkManager.Destroy statement which also takes x latency to appear on the client? However, im not sure if in practice, the latencies for these two things are always identical?

sharp axle
drifting plaza
sharp axle
drifting plaza
#

hm okay, maybe in that case i'll just have the clients despawn the object on their end since I don't want to have to wait until every client recieves the packet

#

Ty Btw

deep briar
#

guys what are the difference between UDP and TCP

#

im new at server programming

#

what do i need to use in my 1v1 Football game

sharp axle
nocturne vapor
# deep briar guys what are the difference between UDP and TCP

UDP is sending a package and not caring if the reciever recieves it
TCP is sending a package and the reciever sends one back to acknowledge the transfer, if that didn't happen the package gets send again

For gamedev you mostly use udp, that is because once a package would be retransmitted it is most often outdated (like a position transmission on a walking player)

deep briar
#

thank youu

mental pond
#

Hey, guys I want to ask, is better to use Dedicated server in Unity or just make own Dedicated Server in Java or something with Sockets UDP ?

nocturne vapor
# mental pond Hey, guys I want to ask, is better to use Dedicated server in Unity or just make...

that depends on what you want, if you want to build a mmo and you need a lot of control over traffic, to get the most out of it, I would write a complete own solution in c or c++, which can handle loadbalencing and so much more, for other games, which don't need that much of control, try to go with the provided solution and see if it works, there also will be a lot more help in the developing process, if you use a public solution

mental pond
#

I'm so sad because switched between dedicated server and windows is so slow

#

And that's the reason why I'm asking

#

it always compile stuff.................. and that's so boring

#

waste of time

nocturne vapor
#

the question you need to ask is, if it is faster to write and manage your own networking solution
I definetly want to try that one day, but having enough todo atm

mental pond
#

I have done my own network solution in dedicated server

#

Thats thing but I also need to manage rigidbody on server side

#

and that's problem I don't know to to make on custom solution

#

I can't calculate stuff on client side

#

how do I disable ''reload script assemblies''

#

is it possible? it takes so long for no reason my godness

#

there's literally nothing in the project and it takes minutes to make changes on single line edit

#

why they dont compile just files that was changed, so shit

real ingot
#

Can someone tell me which netcode should I use? Netcode for gameobjects or netcode DOTS? I just read that you can't have both on because it could cause some problems. So I can't really decide what should I choose.

olive vessel
real ingot
olive vessel
#

Ergo you're using GameObjects

#

Unless you've installed the Entities packages, you are using GameObjects and need to use that Netcode

real ingot
#

does it matter or no?

olive vessel
#

It matters immensely that you use the right Netcode solution

real ingot
#

for the example if I'll need to add entities or something in the future will it be easy to switch from objects to dots

olive vessel
#

I have no idea

#

I'd say start with the architecture you want, rather than rewriting the game

real ingot
#

can you tell me the difference and uses of the netcode for gameobjects and netcode dots?

#

I've been researching for 2 days and still don't have the clear answer

olive vessel
#

Netcode for GameObjects is a networking solution for GameObject architecture, Netcode for Entities is a networking solution for DOTS architecture

real ingot
#

I'm trying to decide before I move on. Cause my game is a little complicated

sharp axle
real ingot
real ingot
#

I don't really understand anything about entities. This is why I'm not sure to what I should choose atm

sharp axle
real ingot
#

I'm trying to learn what are DOTS and entities right now. That's why I'm asking before doing anything.

#

does it matter much? As I heard netcode for entities is more performant and better.

#

aight never mind

#

I'm still not sure but I believe that I should use netcode gameobjects. I figured out a little about entities DOTS

nocturne vapor
# real ingot does it matter much? As I heard netcode for entities is more performant and bett...

Let me give you a tipp for how to programm in general, just pick one and start. You will pretty soon find limits and capabilities. Researching for weeks over what to try out won't get you anywhere, you will learn by picking one and just start.

Since you are new to networking, have no clue what dots really is (me neither btw) and your first project won't be a big one either way (you always start with a small project, if you don't have years of experience in project planing), just pick the more beginner friendly netcode for gameobjects

If you don't like it you can just not use it after that small project, you learned what didn't work, which is very valuable.

And the concepts of how networking works should be universal anyway

real ingot
#

just sayin

#

gotcha

nocturne vapor
#

It seems like, from what I read, that you don't have that experience in networked games, so writing a quick prototype (as a smaller project) in a solution you pick is a good idea
And I now notice my message sounded way meaner than I meant it to be, sorry
A lot of beginners get stuck in that loop of not deciding what to use and that is "dangerous"

real ingot
#

networking is new for me

#

tho I know that it is important for multiplayer

#

right now I'm just trying to learn more about it

#

cause the past 3 years I've been working on coding random games without networking. Just single player games

#

I'm pretty good at coding but network coding is a really new thing to me

nocturne vapor
#

I see. Well if someone asks if you need steam for multiplayer you immediatly think he is a beginner (which is in no way wrong or anything), so you start to point out mistakes you made yourself, like undecidabilty
If you are quite good at coding and have an idea of what you want from the networking solution, write a quick prototype, in the simplest form you can think of and try it out

real ingot
nocturne vapor
#

The netcode for gameobjects docs are quite well written and should be easy to understand.
You can also look into mirror, which is slightly different, but follows more or less the same concepts, it has a lot of ressources you can learn from, espacially a lot of tutorials.
I would encourage you to watch some of them even if you use ngo, since the concepts are transferable

#

Codemonkey has a long tutorial for NGO that covers pretty much everything
So yeah just pick one, both are beginner friendly

sharp axle
# real ingot yeah nah I just do a lot of research to know more and some page said steam got s...

Steam won't host the servers for you. But they can let player download a server version that they can run themselves.

Code Monkey and SamYam probably have the most up to date tutorial videos out there. Quite a few will be out of date. The official docs are very good. And the Netcode discord is there for more specific questions. We can help you get started if you need https://discord.gg/unity-multiplayer-network

candid ginkgo
#

Hello, I have an issue understanding the general way code is read when working with NGO. I've watched a couple of tutorials (namely the 1h one from code monkey and a tutorial by a guy named cuebat about implementing it with steam). I initially tried to do a little test with client authoritative movement which worked and my general idea was that when spawning a player, I should only enable it's component on the owner's side so I wrote this code ```csharp
public class OwnerComponentManager : NetworkBehaviour
{
public Cinemachine.CinemachineFreeLook cinemachineFreeLook;
private RunnerMovement runnerMovement;
private PlayerInput playerInput;
private Collider playerCollider;

private void Awake()
{
    playerInput = GetComponent<PlayerInput>();
    playerCollider = GetComponent<Collider>();
    runnerMovement = GetComponent<RunnerMovement>();
}

public override void OnNetworkSpawn()
{
    base.OnNetworkSpawn();

    enabled = IsClient;

    if (IsServer)
    {
        transform.position = new Vector3(0f, 20f, 0f);
    }

    if (!IsOwner)
    {
        enabled = false;
        return;
    }

    // player input is only enabled on owning players
    playerCollider.enabled = true;
    playerInput.enabled = true;
    runnerMovement.enabled = true;
    cinemachineFreeLook.Priority = 10;
}

}``` which worked. But now that I'm trying to move everything to be server authoritative it doesn't seem to work for the clients, it only works on the host. When I enabled the components manually from the editor for my clients they finally were able to have collisions, move around, etc... So I'm wondering what I'm getting wrong.

#

sorry if this is a huge message idk what the discord etiquette is

sharp axle
#

Hello I have an issue understanding the

cunning robin
#

is this channel fitting for questions about web api and unity web requests or this is exclusively multiplayer-gameplay related?

pearl tusk
#

[Command(requiresAuthority = false)]
    public void CmdSelect(int characterIndex , NetworkConnectionToClient sender = null)
    {
        GameObject characterInstance = Instantiate(characters[characterIndex].CharacterPrefab);
        NetworkServer.Spawn(characterInstance, sender);

        characterInstance.GetComponent<EnemyController>().target = characters[characterIndex].CharacterPrefab.transform;
    }

I have a multiplayer game with 2 characters, when they are connected to the game, I want both of them to be defined as targets in the enemycontroller script, how can I do this? This code is not working

forest badger
forest badger
pearl tusk
#

characterInstance.GetComponent<EnemyController>().target = characters[characterIndex].CharacterPrefab.transform;

Thanks that's the problem ,the component is not actually in a character instance.

stark slate
#

Hi, can someone tell me if photonView.find() is slow or does it use some caching? I have a lot of PunRPC calls that will use photonView id to find correct object on the client.

nocturne vapor
# mint sundial thanks I'll take a look

I got it working with an invite code of 6 letters now btw
Still need to work on it a bit, but if you are interessted I can notify you and I plan to release that one script opensource, since it involves some byte magic I don't understand myself, but chatgpt helped me
Will make a thread out of this and post a video in it

paper sentinel
#
    IEnumerator getRequest(string url)
    {
        UnityWebRequest uwr = UnityWebRequest.Get(url);
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }
    }````how do i make this work for a http server?
nocturne vapor
paper sentinel
#

unity wont allow me, only if i use a https server

#

im trying to not buy a domain and an ssl certificate

keen plover
#

hi everyone, im trying to make 2d multiplayer game and I have InputField where player can write something and it will appear above player head in a speech bubble but it doesnt let me send message, I can write it down but when I click LeftShift as I put in the script it wont send that text, it just stays in inputfield. This is script: https://hastebin.com/share/okulizexov.csharp

real ingot
#

Question. Should I assign all the values and transforms and stuff through script and only through script?

#

I got cameras for difference players and for some reason the host is taking the camera from the client

#

Is it cause I'm assigning the stuff through inspector?

#

oh and another question. I got a parent that holds all the player stuff and I have the network object on the parent. Should I do that or should I just give the network objects to all player objects.

real ingot
#

I don't really understand this warning.

shrewd junco
shrewd junco
shrewd junco
real ingot
#

I'll do this tomorrow since I'm out but thanks for the help

real ingot
#

Oh and I assigned the cameras through script and it still has the same problem

#

It might be cause I didn't assign the prefab list in the network manager

shrewd junco
#

Like some new player joins -> disable their camera for me.

real ingot
#

And the prefabs are assigned. The player and the network prefab

real ingot
#

Don't know the cause

shrewd junco
shrewd junco
lost raptor
#

although I'm not sure if using ClientNetworkTransform is a bad thing

#

like what are the cons of using it?

#

why or why not use it

shrewd junco
#

If you want server authority, then you cant really use ClientNetworkTransform. the issue u were having in #💻┃code-beginner was likely because the server was trying to run the entire code of gathering the input and moving the player. You can have the player update its input via Rpc or network variables, then the host moves everyone based on that

#

ClientNetworkTransform is nice if you want everyone to move themselves and have no concern about hackers ruining multiplayer experience

#

although i had some issues with it and rigidbodies, since syncing them is kinda really annoying.

lost raptor
#

I tried doing this

    [ServerRpc]
    private void MovePlayerServerRpc()
    {
        // Move horizontally
        body.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * speed, body.velocity.y);
    }


    void Update()
    {
        if (!IsOwner || !Application.isFocused) return;

        MovePlayerServerRpc();

        // Hang time
        if (isGrounded()) {
            hangCounter = hangTime;
        } else {
            hangCounter -= Time.deltaTime;
        }

        // Jump buffer
        if (Input.GetButtonDown("Jump")) {
            jumpBufferCounter = jumpBufferLength;
        } else {
            jumpBufferCounter -= Time.deltaTime;
        }

        // Jumping
        if (jumpBufferCounter >= 0 && hangCounter > 0f) {
            body.velocity = new Vector2(body.velocity.x, jumpForce);
            jumpBufferCounter = 0;
        }

        if (Input.GetButtonUp("Jump") && body.velocity.y > 0) {
            body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
        }
    }
#

but it didn't work either.

#

I get why it wouldn't work for the jump but the left & right movement didnt work either

shrewd junco
#

in your rpc add a debug
Debug.Log($"Player {OwnerClientID} moving {Input.GetAxisRaw("Horizontal")}");
and you'll see what the issue comes down to

lost raptor
#

what is OwnerClientID

#

owh its Id

shrewd junco
#

yea the ID of whoever owns this object

lost raptor
#

where do I see the logs?

#

they're in some file somewhere right?

#

I'm on mac

shrewd junco
#

with parrel sync you can run multiple editors and see it like that. there is also a multiplayer tool for like newer versions of unity

lost raptor
#

I have a package called Multiplayer Tools

#

idk what it is for tbh tho

#

rn I'm just rebuilding the game everytime

shrewd junco
#

otherwise yes theres a file somewhere, but ive never directly opened it. I just made a custom text area to display all logs for myself on screen.
You should be able to run the host in the editor, and the client on the build and see the logs on the editor. Since this one is a server rpc, the server will print it

lost raptor
#

but I think I have used parrel sync b4 in some tutorial I followed

lost raptor
#

lemme try that

shrewd junco
#

there is Multiplayer Play Mode and ParrelSync, ive only used parrel sync though

lost raptor
#

"There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene."

#

how do I remove this

#

it's taking up the console and I can't see my logs

shrewd junco
#

likely because of the 2 cameras, temporary solution is to disable the audio listener on one camera if you want to just see the other logs now

lost raptor
#

it is because the camera is nested on each player prefab

#

the "Main Camera"

shrewd junco
#

the real solution is to disable the other players camera when they join, since you really dont need to see theirs

#

yea

lost raptor
#

but would they still be able to see?

#

so I'd be disabling it only for my side?

shrewd junco
#

yea, itd be like on my game i disable your camera but keep mine on. You disable mine but keep yours on

lost raptor
#

owh I get it

#
Player 1 moving 0
UnityEngine.Debug:Log (object)
#

that's what I'm seeing

#

althought should I go back to using the Network Transform cuz I'm using the client one for the moment

#

probably

#

lol

shrewd junco
shrewd junco
shrewd junco
#

client network transform has its flaws, like you cannot really prevent hackers. But its more responsive

#

since the client doesnt have to wait for the server to move them

lost raptor
#

how would I go about fixing that exactly? 😅

shrewd junco
#

i use a network variable to update what the clients input is, then move based on that on the host

lost raptor
#

so just pass the input to the server rpc then?

#

as an argument

#

and use that when updating the velocity

shrewd junco
#

well you would either pass the value, or use a network variable

lost raptor
#

what is the difference?

shrewd junco
#

but you'll really need to experiment with how these work to understand them, it is a weird concept at first

lost raptor
#

I thought they're the same ngl

shrewd junco
#

network variables only update on change, and everyone is notified of this change. you can set the networkvariable so only the owner can update it

lost raptor
#

a network variable just seemed like more work so I used a server rpc

#

lol

#

yeah on the network variable u can set who reads and writes to the variable

shrewd junco
#

i think in CodeMonkey's tutorial, he goes over network variables slightly. Maybe look at that or experiment yourself to see how they work

lost raptor
#

yeah he did

#

I've also used them b4 but I didn't fully understand them at the time

#
    [ServerRpc]
    private void MovePlayerServerRpc(float horizontalInput, bool verticalInput)
    {
        // Move horizontally
        body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

        // Hang time
        if (isGrounded()) {
            hangCounter = hangTime;
        } else {
            hangCounter -= Time.deltaTime;
        }

        // Jump buffer
        if (verticalInput) {
            jumpBufferCounter = jumpBufferLength;
        } else {
            jumpBufferCounter -= Time.deltaTime;
        }

        // Jumping
        if (jumpBufferCounter >= 0 && hangCounter > 0f) {
            body.velocity = new Vector2(body.velocity.x, jumpForce);
            jumpBufferCounter = 0;
        }

        if (verticalInput && body.velocity.y > 0) {
            body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
        }

        Debug.Log($"Player {OwnerClientId} moving {Input.GetAxisRaw("Horizontal")}");
    }


    void Update()
    {
        if (!IsOwner || !Application.isFocused) return;

        MovePlayerServerRpc(Input.GetAxisRaw("Horizontal"), Input.GetButtonDown("Jump"));
    }

rn this is what I came up with

nocturne vapor
lost raptor
nocturne vapor
#

Try if IsLocalPlayer that is what I use, it is a bool, if the object is the clients player object

lost raptor
lost raptor
nocturne vapor
#

You can, you can also use a NetworkTransform, which handles everything for you. But per default this is server authoritive, so clients can't change it, the docs mention how to make it client authoritive

lost raptor
#

I am using a NetworkTransform

#

I don't want to make it client authoritive that's what I was struggling with

#

cuz just switching networktransform to the clientnetworktransform fixes the issue

#

but I didn't wanna use it

#

I managed to get the horizontal movement to work but the vertical movement is not working on either now

#
    [ServerRpc]
    private void MovePlayerServerRpc(float horizontalInput, bool verticalInput)
    {
        // Move horizontally
        body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

        // Hang time
        if (isGrounded()) {
            hangCounter = hangTime;
        } else {
            hangCounter -= Time.deltaTime;
        }

        // Jump buffer
        if (verticalInput) {
            jumpBufferCounter = jumpBufferLength;
        } else {
            jumpBufferCounter -= Time.deltaTime;
        }

        // Jumping
        if (jumpBufferCounter >= 0 && hangCounter > 0f) {
            body.velocity = new Vector2(body.velocity.x, jumpForce);
            jumpBufferCounter = 0;
        }

        if (verticalInput && body.velocity.y > 0) {
            body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
        }

        Debug.Log($"Player {OwnerClientId} horizontal {horizontalInput} vertical {verticalInput} isGrounded {isGrounded()}");
    }
#

verticalInput is always false for some reason

#

isGrounded() is working cuz its displaying True

nocturne vapor
#

Oh I see, well than you need to handle everything in serverrpcs. But you will need to write client side movement prediction, the latency would make it horrible to play
Lets assume a ping of 16ms, which is a good ping
Client --16ms-> Server --16ms-> Client = Latency of 32ms just in networking not even processing
60fps->one frame is 16ms, so your network traffic alone will take twice as long as a frame rendering in the best case

So this makes everything a lot more complicated

lost raptor
lost raptor
#

that does sound complicated

#

but better safe than sorry imo

#

I feel like its easy to abuse the client authorative movement

nocturne vapor
#

Than Input.GetButtonDown("Jump") is probably not working, try to debug it, maybe using a different key for testing or just passing constant true, to check if the issue lies in the server rpc

lost raptor
#

I passed true to the verticalInput and somehow its always jumping when I move to the right

shrewd junco
lost raptor
#

if I press the jump button nothing happens, and its normal when I move to the left

#

but once I press right

#

it moves to the right as well as jumps at the same time

#

like a diognal motion

#

diagonal*

#

thats very weird ngl

nocturne vapor
# lost raptor I feel like its easy to abuse the client authorative movement

That depends on what you are working. My casual coop survival game, simply doesn't need the intervention of a server for moving. Client authorative movement makes sense in that case, in a competetive setting, it makes sense to not use it.

You can also do a mix, use client authorative, but check for every movement update, if that makes sense on the server, if not force reset it

lost raptor
lost raptor
shrewd junco
nocturne vapor
#

Yea, but a bit simpler, since you are just checking if the movement was allowed, which in a highly competitve game, could surely be abused somehow.
In mathematics it is easier to verify that a solution is correct than actually calculating the solution from scratch, thats why this could be one approach which makes it easy to have both instant client side movement and a system which isn't as abusable as client authorative movement

lost raptor
#

do u think its the hangCounter that's causing the issue, also I figured a new thing where when the client is jumping it goes down very very slowly and if I go to the left it goes down faster, I somehow implemented diagonal movement.

Player 1 vertical True isGrounded False jumpBuffer 0 hangCounter 0.05445842
#
    [ServerRpc]
    private void MovePlayerServerRpc(float horizontalInput, bool verticalInput)
    {
        // Move horizontally
        body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);

        // Hang time
        if (isGrounded()) {
            hangCounter = hangTime;
        } else {
            hangCounter -= Time.deltaTime;
        }

        // Jump buffer
        if (verticalInput) {
            jumpBufferCounter = jumpBufferLength;
        } else {
            jumpBufferCounter -= Time.deltaTime;
        }

        // Jumping
        if (jumpBufferCounter >= 0 && hangCounter > 0f) {
            body.velocity = new Vector2(body.velocity.x, jumpForce);
            jumpBufferCounter = 0;
        }

        if (verticalInput && body.velocity.y > 0) {
            body.velocity = new Vector2(body.velocity.x, body.velocity.x * 0.5f);
        }

        Debug.Log($"Player {OwnerClientId} vertical {verticalInput} isGrounded {isGrounded()} jumpBuffer {jumpBufferLength} hangCounter {hangCounter}");
    }
#

I think its the jumpBufferCounter cuz its always 0 for some reason

#

okay I fixed it

#

but now I got another issue lol

#

when I connect a client, the camera switches to the client's for both the host and the client

#

I think this is what u were talking about having to disable the camera

nocturne vapor
lost raptor
#

well

#

ugh

#

how?

#

I get how to get the player's camera

#

but how do I disable everyones?

#

do I make it disabled by default

#

and when its created enable it?

nocturne vapor
#

disable it in the prefab and enable it on Start, with .SetActive(true), if IsLocalPlayer is true

#

you can also just do .SetActive(IsLocalPlayer)

lost raptor
#

if IsLocalPlayer or IsOwner ?

#

or both

nocturne vapor
#

IsLocalPlayer, beacause you want to check if that object is the clients playerobject

lost raptor
#

IsLocalPlayer && IsOwner

#

owh

#

wait

nocturne vapor
#

if it works just do both

lost raptor
#

ur right

#

cuz if its not a local player

#

there shouldn't be an issue

#

unless he's running 2 instances of the game

#

so yeah prob both?

nocturne vapor
#

if the player would be running 2 instances, it would be handled as 2 different clients

#

just try out what works for you

lost raptor
#
[SerializedField] private Camera playerCamera;

playerCamera.SetActive(IsLocalPlayer && IsOwner);

I'm trying this but its not working any ideas why?

#

the SetActive is not a member

nocturne vapor
#

private GameObject playerCamera

lost raptor
#

also I'm doing it on OnNetworkSpawn not Awake

nocturne vapor
#

you want to enable and disable the gameobject

lost raptor
nocturne vapor
#

yes

lost raptor
#

makes sense

#
    [SerializeField] private GameObject playerCamera;


    void Start()
    {
        body = GetComponent<Rigidbody2D>();
        playerCollider = GetComponent<CapsuleCollider2D>();
    }


    override public void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();

        playerCamera.SetActive(IsLocalPlayer && IsOwner);
    }
#

hmm...

#

it is public override or does it not matter?

nocturne vapor
#

public override I think, what does the errorlog in unity say?

lost raptor
#

never mind

#

I disabled the component

#

instead of the camera itself

#

by default

#

like the gameobect

#

j*

#

okay its working now

#

thanks so much

nocturne vapor
#

good, you got this

lost raptor
#

ty ❤️

lost raptor
#

cuz rn mac is the only building option I see

nocturne vapor
#

you can, but you can't execute the build

lost raptor
#

and I know how shitty apple is with this kinda stuff

lost raptor
nocturne vapor
#

you need to install it with add modules, I'm on windows, so I marked mac and linux

jaunty summit
#

I'm following the 'getting started' tutorial for ngo, and I'm stuck on After the client and server spawn, a log displays in the Console of the client and server sending RPC messages to each other. I know this part probably works, but I would like to see it. Executing the built exe just immediately exits because I'm guessing under the hood its spinning off another task or something, so I get no stdout in the termainl, and there's no log in game.

nocturne vapor
jaunty summit
#

I know its bad to stick closely to tutorials, but they should put a note for that right?

#

They pretty much explicitly say you'll be able to see the output somehow, no custom work required

nocturne vapor
#

I think they are expecting you to be familiar enough with unity to know that, because you usually don't start with mutliplayer games if you have no experience in single player games

jaunty summit
#

I have experience working with unity, I'm not an expert but I would've thought there would be a way to pipe Debug.Log to stdout atleast for development builds

#

maybe I can play with the profiler settings or something

#

I also assume its harder to access two instance's simultaneously because Unity Editor will only accept one

shrewd junco
#

Cheaper than buying a whole console I dont need

jaunty summit
real ingot
solemn haven
#

Hey I am using Unity TPSBR photon fusion template and it does not use asmdef-s and it is slow. I tried to create my own to make project lighter but there are 300+ errors now. How to refactor project such that there are many scripts and libraries, over 50+ asmdefs but main project does not use asmdef and I want to add it?

lusty quarry
#

Hello, I am creating a multiplayer game with morror and I would like to make a skin change system, this is where a problem comes to me when I change the color of a material it changes on both players. Would you have a solution?

real ingot
#

try using if(!isOwner) idk if that is gonna work

real ingot
shrewd junco
real ingot
#

ok

keen plover
#

hi everyone, im trying to make 2d multiplayer game and I have InputField where player can write something and it will appear above player head in a speech bubble but it doesnt let me send message, I can write it down but when I click LeftShift as I put in the script it wont send that text, it just stays in inputfield. This is script: https://hastebin.com/share/okulizexov.csharp

real ingot
#

I'm still getting this message

#

the networkPrefabs isn't empty

real ingot
#

Client or host position isn't updated for neither of them. Do I need to have the client network transform on every single object that changes the position? Right now I have it on the parent which is always on 0 position.

#

yep it seems like it.

#

How do I fix the late movement when the player 1 moves but the player 2 sees the player 1 move a little later

real ingot
#

nvm it's good

real ingot
keen plover
#

No cause i dont know where to put debugs

real ingot
#

look where it doesn't run the code. And figure out why. Try doing Debug.Log("Work here!"); in this

#

if it works then everything should be fine in there

real ingot
keen plover
#

Okay i will try that rn

real ingot
#

if that doesn't send the message go debug before the if statement again till it works and then look for the problem where it stops working

#

you might've made a mistake with the DisableSend bool. It could be always false

#

I think DisableSend = false; should be true

#

I might be wrong

keen plover
#

I will try that

real ingot
#

sorry, in here

keen plover
#

yea

#

also this is script made in tutorial btw

#

and here in tutorial it goes !DisableSemd && ChatInputField.isFocused

#

but it showed error here so i just changed it and it doesnt show error

real ingot
#

then make it !DisableSend

#

oh

keen plover
#

Here like this

real ingot
#

for you or in the tutorial?

keen plover
#

yes

#

in tutorial and it is now i changed it

#

this is error

real ingot
#

strange

keen plover
#

yeah

#

this is that bool

real ingot
#

yeah i

#

ik

#

this only happens when you do !DisableSend?

keen plover
#

yes

#

but in tutorial it doesnt show error

#

and i double checked everything i have everything like in tutorial

real ingot
#

what about in the inspector? (Thought I doubt there should be a problem)

keen plover
real ingot
#

ah never mind

keen plover
#

i put these debugs i will see now

real ingot
#

tell me what runs and what doesn't

keen plover
#

only WORK! runs

real ingot
#

expected

#

try putting it on DisableSend instead of !DisableSend and play again

#

and tell me what runs and what doesn't

keen plover
#

i did

#

i tried every method in this if

#

but it only shows WORK!

real ingot
#

makes sense

#

the DisableSend = true;

#

that's the only time it turns to true that means if(DisableSend && ...) doesn't run cause DisableSend is always false

keen plover
#

i should do this?

real ingot
#

but if you do !DisableSend it should work but it throws an error and it doesn't really make any sense

real ingot
#

tell me if it throws an error again

keen plover
#

still only this

real ingot
#

odd

#

I don't think it's the DisableSend problem

#

make sure this is written right

keen plover
#

omg i had that written on wrong object that was the problem

#

thankss

#

but before u go

#

can u help me so player cant walk while i type

#

cause it can move left and right

#

when i write

pearl tusk
#
using UnityEngine;

public class PlayerController : NetworkBehaviour
{
    [SerializeField] private MultiRotationConstraint bodyAim;
    [SerializeField] private Animator animator;

    [SyncVar(hook = nameof(OnWeightChanged))]
    private float syncWeight;

    private bool rangerAiming;

    private void Update()
    {
        if (!hasAuthority)
            return;

        if (Input.GetMouseButtonDown(1))
        {
            if (!rangerAiming)
            {
                RangerAim(1f);
            }
            else
            {
                StopRangerAim();
            }
        }
    }

    private void RangerAim(float aimWeight)
    {
        CmdRangerAim(aimWeight);
    }

    private void StopRangerAim()
    {
        CmdRangerAim(0f);
    }

    [Command]
    private void CmdRangerAim(float weight)
    {
        syncWeight = weight;
        RpcSyncRangerAim(weight);
    }

    [ClientRpc]
    private void RpcSyncRangerAim(float weight)
    {
        if (bodyAim != null)
        {
            bodyAim.weight = weight;
        }

        if (animator != null)
        {
            animator.SetBool("ArrowAim", weight > 0f);
        }

        rangerAiming = weight > 0f;
    }

    private void OnWeightChanged(float oldValue, float newValue)
    {
        if (!isLocalPlayer)
        {
            if (bodyAim != null)
            {
                bodyAim.weight = newValue;
            }

            if (animator != null)
            {
                animator.SetBool("ArrowAim", newValue > 0f);
            }

            rangerAiming = newValue > 0f;
        }
    }
}

The bodyaim.weight value is not 1 on the client side, it goes up to 0.7-0.8 values, how can I solve this?

real ingot
keen plover
#

Okay one sec