#archived-networking
1 messages ยท Page 4 of 1
Well if you make any changes in the editor, you must make a new build to test
i close the run everytime
And rebuild it?
yes
Well you seem to have differences in NetworkConfig
anyidea where i might find that
ive done alot of mindless following and im not sure where exactly everything is at perfectly
I assume the NetworkManager
Well I don't have Netcode installed, so you're gonna ahve to show the NetworkManager component
I would rebuild the client and try again
NetworkConfig is things like that connection approval, and spawning stuff
rebuild client?
Well you've made a build, so I assume you know how to make another build
Probably not
idk i just googled thee warning i got a that was a solution
you happen to know where it is so i can try it?
Along the top I think
Top of the window
calling it a night thanks for all the help really!
Has anyone used quantum v2 photon for multiplayer on unity? Whats their opinion on it. I was thinking of making my own game server, but it seems this quantum stuff has some much done already.
The documentation looks horrid though.
What do you not like about the docs?
Some of the stuff i just cant understand. .e.g. making a custom authenticator it tells me how to impl a interface but it dont explain anything around how the interface methods are called
Good documentation in my eyes is something i understand without reading it multiple times
Maybe im just looking at the wrong thing?
Im looking at the sidebar over here https://doc.photonengine.com/en-us/quantum/current/getting-started/quantum-intro
The revolution in multiplayer games development! Create MOBAs, brawler, RTS, fighting and sports games with the blazing fast deterministic networking engine: QUANTUM.
No You're looking at the right page but you should start with the intro stuff (Quantum 100). Custom authenticators will make more sense once you actually need them they are a bit more advanced.
Thank you for guidance ๐
// PLAYER SCRIPT
[ServerRpc]
void SendMsgServerRpc()
{
MyNetworkManager.SingleTon.ServerAuthTestClientRpc(" ; hi", OwnerClientId);
}
// NETWORKMANAGER SCRIPT
[ClientRpc]
public void ServerAuthTestClientRpc(string message, ulong clientId)
{
Debug.Log("Player: " + clientId + message);
}
Unity Netcode for gameobjects:
is there something wrong with this? When I call it from the client, the code is only ran on the server. Im trying to make it run on all clients. The idea is that the client wants to tell the server to run the code on all the clients
okay im stuck... ive been trying to research work around that my brain can understand and i cant, i have a client host and a client on a build/run, TWO PROBLEMS,
1! when i imput on one of the two instances BOTH prefabs move, so the client controls itself AND the host (and vice versa)
2! im still glad im able to even get connection BUT, when im moving aorund in one window as client the clients movement is not synced to the host and also vice versa
I don't think Rpc can do managed types. Does it work when you remove the message entirely?
using UnityEngine;
using Unity.Netcode;
public class movement : NetworkBehaviour
{
public CharacterController controller;
public float speed = 5f;
public float gravity = -32f;
public float jumpHeight = 2f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
public GameObject PlayerCanvasObject;
void Start()
{
if (IsLocalPlayer)
{
PlayerCanvasObject.SetActive(true);
}
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
can you elaborate on "managed types"? And which message are you refering to that i remove?
Those types which are not value types. ulong is unmanaged, string is managed. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/unmanaged-types
- check for IsOwner to move the correct prefab on the correct client
- did u put a network transform on both prefabs?
And I mean the string parameter of your clientrpc. Take it out entirely, only print the clientId. Does that work?
its only one prefab shared between the two
also i wouldnt be sure where or how to instert IsOwner
put if (!IsOwner) return; in the first line of Update()
see if that works
trying nowe
same results. However, when this delegate is called, it runs code between all clients (aka working as intended)
OnClientConnectedCallback += (ulong num) => ServerAuthTestClientRpc(num);
OnClientConnectedCallback is the Action derived from NetworkManager component
they both still move but only on one instance, no movement on the other
share ur Update() method now
void Update()
{
if (IsOwner) return;
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
you forgot the ! before IsOwner
aww ๐ฆ
so basically, !IsOwner is gonna check if we dont own the network object, then dont run the code below
but since you will own the object, it will run the code for YOUR object, not the other
okay neat i was running a if (!IsOwner) destroy line before.. it worked but it threw errors in game
what are the errors
i dont get them anymore since i took that line out ive been looking for something different which you guys just gave me
ill find what it was hold up
just go ahead and run the code and see if it works now
Netcode Behaviour index was out of bounds. Did you mess up the order of your NetworkBehaviours? Unity Netcode for GameObjects
this is what it was
THAT WORKED !
all i need now is for the movement to transfer to the host
wdym
so if i have both "games" open right client and hos
if i tab in the clients game and mmove around, the movement doesnt show on the hosts screen and vice versa
add a networktransform component to the prefab
it doesnt work because it ruins the camera how?
so everytime i use the transform component, whoever the client is CANNOT look left or right anymore, and it also doesnt even sync the movement anyways
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerNetwork : NetworkBehaviour
{
private NetworkVariable<Vector3> _netPos = new(writePerm: NetworkVariableWritePermission.Owner);
private NetworkVariable<Quaternion> _netRot = new(writePerm: NetworkVariableWritePermission.Owner);
// Update is called once per frame
void Update()
{
if (IsOwner)
{
_netPos.Value = transform.position;
_netRot.Value = transform.rotation;
}
else {
transform.position = _netPos.Value;
transform.rotation = _netRot.Value;
}
}
}
this is my replacement code
well if u want a ClientAuth fix, add this instead
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Multiplayer.Samples.Utilities.ClientAuthority
{
/// <summary>
/// Used for syncing a transform with client side changes. This includes host. Pure server as owner isn't supported by this. Please use NetworkTransform
/// for transforms that'll always be owned by the server.
/// </summary>
[DisallowMultipleComponent]
public class ClientNetworkTransform : NetworkTransform
{
/// <summary>
/// Used to determine who can write to this transform. Owner client only.
/// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
/// </summary>
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
}
so replace that with what i sent?
yeah, see if that works
one sec
hey david you still with me?
Yeah, I just don't know haha. My first idea was that your ServerRpc probably isn't being called, but you said it prints on the server so apparently it is. Calling a clientRpc and it only executes on the server seems weird
Your server is your host, yes?
yes
i actually may have mislead you. the clientRpc is only running the code on the host client and not on any other, when of course called from another client
Your networkmanager script exists on both clients, I assume? And you get the same result, no matter which client calls the ServerRpc?
hey guys when a clien spawns I get this message
[Netcode] Behaviour index was out of bounds. Did you mess up the order of your NetworkBehaviours?
Any sugestion?
the scripts are gone they arent here no more i deleted them i still cant override
yes. The only time it works is when that networkmanager delegate, i showed you, fires. If a client wants to run the method, it only works on the host client ๐ค
i have no idea sorry for breaking your project
ive never ran into that situation before
do you have some sort of if (!IsOwner) destroy line?
wdym "destroy line"?
he is getting the same error i was earlier with that coded
if (!IsOwner) Destroy(PlayerController); ```
humm ok
at the very top of void update
why cant I destroy the script?
i have no clue
do Destroy(this);
THATS what i was doing
hmm
that yeilds the same error
there may be a network destroy function within netcode. try find something like that
maybe its because I am destryong the same script in two diferent places
gona check
nop still the same
help me with this dumb script warning ๐ฆ
i have no idea, ive never ran into something like that
try if (!IsOwner) return;
ok will
I will say, there is a Discord specifically for Netcode for GameObjects pinned here if you want, they may have better answers
thank you
ok it works , but I wanted to destroy the script and not having to return on every update fram
The people working on NGO are somewhat active in there too which is a help
I GOT ITTTTT
why is your player network script derived off of network transform?
dont do that
well, you dont need to do that. It will just makes things more confusing
i just put in the script you gave me
currently googling answering to see if anyone has a fix
open up the script and send me a ss
unity network animator and animator need to be in same gameobject?
animator and a animator control script worked for me
what do you mean?
This channel is only for netcode cause I use Photon?
It's #archived-networking, so any netcode solution
is there anyone who can help me with player networking, ive tried many different things but i cant get anything to work and sync my players
hello, im making a fps game with netcode and when i instantiate the player prefab it doesnt sync over the network
you and me both brotha
trying to use the network animator with my animator for my prefab and i get this when running client and host
RPC method 'OnFire' found on object with PhotonView 1001 but has wrong parameters. Implement as 'OnFire()'. PhotonMessageInfo is optional as final parameter.Return type must be void or IEnumerator (if you enable RunRpcCoroutines).
[PunRPC]
void OnFire(InputValue value)
{
if (view.IsMine)
{
animator.SetTrigger("isAttacking");
}
}
void Update()
{
view.RPC("StaminaRegen", RpcTarget.All);
view.RPC("OnFire", RpcTarget.All);
}
hello, im trying to synchronize the attack movement throughout all my plaers
but its giving me that error
what could be the problem here?
You need to pay attention what you are trying to send over the network. IIRC PUN will only send types that are registered with the system, which are listed in the documentation and the ones you add support for.
yea it was giving me a warning
i just dont understand the "Implement as 'OnFire()' part
That is probably what PUN actually sent once it ignored all the unsupported types, hence the tip.
oh maybe its because i have InputValue on my function
That is what I was referring to
ohh i see
if networkManager can control only one player prefab, how do we control other surrounding objects?
for Mirror
nvm i got my answer
When I try and use this script the camera is on the other player. I looked in the inspector and player is set to the right player.
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class MoveCamera : MonoBehaviourPunCallbacks
{
public PhotonView pv;
public GameObject player;
void Update()
{
// forEach()
if(pv.IsMine){
Camera.main.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, Camera.main.transform.position.z);
}
}
}
trying to use the network animator with my animator for my prefab and i get this when running client and host https://media.discordapp.net/attachments/497874116246896640/1031177657888546836/unknown.png
anyone know a work around to get the animations of a player prefab to sync
Hi. I am using mirror and trying create player with unique name. But NetworkManager gets name form server. What should I change?
public class NetworkRoomManagerNames : NetworkRoomManager
{
[SerializeField] private InRoomName inRoomPlayerName;
public override GameObject OnRoomServerCreateGamePlayer(NetworkConnectionToClient conn, GameObject roomPlayer)
{
var gamePlayer = Instantiate(playerPrefab);
gamePlayer.GetComponent<PlayerName>().playerName = inRoomPlayerName.Name;
return gamePlayer;
}
}
public class InRoomName : NetworkBehaviour
{
public string Name { get; private set; }
public void GenerateName()
{
Name = Guid.NewGuid().ToString();
}
}
public class PlayerName : NetworkBehaviour
{
[SyncVar] public string playerName;
}
What do the docs say?
Which one do you refer to? The local userID? The local actorNumber (which identifies a client in a room/match)?
And which SDK do you use? PUN, Fusion ..?
Hello, I would do a small proiect: create a card game with a server and 2 client where they can enter and play. Which technology can I use between Mirror and Netcode?
Either, choose a solution that you like
Hi there, one newbie question, it's safe to use port 7777 as default? Or what's the best practice regarding ports? thx!
Sure 7777 works, there's loads of ports and a big list on Wikipedia if you want to look for one that's not used
not sure what api you are using, most for the most part if you start listening on a unassigned port so port 0, the OS will assign a free port for you
just sending messages through the unity transport component, so we need the IP / port
any port that isnt used by the default ones like HTTP, HTTPS, FTP, TCP and so on are fine
i'd check the list just to make sure
i created a separate camera for each of my players
i guess that makes more sense too
hello, I am having problems with the new netcode for game object thing, tbh I haven't ever written any multiplayer games ever, I've been strictly working on singleplayer games
so this might sound elementary
I am having problems with assigning cameras to each player
I can't get each instance of the game to only use that camera, and that camera only
it always grabs the newest camera in the scene
I tried making the cameras offline (they don't have network objects) but they still exist in the hierarchy of both
Put the camera on the player prefab, then check if this is the local player, if not disable the camera
does disabling the camera on one side, not disable it on the other?
No, not unless you make it that way
I tried that already
still doesn't work
Define doesn't work, because I've done it and it has worked
doesn't work meaning it still grabs the latest created camera
Latest created being the newest player?
yes
So the newest player that isn't the local player should disable their camera on our client
Have a component on the player object that checks if this is the local player, if it is not, disable the camera
ok
By grabbing the camera, I assume you mean the viewport switches to it
yes
Right then this ought to work
like this cs private void OnConnectedToServer() { if (!IsLocalPlayer) GetComponentInChildren<Camera>().enabled = false; }
If this is on the player, and the camera is a child, yes
Is OnConnectedToServer actually called?
Surely it should be an override or something, I don't think it's called
What Networking solution is this?
netcode for gameobjects
Right well my guess is OnConnectedToServer is not called
let me see
Is it asking you to override it?
no
there is OnNetworkSpawn
Ok, so use that then
The method has to actually be called to do something
You will have to override that method
that did it
thank you
I realize that with the new netcode library there's not going to be much help, as much as Mirror or UNet
UNet is about to be deprecated
UNet is deprecated, Netcode has docs
should I switch to mirror now, before getting any major work done
Well would switching to Mirror benefit you? What is Netcode lacking that Mirror brings?
Well it depends on how far you've got and if you want to switch now
They're not too different, I personally like Mirror more but that's because I've used it more
well I am making a multiplayer shooter, as my graduation project
you obviously know how concrete it is?
I'm afraid of lunging into netcode, and being later surprised that its immature
I was gonna make a multiplayer project for mine, ended up swapping ideas
Mirror has a good community too, so maybe it'd be best to use it instead
I'll give it a go
I haven't spent much time with netcode either way
only started yesterday
Ah well, you'll have forgotten it by Friday
well I hope it goes well, I have about until next june
and I haven't even started on a proper character controller
Hi, is it a good idea to use Rpc's just to send input/ state data?
I assume this is game critical input
and as I understand it RPC client or server has to go and come back
might introduce some kind of latency
oh I didn't know it had to be returned but now that I think about it makes sense ๐ฎ thanks I guess I'll look into custom messages then
if it must be broadcasted to other objects, you can probably do it localy first, then broadcast ot
I'm trying to make a 1vs4 game. I did this by assigning everyone a number when they enter lobby (everytime they leave or re-enter the lobby they give back the number and it's switched again). I thought this would be an easy way to differentiate between players (different characters, abilities, items,...). I'm starting to get a few problems now tho. My first problem is not knowing how I can put multiple character models with all their own animations and skills on the different numbers. Via a tutorial I made one PlayerObject asset which owns the player mesh, the player controller script, etc. I was thinking that maybe an array of character models would fix that? I'm not sure.
Second and maybe the most easiest problem...
I already threw in one standard character mesh, for when the player is one of the four normal players. I animated it to. Now the problem is that this mesh already appears inside the lobby with animation, but then also appears inside the game without animation
like this
Hey, does anyone know of any good resources to implement a dedicated server client? Can unity build the game client and a dedicated server client from the same project?
It is a seperate camera for each player
OHHH
server build can be used for headless clients as well. if that's what you are asking
try mirror discord help channel ๐
not many of is lurking here
depends on what u mean exactly.
and which netcode.
for example, UNET and Mirror remote calls are zero overhead abstractions. which means that they are as fast and same bandwidth as sending a message manually.
however, some libs allocate strings or use reflection for rpc calls, which would be more expensive.
local userID
wdym docs?
I have problem with RoomOptions in Photon. I want to set CleanupCacheOnLeave to false. I don't really understand how to do it and how to work with RoomOptions at all. So when i tried to make them there a error that this thing doesn't even exist. Why this is happening?
Docs, documentation, manual. You know, the thing that people read to learn/troubleshoot an engine/library/api...
What fixes does the ide suggest? You're probably missing a namespace...
What the name of namespace that i need?
Does the ide not suggest you any?
nah
Is it configured properly?
So i spawn a damage pop up on the server, how can i then make it face each player locally? i know the rotation part, just unsure how to do it locally to each player
?
Is your ide configured properly? It should suggest you the correct namespace if it is.
Donno what networking solution you're using, but you can probably invoke an RPC that contains the rotation logic.
thanks mate, im using mirror, i thought if i use an rpc each player will see it rotate, so would i just do an rpc and check isLocalPlayer then run the rotation script?
Yes. Where and how it rotates is up to your logic in the RPC.
//Enemy spawns damage pop up
[Server]
public void ServerShowDamage()
{
GameObject damageTextSpawn = Instantiate(damageTextPrefab, transform.position, Quaternion.identity);
damageTextSpawn.GetComponent<TMP_Text>().text = enemyHealth.ToString();
NetworkServer.Spawn(damageTextSpawn);
RpcRotateDamageText(damageTextSpawn);
}
//place this on the player to run
[ClientRpc]
public void RpcRotateDamageText(GameObject damageTextSpawn)
{
if (isLocalPlayer)
{
//get the damage text spawn gameobject, and rotate it to current player
}
}
something like that? and once ive checked if local player, i could just do transform.rotation and that would refer to the current players gameobject, then to move the damage text i would use damageTextSpawn reference?
Depends on where the RPC method is. If it's on the player character, then yes.
its on the enemy, but i probably can try put it on the player
Do you guys have any idea how to fix this one issue?
I already fixed one issue but there is a little more.
It would be awesome if you guys could help out straight away:
That's not how you invoke a method(AddListener)
video told me to do it and I am following it like so
It's not the same as in the video.
I change the stuff a little because my layout style is different
Compare character by character if you have to. It's not just the layout. It's a totally wrong syntax.
It would be even better if you analyze the mistake and learn the proper syntax. Or figure out what led to the misunderstanding.
I am going to slowly take it step by step instead of trying to code fast.
I'm having trouble getting around a issue and I'm not sure how to fix it.
private void OnTick()
{
if (IsOwner && IsClient)
{
Debug.Log("CAN SERVER EXECUTE THIS ? " + IsServer);
}
}```
I have the following code on a player, if the editor is playing as the host this will still run.
Although this is not what I want. I want this code to only run for the client of the host.
But I guess that is not possible to do so? I think the script is only run once if your are the host/client
This is in netcode btw
private void OnTick()
{
if (IsServer && IsClient)
{
Debug.Log("THIS ONLY RUNS ON A HOST");
}
}
private void OnTick()
{
if (IsOwner && IsClient)
{
var bufferIndex = NetworkManager.Singleton.NetworkTickSystem.LocalTime.Tick % BufferSize;
var userInput = GetUserInput();
clientInputBuffer[bufferIndex] = userInput;
clientStateBuffer[bufferIndex] = ProcessMovement(userInput);
SendInputToServerRPC(userInput);
}
if (IsServer)
{
while (inputQueue.Count > 0)
{
var userInput = inputQueue.Dequeue();
var bufferIndex = userInput.Tick % BufferSize;
if (!IsLocalPlayer)
{
StatePayload statePayload = ProcessMovement(userInput);
if (bufferIndex != -1)
{
UpdateStateClientRPC(statePayload);
}
return;
}
if (bufferIndex != -1)
{
UpdateInputOnClientRPC(userInput);
}
}
}
}
[ServerRpc]
private void SendInputToServerRPC(InputPayload payload)
{
inputQueue.Enqueue(payload);
}
[ClientRpc]
private void UpdateStateClientRPC(StatePayload statePayload)
{
if (IsOwner)
{
latestServerState = statePayload;
}
}
[ClientRpc]
private void UpdateInputOnClientRPC(InputPayload payload)
{
if (IsOwner || IsHost || IsServer)
return;
ProcessMovement(payload);
}```
Got it like this now and working
Hey guys, i'm just trying out Networking for GameObjects, and i got done with basic player movement syncing.
I'm currently trying to make the clients be able to find and connect to a host without the host needing to port forward.
I tried researching online and i found a few posts about NAT-Punchtrough, but i didn't find any actual explanations or code examples on how it should be done
Can someone please help me understand it/point me in the right direction? Thanks in advance
The easy answer is to use a relay server. The other options require your clients to configure their firewalls and routers such that a request from the public internet on a certain port gets directed to the right machine on the private network or using a server to moderate the connection setup. maybe this helps https://bford.info/pub/net/p2pnat/
Ah, okay
Thanks for the help
This might be a advanced question but how would we make a button not show for a client but only to the host?
Or to a specific client?
its very very hard to research lol
if you are using nfg, you can use the networkedmonobehaviour type to get access to thing about the connection
one of them is IsClient and IsHost
you can use those to check when to enable
Docs to help with all the variables
https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkBehaviour/index.html
omg thank you 
[PunRPC]
void StaminaRegen()
{
staminaRegenTime += 1 * Time.deltaTime;
if (staminaRegenTime >= 5f && canDash)
{
staminaRegenTime = 0f;
}
if (staminaRegenTime >= 5f)
{
stamina.value = stamina.value += 0.1f;
}
}
hello, im using photon and my stamina doesnt seem to be syncing at all
each player has its own health + stamina UI (both sliders)
Don't send network messages per frame. Check how network transform is done if you want to stream values.
you mean how the photon transform component works?
basically only send data if the value changes?
and without tying the send rate to frame rate.
okok
i'll give it a look
thanks again!
Stuff like this will result in overcharge fees ๐
Where do we look for if we want to develop register and login menu for netcode game objects or netcode itself?
So data from players can be save.
You might find #archived-unity-gaming-services useful
alright didnt know where to ask thank you
Actually they appear to have not linked anything about it in the channel
0/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class MoveCamera : MonoBehaviourPunCallbacks
{
public PhotonView pv;
public GameObject player;
public GameObject cam;
public Vector3 CamPos;
private void Awake() {
cam = gameObject;
}
void Update()
{
// forEach()
if(pv.IsMine){
CamPos = new Vector3(player.transform.position.x, player.transform.position.y, Camera.main.transform.position.z);
Debug.Log(cam + "teleported to" + player + "with PhotonView" + pv);
Debug.Log(cam + "and" + CamPos);
cam.transform.position = CamPos;
}
}
}
This is not setting the camera to the right player
please help
I've been stuck for 5 days
and my teacher is going to give me an z-
Is it possible to remove data from scriptable objects for server build?
if i do use #if then it breaks the client
Is there only one camera and it is an offline object or are there multiple networkObject cameras to each player?
Pretty sure MonoBehaviourPunCallbacks already has a reference to the correct photon view.
you have to disable the camera if the pv.isMine is false
just add an else statement
Any idea how to attempt reconnection based on FusionBR? Outcome should be: do not destroy player Agent for others when someone disconnects, and reinitialize existing object to reconnecting player.
First goal is achived but second one is more complex ๐ฆ
what's the best way to find a network object by ID? Is this fine? ```cs
foreach (var networkObject in FindObjectsOfType<NetworkObject>())
{
if (networkObject.NetworkObjectId == nID)
{
// FOUND IT
}
}
no, you'd only do this when other approaches would be terribly inconvenient. You'd aim to avoid search like this by injecting the necessary references that objects need when you spawn/create them.
I have to imagine the networking system holds a lookup of IDs to NetworkObjects, considering that the networking system likely has to figure it out very frequently.
@olive vessel I couldnt dm you but login and register menu is very hard to do then networking itself xD
Yes, none of this multiplayer stuff is ever advertised as being easy
I quite liked PlayFab too for that kind of thing
I only suggested UGS because it's Unity's new solution
I saw something about playfab when I was deep researching
hey guys is there a "Network Transform Child" component? I can't seem to find it
?
That documentation is for the old UNet. I imagine you are using Netcode for GameObjects now?
yes
how should I approach this then? I need to sync a child transform position in the server
Pretty sure Netcode for GameObjects has a similar component
Hey can somebody help with the new unity network. I try to let the player move but somehow only the host can move and not the client. What do i make wrong with the input system?
public class PlayerNetwork : NetworkBehaviour
{
[SerializeField]
private InputActionAsset inputActions;
[Header("Movement")]
[SerializeField]
private float movementSpeed = 3;
private PlayerCameraManager playerCameraManager;
private NetworkVariable<Vector3> newtorkMovementDirection = new NetworkVariable<Vector3>(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable<NetworkPlayerData> networkData = new NetworkVariable<NetworkPlayerData>(
new NetworkPlayerData
{
currentHealth = 100,
maxHealth = 100
}, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public override void OnNetworkSpawn()
{
SubscribeInput();
base.OnNetworkSpawn();
}
void Update()
{
if (!IsOwner) return;
ApplyMovementServerRpc();
}
private void SubscribeInput()
{
if (!IsOwner)
{
return;
}
var map = inputActions.FindActionMap("Player");
map.FindAction("Move").performed += PlayerNetwork_performed;
map.FindAction("Move").canceled += PlayerNetwork_performed;
}
private void PlayerNetwork_performed(InputAction.CallbackContext obj)
{
if (!IsOwner)
{
return;
}
newtorkMovementDirection.Value = new Vector3(
obj.ReadValue<Vector2>().x,
newtorkMovementDirection.Value.y,
obj.ReadValue<Vector2>().y);
}
[ServerRpc]
private void ApplyMovementServerRpc()
{
transform.position += newtorkMovementDirection.Value * movementSpeed * Time.deltaTime;
}
}
hey guys In client two weapons spawn instead of just one
if (!IsOwner)return;
print("equiping");
RequestEquipServerRpc();
}
[ServerRpc]
public void RequestEquipServerRpc(){
EquipWeaponClientRpc();
}
[ClientRpc]
public void EquipWeaponClientRpc(){
Destroy(SpawnedWeapon);
SpawnedWeapon=Instantiate(
weapon,
weaponPotision.position,
weapons.transform.rotation
);
SpawnedWeapon.GetComponent<NetworkObject>().Spawn(true);
}
spawning in host side only one weapon spawn correctly, meaning host and client can see the player spawing the weapon,
but if client spawns, it double spawns on its side
I am getting this message NotServerException: Only server can spawn NetworkObjects
So I guess the code is trying to spawn for it self and another that is comming from the server
make it ServerRpc and not ClientRpc
well I fixed by manking the weapons not an network object
Does the new Input system work with the new Netcode?
I would like to have a board game thatโs hosted centrally, and have users sign into the server, and have the server host multiple games simultaneously. Iโm extremely confused on where to even begin. Mirror seemed promising but everything is geared towards client hosted server.
what gave you the idea that mirror is focused on host based games?
Mirror supports client, host and server modes. You are most likely seeing a lot of host examples since they are convenient to showcase.
Ah, that makes sense. Do you know of any resources that help me setup something like a central server client that hosts player data, matches, etc, and simply sends messages to the player clients?
Tbh for that use you are probably better of with a vanilla C# project + HTTP/Websocket, but to answer the question https://mirror-networking.gitbook.io/docs/guides/communications/network-messages
I see. I'd rather keep everything in Unity if possible, in an effort to reduce any need to duplicate logic.
Could I set up a Scene with empty objects, scripted to listen for connections, and send / receive data to serve as the 'backend' within unity?
Yes. I would run your plans through the peeps at the Mirror discord. Probably safe to say that you will be paying for higher end servers while serving less users and be unable to take advantage of potential improvements in modern NET5/6/7 libraries designed for this sort of use.
Got it, I tried to find a mirror discord but didn't find anything on google. Do you know how I can find it?
There is an invite in the pinned post
Thanks ๐
When I copy paste the example code at: https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/fastbufferwriter-fastbufferreader/index.html and use it with a writer with buffer size 1100 it always throws the exception "Not enough space in the buffer"
The serialization and deserialization is done via FastBufferWriter and FastBufferReader. These have methods for serializing individual types and methods for serializing packed numbers, but in particular provide a high-performance method called WriteValue()/ReadValue() (for Writers and Readers, respectively) that can extremely quickly write an en...
What size should the buffer be? also is the size in bytes? The API documentation just says "Size of the buffer to create"
Hi! I'm studying Netcode and I can't find nothing about to setup "tag" for both client and server. Anyone can redirect me how to sync tags ?
Hey everyone, currently I am developing an application where on every start it checks for new images or changed values/settings. Basically I want to synchronise my application with some settings made in a backend on a website! Has anyone an idea how I can achieve that. No experience with Networking Problems like that! Thanks in advance
You would not use dynamic tags on game objects in netcode, but you could build a custom system to sync them (with little value)
If you need the concept of tags in your architecture just make a tag component that derives from NetworkBehaviour and store the tag value itself in a network variable
I agree, instead to check a tag, I can check a network variable!!! Thank you!
Iโd also recommend storing tags as enums or integers to make sync efficient (vs strings)โฆ if you use strings, limit them to just a few characters, say 8 or 16 so you can use allocation free fixed length string types
please help
Yeah! I'm hardly avoiding strings and I'm a lot into network variables integer, so I go ahead there. I Will give a shot with enums too
Can somebody helps - all the time my client is not a owner from itself. How can i fix it?
hey guys help me out, I have two player shooting each other and I got this code to call for the health
public void Damage(int _damage){
OnDamageRequestServerRpc(_damage);
print("damage "+_damage);
}
[ServerRpc()]
public void OnDamageRequestServerRpc(int _damage){
OnDamageRecieveClientRpc(_damage);
}
[ClientRpc]
public void OnDamageRecieveClientRpc(int _damage){
CurrentHealth-=_damage;
if(CurrentHealth<=0){
GameOver();
}
I call public void Damage with an raycast that detects the interface that uses that method
of the player in specific that was targeted
my problem is, when some one calls OnDamageRequestServerRpc I get an "Only the owner can invoke a ServerRpc that requires ownership!"
I already used a system like to spawn objects and it works, but for this case it does not
void equipWeapon(){
if (!IsOwner)return;
RequestEquipServerRpc(weaponDefenition.name);
}
[ServerRpc]
public void RequestEquipServerRpc(string WeaponName){
EquipWeaponClientRpc(weaponDefenition.name);
}
[ClientRpc]
public void EquipWeaponClientRpc(string weaponName){
SpawnedWeapon=Instantiate(
CurrentWeaponEquiped.WeaponPrefab,
weaponPivotPoint.position,
weaponPivotPoint.transform.rotation
);
}
this last one works, so I guess its the same aproach, why does the first one does not?
ok I changed it to [ServerRpc(RequireOwnership = false)] can some one help me out if this the best approach?
https://pastebin.com/bVBxR3Li
team 2 respawns but not team 1
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Does anyone know any SDK I can use for offline Multiplayer?
The goal is to have my laptop as a server and all the devices connected to it via hotpot get to play the game.
I did notice that Netcode allows for offline multiplayer when connected to a LAN cable but it did not work with hotspot.
Codemonkey on YouTube has a tut for that
Tarodev as it also
thats just the same as regular multiplayer, you can use any library like netcode or mirror for that
Yeah, I did follow that, it's not what I am looking for. I am looking for a way to connect using Laptop's hotspot and NOT LAN cable.
thats the same technology
you're always gonna have IPs and send messages between them
Just to clarify, does this work without the internet?
Oh, but for some reason, it does not seem to work.
Any particular settings I might have to change?
PS: I am new to networking, sorry if my question sounds dump
yes, it works on any IP based network
Alright, I will try it out once again, thank you ๐
We need our app to be used behind a proxy server with Proxy-Authorization. To do so it's necessary to set the HTML request's custom header "Proxy-Authorization" like this:
request.SetRequestHeader("Proxy-Authorization", "Basic HereIsTheToken");
Unfortunaly Unity is blocking it saying InvalidOperationException: Cannot override system-specified headers. Does anybody has an idea on how to solve this problem?
Hello, I'm building a card game with 2 players, I coded everything but I missed one important thing, with 2 client, LocalClientId is 0 for both clients when I run it on my PC... there is a way to change the local clientid for one of them?
I don't think that two connected clients can share the same ID. I test my game using two editor instances, and each one has a different LocalClientId when connected.
I did a test by logging from server each time I open a client, and each time the localClientId is 0
are u using Netcode?
I build the game and than I open from the build the game 3 time, 1 server and 2 clients
Yes, I am. I don't use dedicated server, but player hosting instead. Don't know if this affects somehow.
I didn't test this way yet. At least i didn't noticed any issue regarding the IDs.
Can someone DM who is familiar with Photon Fusion?? i need help spawning game objects
any idea on how should I aproach on how to do a game score? I didn't want to keep it client side, only server side, should I use the network variables with a list?
or should I just make a list of network variables?
a variable for each player in game
@uncut bluff Without more context I don't know what are you doing.. but you can have a variable in each client that stores that (even if you set it only on the server), or a list in a Server script with each player score...
so this is what I am trying to do
public class GameScore : NetworkBehaviour
{
private NetworkList <PlayerScore> _gameScore = new NetworkList <PlayerScore>();
}
public class PlayerScore{
public int ID =0;
public int Death=0 ;
public int Kill=0 ;
public PlayerScore (int _id, int _death, int _kill )
{
ID=_id;
Death=_death;
Kill=_kill;
}
}
but I am getting a "The type 'PlayerScore' must be a non-nullable value type" when creating the network list
Make that class a struct
the same error pressits
public struct PlayerScore{
public int ID;
public int Death;
public int Kill;
public PlayerScore (int _id, int _death, int _kill )
{
ID=_id;
Death=_death;
Kill=_kill;
}
}
like this?
now I have the error
The type 'PlayerScore' cannot be used as type parameter 'T' in the generic type or method 'NetworkList<T>'
Well that's technically a different error, progress
Ah
You may need to implement this interface
so I cannot use a struct in a list I guess?
humm ok
I think you should do something like:
`
public struct PlayerScore : INetworkSerializable
{
public int ID;
public int Death;
public int Kill;
public PlayerScore(int _id, int _death, int _kill)
{
ID = _id;
Death = _death;
Kill = _kill;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref ID);
serializer.SerializeValue(ref Death);
serializer.SerializeValue(ref Kill);
}
}
`
sorry, i don't know how to format code xD
still has this error
The type 'PlayerScore' cannot be used as type parameter 'T' in the generic type or method 'NetworkList<T>'. There is no boxing conversion from 'PlayerScore' to 'System.IEquatable<PlayerScore>'. [Assembly-CSharp]csharp(CS0315)
with that last one @cobalt ore
the variable declaration is something like this:
private readonly NetworkVariable<PlayerScore> playerScoreVariable = new(writePerm: NetworkVariableWritePermission.Server);
The type 'PlayerScore' cannot be used as type parameter 'T' in the generic type or method 'NetworkList<T>'. There is no boxing conversion from 'PlayerScore' to 'System.IEquatable<PlayerScore>'.```
private readonly NetworkList <PlayerScore> _gameScore = new (writePerm:NetworkVariableWritePermission.Server);
Maybe because you're trying to use NetworkList instead of NetworkVariable.
Try changing to NetworkVariable and see if that works.
maybe, that was why I was using a class instead of a struct?
After that you may try to adapt to a List.
but I need a list
a list of networkvariables?
fuck this is gona be hard I suck at reading docs
Nobody said Multiplayer is easy
hahaha
well I was thinking in making a gameobject with a script that holds a list of players with their kill/death ratio, and I wanted only that object to be edited in the server, maybe I can save the data of each player in the player game object using RPC and then I fetch all of the network variable data from each player game object?
can that still be hacked?
ah no forget it, because each player prefab network variable would be the same...
you want something like a network game manager, right?
I just found an example of NetworkList inside Boss Room sample
You might just adapt to your needs.
how do i insert a code block here on discord?
in unity learn?
no, inside boss room project
`` ``
3 of those in the beggining and in the end
I made 4 by mistake, no spaces
were can I find that boss room project?
discord do not allow me to send, the code is too long ๐
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
if you want to look the code yourself, it's located at "Assets\Scripts\Gameplay\GameState\CharSelectData.cs"
just search for NetworkList
humm cool thanks man
the key to NetworkList appears to be the "public bool Equals(LobbyPlayerState other)" inside the struct
I am already downloading the project to study it but I am gona try to do this now
ok
ok, good luck
I've been working on online multiplayer for my game using Unity Relay, and it's doing well for now. I'm trying to figure it out how to implement NAT Punchthrough with Relay Fallback, but I couldn't find any guide on how to setup NAT Punchthrough. Do I need a different Transport? Can anyone tell how to begin with it? Thanks!
@cobalt ore I managed to make the list
now it seems that to add rows its not as like a normal list
nice
i did not mess with network lists yet, so I don't know how it works
and the docs seems to be vague yet
yeap I dont know I am getting a null ref when I try to add a row, and it seems that its the same as a normal list as I can see in the example project
Using this rpc on all clients. Everything okay if client is a MasterClient, but things are going weird when client is not. At the part when i am setting the map map = โฆ it not setting it or it sets to (Missing object). And at the transform.position = โฆ it throws Null Reference Exception. Everything other in this rpc is works, except it cant set the variable map for non-MasterClient players.
Hey guys, I'm new to Unity multiplayer and this new Netcode for Gameobjects still doesn't seem to have enough easy sources to learn from. Is there an alternative to use or should I just wait for more learning content to be produced?
There's other solutions like Mirror, or Photon PUN/Fusion
Mirror is probably most similar to Netcode
Would you recommend them over Netcode to a beginner?
Netcode doesn't seem too hard but I keep making mistakes on it and I just can't find a proper in depth tutorial that goes over everything
Beginner at Unity and C#, or beginner at multiplayer?
I found Mirror easier to grasp than Netcode
I'm decent at C# coz I've been using Java for years, and I've started with Unity like 3 months ago, so I do know how to make games, even tho they're not necessarily polished by any means. I wanted to look into multiplayer, but that just seems harder to learn
But Mirror has been around longer, there's lots more information out there about it
Hmm, will look into it
Thank you
Heck yeah, so many tutorials about it
Will switch back to Netcode if it becomes the norm but Mirror seems great for now :D
Is there a better way to 'hold' objects? When I have two players loaded into a scene and I have the non-master client holding something, the master client sees the non-master client's held object jumping into place, causing physics to freak out a little. I do have it set so OnClick() (when the item is picked up) ownership is transferred.
Upon further investigation the strange de-syncing only seems to happen when an object is 'dropped' by one player, and picked up by another.
I'm new to unity, but wanted to get some insight into networking design for a simple multiplayer fps in the future. When designing multiplayer functionality, do you generally lock the server update tick rate to the physics rate, or is it generally independent? How does physics tick rate affect client desync and server tick rate?
Lockstep is a technique you can use for implementing advanced correctness requirements and rollback in competitive or turn based games. in simpler games youโd treat client and server as inherently unreliable and just rely on the network clock to detect and fix desync without implementing actual numberd ticks. It is sufficient in most non-competitive or slow paced games.
A simple architecture would just have client send inputs to a server and receive all changes resulting from these inputs that affect gameplay from the server directly without doing any prediction or anticipation to reduce lag, since the tick here is just happening on the server no further management of it is needed. Alternatively if you donโt need to deal with cheating you can allow all clients to change the game world directly and use the server only for reporting these changes to others, with the result that lag becomes invisible unless two players interact in high-accuracy situations (like shooting at each other), here a tick system is also often unnecessary
example:
should i do that to not run it on a server?
public class FpsCounter : NetworkBehaviour {
private float t;
private long lastTicks = DateTime.Now.Ticks;
private int count;
private int frames;
public override void OnNetworkSpawn() {
if (!this.IsClient) return;
}
public void Update () {
long ticks = DateTime.Now.Ticks;
this.t += (ticks - this.lastTicks);
this.lastTicks = ticks;
this.count++;
if (this.t >= 10000000) {
this.frames = this.count;
this.count = 0;
this.t %= 10000000;
}
}
public int GetFps() {
return this.frames;
}
}
or is that fine? (because this need not run on a server) does it automaticly not run on a server?
public class FpsCounter : MonoBehaviour {
private float t;
private long lastTicks = DateTime.Now.Ticks;
private int count;
private int frames;
public void Update () {
long ticks = DateTime.Now.Ticks;
this.t += (ticks - this.lastTicks);
this.lastTicks = ticks;
this.count++;
if (this.t >= 10000000) {
this.frames = this.count;
this.count = 0;
this.t %= 10000000;
}
}
public int GetFps() {
return this.frames;
}
}
On games that have server browsers, how does the server broadcast its presence to other clients on the internet? I assume there's an sql database somewhere that the server just sends its ip address, server name and whatnot to an sql database sever. Then the client server browsers just retrieve the information from that predefined server. I could be wrong though. Is there a better way to do that?
You don't have to do that with lan servers because checking all 255 ip addresses for a server isn't that hard.
Itโs the way to do it. But with an api and a Webserver in front of the database (for security)
Is there a better way to 'hold' objects? When I have two players loaded into a scene and I have the non-master client holding something, the master client sees the non-master client's held object jumping into place, causing physics to freak out a little. I do have it set so OnClick() (when the item is picked up) ownership is transferred.
Upon further investigation the strange de-syncing only seems to happen when an object is 'dropped' by one player, and picked up by another.
(posting again as I didn't get a response from yday, and am still stuck on the issue)
Hello any networking expert here ^^ . I am trying to parse a Json from URL "https://api.wenlambo.one/meta?meta=1514" and every time I face Handshake failure I tried so many ways but nothing works
hello noob question how can i sync in the unet structure with code the players prefab? like GetComponent<NetworkObject>().syncPrefab ?
it's based on UNET btw. Unity's netcode from 2015. many here may not remember, but we kept working on it when Unity abandoned it
Anyone have any idea why rigidbody collision velocity would be inconsistent with clientnetworktransform?
they seemed to work fine when i was trying to make it server-side, but when i changed to client-side, the variables are really strange. like a normal object falling from a relatively short distance at normal gravity will give me 70 squaremagnitude for collision.relativevelocity
Does anyone have a solution in mirror only for certain game objects to have a rank tag before there name like owner: playername for an example?
All I want is an answer FYI
I don't think you can create tags at runtime
You can create components that hold strings though
Now I understand you only want an answer, but there's probably a different way to do what you're doing
alright because right now I am researching my solution atm
@olive vessel So I can do this by adding on strings to the player object?
@olive vessel do you hav an idea?
I don't deal with UNet, it is deprecated
A component with a public string, sure
Here is an example what I am trying to do.
I want to be able to set tags to specific object next to an object. Like assigning it basically.
Is there a way to do this or any examples that can really help me out? xD
You mean a nametag?
yes but with some tags that are assign as staff and etc. But for default players it will just be memeber
idk if I am making any sense
Right well be specific in future, tags are a different thing in Unity
ah
A nametag is simple, make a component with a networked string or whatever, that sets a text above someone's head
To put the text above someone you can use a world space canvas
right and I did this for an example and its not the best example in the world lmfao.
So I just add a canvas next to that certan object to add the text owner: to that one object?
You can use the same text object, just concatenate strings
Maybe it'd look better to have it on a different Text object in smaller font
Either above or below the name
Are you multiplying the input by Time.deltaTime?
?
I did, yes.
Oh wait, no
My bad, that was just the camera speed in my Script
The movement itself doesn't use it
Lemme add it
Great, now I can't move in the Unity Editor version either
Lemme increase the speed
It works! Thanks!
anyone have any idea why this throws an error? i'm literally just copypasting the sample from the documentation, seen at
https://docs-multiplayer.unity3d.com/netcode/current/basics/object-spawning/index.html
getting this compilation error: ssets\Scripts\PogoCharacter.cs(460,9): error - SpawnVfxServerRpc - Don't know how to serialize GameObject. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. If this type is external and you are sure its memory layout makes it serializable by memcpy, you can replace UnityEngine.GameObject with ForceNetworkSerializeByMemcpy`1<UnityEngine.GameObject>, or you can create extension methods for FastBufferReader.ReadValueSafe(this FastBufferReader, out UnityEngine.GameObject) and FastBufferWriter.WriteValueSafe(this FastBufferWriter, in UnityEngine.GameObject) to define serialization for this type.
Which one?
I can't see one that passes a GameObject in an RPC
Probably because you can't
hmmm... but the spawning has to be done on server side, no?
even if the reference is stored on the server, it seems to throw the same issue
Yeah, like this
Is there a better way to 'hold' objects? When I have two players loaded into a scene and I have the non-master client holding something, the master client sees the non-master client's held object jumping into place, causing physics to freak out a little. I do have it set so OnClick() (when the item is picked up) ownership is transferred.
Upon further investigation the strange de-syncing only seems to happen when an object is 'dropped' by one player, and picked up by another.
(posting again as I didn't get a response from yday, and am still stuck on the issue)
yeah, that is what i did
hmm... there doesn't seem to be any kind of error message thrown, i'm sure im doing something wrong.. but unity does not seem to be giving me any warnings for this
0 errors thrown on either server or client side
Hi everyone, I'm using Unity Netcode For GameObj and I have an void which Updates the Client. But in the editor I get "Server Rpc Method must end with 'ServerRpc' suffix!"
you just add ServerRpc to the end of the function like you see on my screenshot i just posted
but the problem is, that the UpdateClient void is looking like this "UpdateClientServerRpc"
you rename that as well, and you add [ServerRpc] above
yeah, that should work
yeah, i still get the error
you need to add it where it's called as well
show me how you're trying to call it
yeah, what's the error now?
yea, i fixed it
I moved the position for the void in the script (Like at the top in the class) and it got fixed.
Hey, I have a Flashlight which players can pick up at their own discretion, however when someone picks it up after it's instiatiated and drops it and someone else picks it up, it has really bad positioning de-sync and I'm not sure why.
void Click()
{
playerController = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
handCube = playerController.GetRightHand();
this.tag = "HeldEquipment";
GetComponent<BoxCollider>().enabled = false;
GetComponent<Rigidbody>().isKinematic = true;
transform.parent = handCube.transform;
transform.position = handCube.transform.position;
transform.rotation = handCube.transform.rotation;
transform.localRotation = Quaternion.Euler(180, 0, 180);
transform.localPosition = new Vector3(1.8f, -0.2f, -1.7f);
this.tag = "HeldEquipment";
isPickedUp = true;
}
[PunRPC]
void OnToggleEquipment()
{
GetComponentInChildren<PhotonView>().RPC("ToggleEquipment", RpcTarget.All);
}
[PunRPC]
void ToggleEquipment()
{
if (!isPickedUp) return;
isTurnedOn = !isTurnedOn;
lightSwitch.Play(null);
lightSwitch.Play("Click");
GetComponent<AudioSource>().Play();
StartCoroutine(ToggleLight(isTurnedOn));
}
IEnumerator ToggleLight(bool toggle)
{
yield return new WaitForSeconds(.1f);
lightObject.enabled = toggle;
}
void OnDropEquipment()
{
this.tag = "Equipment";
isPickedUp = false;
GetComponent<BoxCollider>().enabled = true;
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
GetComponent<Rigidbody>().AddForce(handCube.transform.forward * 100);
this.tag = "Equipment";
playerController = null;
}
Is there anything obvious there?
i know network parenting is tricky.. one of the docs should mention it somewhere, maybe in networktransform
I managed to 'fix' it by removing the .addForce() from it.
It's probably not the best solution but I'm so annoyed that I didn't think of that before.
Seems to look stable enough so I'll deal with it.
DoorController[] doors = GameObject.FindObjectsOfType<DoorController>();
foreach(DoorController doorController in doors)
{
GameObject networkedDoor = null;
if(PhotonNetwork.IsMasterClient)
{
networkedDoor = PhotonNetwork.InstantiateRoomObject("Doors/" + doorController.name, doorController.transform.position, doorController.transform.rotation);
}
networkedDoor.AddComponent(doorController);
}
I'm currently working on this and trying to figure out the best way to apply already-existing variables to a newly instantiated object.
cannot convert from 'DoorController' to 'System.Type'
Hi, I'm planning to make 1v1 tower defense game. I've never made any multiplayer game, but I'm familiar with Unity. Would You recommend me to use Photon or Netcode?
I just started learning netcode, itโs pretty easy if you follow CodeMonkeys tutorial
Oh that's nice, I also wanted that to be my first entry point into mp ๐
is this the channel for online games?
Sure, it's for networking
Hey I'm having a issue where my server shutsdown after like 3minutes with the error: stack smashing detected, I'm using unity Game Server Hosting.
All I'm doing is sending a boolean to the server every 15 seconds to prevent the client from disconnecting for being idle:
private void SendActivityToServerServerRpc(int inClientID, bool inIsActive)
{
if (inClientID == 1)
{
IsStillPlayingPlayerOne.Value = inIsActive;
}
else
{
IsStillPlayingPlayerTwo.Value = inIsActive;
}
}```
I have a "simple" question which is
is it possible to do an online game for mobile phone devices with Unity
I know it is possible to do an online game or a phone game but idk if the both combined are possible for really amateur teams
is there like.. any way to debug why an a function is not getting called?
i have a simple scenario where the server subscribes to networkvariable.onvaluechanged
now, i've debugged every single variable change.
the variables are being changed from the server, which should be triggering the onvaluechanged function.
but there are just no errors and no debugs of any sort, the function just never gets called.
i tried serverrpc as well, but it just doesn't seem to work.
Multiplayer between two phones? Sure
the bottom line on the image does trigger onscorechanged
It is possible yes
There are games that do that, which would be hard if it were impossible
but somewhere else, (still running on the Server), i change the teamscore value, it debugs that it's getting called, but the onvaluechanged is never called
so what about phone with computer, instead of computer with computer or phone with phone (crossplay basically)?
is it possible or only Amogus can do it?
Well that's a silly comment
If one game can do it, any game can
I am assuming Netcode could do it
You can test it
okay, thank you so much! I should probably
Would you happen to know what it means when my server stop with the error: stack smashing detected?
Nothing, thats the issue, my clients are connected to the dedicated linux server using unity gaming service
And everytime after 3 minutes this error stops the server
True, but I'm not sending any RPC calls or anything
Are you doing anything?
No, only initializing some network variables once the server and client connect
Lets have a look
{
if (!Instance)
Instance = this;
// Initialize all the networked variables
Player1Field = new NetworkList<ReplicatedGameData>(new List<ReplicatedGameData>(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
Player1Field.Initialize(this);
Player2Field = new NetworkList<ReplicatedGameData>(new List<ReplicatedGameData>(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
Player2Field.Initialize(this);
BulletsThatPlayer1Fired = new NetworkList<ReplicatedBulletData>(new List<ReplicatedBulletData>(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
BulletsThatPlayer1Fired.Initialize(this);
BulletsThatPlayer2Fired = new NetworkList<ReplicatedBulletData>(new List<ReplicatedBulletData>(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);
BulletsThatPlayer2Fired.Initialize(this);
}```
So this is happening on the server and the clients, since the script is placed on a object in the scene
If you comment it out is it still borked?
Yea
You mentioned earlier you were sending a heartbeat
Meh I don't get it, you're using Netcode right?
Yes, using Unity.Netcode;
public NetworkList<ReplicatedBulletData> BulletsThatPlayer2Fired;
What's ReplicatedBulletData
A custom struct
Lets see it
public struct ReplicatedBulletData : INetworkSerializable, IEquatable<ReplicatedBulletData>
{
public int TileID;
public int BulletType;
public ReplicatedBulletData(int inTileID, int inBulletType)
{
TileID = inTileID;
BulletType = inBulletType;
}
public bool Equals(ReplicatedBulletData other)
{
return TileID == other.TileID && BulletType == other.BulletType;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref TileID);
serializer.SerializeValue(ref BulletType);
}
}```
And ReplicatedGameData
public struct ReplicatedGameData : INetworkSerializable, IEquatable<ReplicatedGameData>
{
public bool bIsInitialized;
public int TilePos;
public int TileType;
public int FogDuration;
public int DamagedDuration;
public int BuildingType;
public int Health;
public int ShieldTopLeftCornerID;
public int CartType;
public int UpgradeType;
public ReplicatedGameData(GameData inGameData)
{
bIsInitialized = true;
TilePos = inGameData.TilePos;
TileType = inGameData.TileType;
FogDuration = inGameData.FogDuration;
DamagedDuration = inGameData.DamagedDuration;
BuildingType = inGameData.BuildingType;
Health = inGameData.Health;
ShieldTopLeftCornerID = inGameData.ShieldTopLeftCornerID;
CartType = inGameData.CartType;
UpgradeType = inGameData.UpgradeType;
}
public static int SortByPos(ReplicatedGameData a, ReplicatedGameData b)
{
return a.TilePos.CompareTo(b.TilePos);
}
// Don't compare these lol, tiles from different fields are not comparable with one another
public bool Equals(ReplicatedGameData other)
{
return TilePos == other.TilePos;
}
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref bIsInitialized);
serializer.SerializeValue(ref TilePos);
serializer.SerializeValue(ref TileType);
serializer.SerializeValue(ref FogDuration);
serializer.SerializeValue(ref DamagedDuration);
serializer.SerializeValue(ref BuildingType);
serializer.SerializeValue(ref Health);
serializer.SerializeValue(ref ShieldTopLeftCornerID);
serializer.SerializeValue(ref CartType);
serializer.SerializeValue(ref UpgradeType);
}
}```
I've no clue, I thought you might have some recursion in your serialisation
The Netcode Discord is pinned here, might get you help faster
Could it be this: GameData inGameData in the struct constructor
Cause thats not a replicated struct
Its not stored inside it though
As I say, no idea
Alright, thanks for the help though! I'll ask in netcode server in that case
They'll probably have a better understanding of it than I do
hmm i don't get it.. networkvariable.onvaluechanged does not get called on server? also you can't call serverrpc on server?
I'm using Netcode for GameObjects, and I want to be able to show an error message on screen when the user types in an invalid port or address. Is there a quick way to accomplish this?
https://learn.microsoft.com/en-us/dotnet/api/system.net.ipaddress.tryparse?view=net-6.0 TryParse will return false if an IP isn't valid
Oh! Thank you! I will look into it and see if I can get it to work
Thank you so much! You have no idea how much time you have saved me!
500ms is too quick, set to 5s
What would be the proper way to set up a playername, and then synchronize that name to other players upon join, if the player name is stored as a networkvariable?
since each player has team-related things, i assume you'd have to somehow iterate through all connected clients on join on Server, and have them assign the necessary things client-side, on all other clients (that they don't own)?
Thanks for the reply, I'll try this as well! Not sure if this will fix the issue since I'm not getting a timeout message or anything
yea still no idea if that's the issue
I think that maybe GameData inGameData this could be the issue, its a parameter inside a networked struct, and that is not a networked struct, and maybe there it somehow gets fucked? But its not storing it in anyway so yea
I will do a bunch of more testing when I get home and see if anything works!
I doubt it, they're all value types so there's no references being stored
i did a player 2d topdown movement with a joystick for mobile, but when i try to implement multiplayer, that doesnt work, because in my script i cant use the joystick because player becomes a prefab what could i do?
I don't see why the player being a prefab is an issue?
well ig i just asked wrong way
here i need to put my joystick
but everytime i delete the prefab from the scene, so it comes into the scene when i start host
Well surely it's a script on the player?
wdym on player theres player script and i have script on joystick canvas aswell
So PlayerMovement is on what?
Because really with a name like that, one would assume it's on the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public PlayerMovement movementJoystick;
public float playerSpeed;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
if(movementJoystick.joystickVec.y != 0)
{
rb.velocity = new Vector2(movementJoystick.joystickVec.x * playerSpeed, movementJoystick.joystickVec.y * playerSpeed);
}
else
{
rb.velocity = Vector2.zero;
}
}
}```
thats the player one
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerMovement : MonoBehaviour
{
public GameObject joystick;
public GameObject joystickBG;
public Vector2 joystickVec;
private Vector2 joystickTouchPos;
private Vector2 joystickOriginalPos;
private float joystickRadius;
// Start is called before the first frame update
void Start()
{
joystickOriginalPos = joystickBG.transform.position;
joystickRadius = joystickBG.GetComponent<RectTransform>().sizeDelta.y / 4;
}
public void PointerDown()
{
joystick.transform.position = Input.mousePosition;
joystickBG.transform.position = Input.mousePosition;
joystickTouchPos = Input.mousePosition;
}
public void Drag(BaseEventData baseEventData)
{
PointerEventData pointerEventData = baseEventData as PointerEventData;
Vector2 dragPos = pointerEventData.position;
joystickVec = (dragPos - joystickTouchPos).normalized;
float joystickDist = Vector2.Distance(dragPos, joystickTouchPos);
if(joystickDist < joystickRadius)
{
joystick.transform.position = joystickTouchPos + joystickVec * joystickDist;
}
else
{
joystick.transform.position = joystickTouchPos + joystickVec * joystickRadius;
}
}
public void PointerUp()
{
joystickVec = Vector2.zero;
joystick.transform.position = joystickOriginalPos;
joystickBG.transform.position = joystickOriginalPos;
}
}
thats movement which is on my joystick canvas
Right so when the Player is spawned, they're gonna need to use a method to find it
like so
oh
You can't reference scene objects in a prefab
so like i need to find the other methos, that at the start, it connects the script or its not even possible?
Well obviously it's possible to find other objects at runtime
When the Player is spawned you can search for the PlayerMovement that exists in the scene
I don't really get your setup to be honest
If the canvas with PlayerMovement exists in the scene, when the Player is spawned you can find it
yeah its here, the one i drag in the player script is MovementJoystick object
so ig i have to find a way to find MovementJoystick at the start?
I'm getting an error saying that "only the server can despawn objects" even though I'm running the despawn function in a server rpc
So even with having no networked variables in mt game, the server still shuts down after 3min saysing 'stack smashing detected'
Could it be my build confif Launch parameters, that I'm missing something? I have:
-nographics -batchmode -ip 0.0.0.0 -port $$port$$ -queryPort $$query_port$$ -logFile $$log_dir$$/matchplaylog.log -sqp
still kinda stuck on this... maybe i'm just missing something very obvious... how would you synchronize player names?
i'm able to assign teams and names to my players using networkvariables, but if a player's name is set, wouldn't that mean you'd have to assign the textrenderers on every other connected player, but not on their own networkprefab, but on their local versions of every client?
since you can't just synchronize a textrenderer like you can synchronize a networktrasform...
anyone got any tips for this?
The player exists for other people, so give them a network variable for their name, and set their "body"'s text for everyone using it
Should be really simple
they do have a networkvariable for their names. by all accounts it should work, but it's looking strange
for some of the clients none of them synchronized, for some, all but one did
that's pretty much all i did
i thought so ๐คฃ
I wonder if the OnValueChanged event is called when a client joins after the change
It might not be, and that would mean the original client (or host) sees all the names, and the newest sees none of them
ok so ive tested who sees what names; Server: correctly sees everyone, Client1: correctly sees everyone joining after; further clients don't see proper names of the clients that joined previously
My guess is the event is not called when a client joins after a change
You can ask in the Netcode Discord, it's pinned here
Hey everyone! Just dropping by to say that the **Multiplayer Dev Blitz Day is open for your questions! **
Just head to the Multiplayer Discord Server, Unity Forum or Reddit Unity3D to ask anything related to Multiplayer ๐
https://discord.gg/3SzD5agE?event=1032672021110329344
Hello. I'm using Netcode. How can I set player's camera? Each player has a camera as a child object.
I want the player to see from it's own camera.
General rule is to check isLocalPlayer and disable components like the Camera on objects when that is false
Okay, thank you
I found the issue on why the second player can't move. The new input system assigned him to an Xbox Controller. Is there a work around so Unity can assign every player Mouse and Keyboard?
I have a question about Relay/Lobby system.
_currentLobby = await Lobbies.Instance.QuickJoinLobbyAsync();
there is no problem about this part. I'm getting my lobby code via Data property.
Players can find available open lobbies but the problem is after they left the lobby they can't find the same lobby again. (No available lobbies even if lobby is still there)
But i wan't people to be able to find the same lobby again.
Details:
*There is no problem about lobby heartbeats etc. New players can still find that specific lobby with QuickJoinLobbyAsync .
*The player who leaves the lobby is still able to join another/a different lobby if there is any (room available)
*The player is able to join the same lobby using the lobby code
Hi
I am working on a multiplayer game.
I want if the player 1 and player 2 is in the circle and player 3 is not in circle
The destroy player 3
Those player whos not in the circle destroy
hello i have another problem.. so basically i was trying to get netcode to work with a server but a server and client dont work.. why? it gives a error that only server can spawn players tho i made a server
also i have not assigned the player prefab as i do it in my script automatically
Well the error doesn't say "You haven't got a server" it says "Only the server can spawn objects" or something
That means the client tries to spawn objects, which isn't allowed
Ok
Hey i am trying to combine MLAPI with Steam to use the steam functionality to combine player. Can somebody help how to do that?
Netcode for GameObjects has a community transport for Steam I believe
do you know where
can you send it to me?
There is a repo for them online if you search for it, ensure you are using Netcode for GameObjects and not it's predecessor MLAPI
anyone here done networking? I need help thinking on how to sync objects
the problem is that I have A LOT of objects in the game
and sending them over will be slow
does unity have like "hashes" for objects or smth like that?
mainly, I need to give each object a unique "id" which is gonna be accessed with a dict
public Dictionary<int, Object> Objects { get; private set; }
just increment an int every a time a new object is created and assign that id to that new object.. but what does a dictionary of objects have to do with the fact that sending them all over will be slow?
if you are sending a ton of data when a client connects or something, just send it over time and make the client wait for a message letting it know that it been sent all the data and can now join
Thank you so much! This seems good
Alright!
sorry for the very green question - What is the current state of networking / official networking solutions in unity? I'd like to make a mobile racing game as a solo developer.
hello, uhm in my networking with netcode when i dont assign the player prefab in the player prefab spot and i try to spawn it myself it doesnt work. I did it as a network object but somehow it doesnt work.. please help. below is code
NetworkManager.Singleton.StartClient();
Vector3 playerPosition = new Vector3(0f, 1f, 0f);
Quaternion playerRotation = new Quaternion(0f, 0f, 0f, 0f);
Transform spawnedObjectTransform = Instantiate(playerPrefab, playerPosition, playerRotation);
spawnedObjectTransform.GetComponent<NetworkObject>().Spawn(true);```
in my code basically when i try to make a network Object it doesnt create a network object
just locally
idk why
i tried to add things if(!IsServer) return; but no change
And is this being done on the server?
My guess is no given the StartClient call there
Pretty sure that Quaternion isn't valid either, you don't want to be messing around making Quaternions, use Quaternion.identity
anyone can help me with photon?
i have 2 players one of them cant see through the other character
for example player A and player B
I join in with player A
Friend joins in with player B
I am able to move player A and not B
Friend can move player B but cant see out of him
instead is looking through the view of player A and roates both when looking around but doesnt move A only moves B
I saw the post in the other channel. Are you actually starting host mode somewhere?
yeah
Well that error would suggest otherwise
Well you've got a button for it there
im only using a button to start the host
ive also tried manually starting in networkmanager
I assume you're trying to spawn networked objects before it's ready
Well then you need to think about what changes you made
i tried to comment out everything here and it was still not working
i think i might have broke it
Well the error is regarding the spawning of objects
this is how im spawning it
am i doing something wrong
i have the gameobject correctly linked with both the script and networkprefabs
but its just not working

Do you have any other object spawning code?
Any code that spawns objects before the NetworkManager is ready is an issue yes
im only doing it in the updates
That tells me nothing
How about you just show the code?
ok
this part has been working
this is from another script that im testing with
but it doesnt call rpc
In the error is it more specific, click it and show the whole Console
What is PlayerObjectSpawner line 19?
Well that's the line that is called before the NetworkManager is listening

Not quite sure how, thought that class was a NetworkBehaviour
Ah ha
You're calling Spawn in a ClientRpc, it must be called on the server
So do it in the ServerRpc instead
ive tried that before i think
lemme try again
for some reason its just not recognizing my host as the host i think
I'm out of ideas then, the Netcode Discord is linked in pins if you want to give them a go ยฏ_(ใ)_/ยฏ
thanks
I have given that..
I'm not sure about it, Please ping me when ur online and can help me
Okay so I found the error in my code I believe..
So basically don't have a RPC to send the message to server to create the object
But I have no idea how to do it
Can someone tell how to use RPC to spawn objects?
Create a ServerRpc and create objects in there
Hey Guys question ! im looking to start my first multiplayer project "super small" to learn basically like let 1 friend join me and play any advice on where to go or what to use to get that ?
Any solution like Mirror, Netcode for GameObjects or Photon PUN would work for it
Well that's not exactly an easy question, most people just say "Photon PUN" to that but I always found Mirror easier
With Photon PUN you run on their servers, up to 20CCU free
So you wouldn't have to mess around with port forwarding or using a relay
At the end of the day it comes down to features and preference
20 concurrent users
I have no idea what a pop situation is
You can do P2P or dedicated servers with most solutions
Hm ok.. so photon pun I guess will be the solution then messing with ports is a hassle
You got any good tutorials for that ?
Nope, didn't like PUN really so never bothered going too far with it
Ok with mirror then ?
You're on Discord which suggests to me you have internet
Networking is hard, so you should expect to do a shit tonne of learning yourself
Ok gotcha
the new unity MLAPI looks promising, it also integrates easily with unities matchmaking and servers. Plus its basically free and allows your to build your own dedicated servers if needed without having to pay a bunch to licensing to photon. https://docs-multiplayer.unity3d.com/netcode/0.1.0/tutorials/goldenpath_series/goldenpath_foundation_module
Alternatively you could look into steam or epic's networking sdk which contain match making etc..
Note: MLAPI is now called Netcode for GameObjects
Tried that but in server rpc a error comes saying "sending data while connecting on connection 4294967296 is not allowed." I have no idea what it means. Also connection approval is disabled in network manager
Well when is the RPC sent
After client is connected
After NetworkManager.Singleton.StartClient()
What does that mean?
Ok let me tell what I'm doing
Well no, it's up to you to provide the code
I asked you when the RPC is sent, so show the code relevant to calling that method
public void ButtonClicked() {
NetworkManager.Singleton.StartClient();
PlayerServerRpc();
}```
This is the code
Right, so chances are you ain't connected
Jesus...
Sorry
Chances are that when you call the RPC you are not actually connected
I'm new to it
Hmm
So how do I fix it?
Wait until a callback that guarantees you're in, like OnNetworkSpawn in NetworkBehaviour
I think so
Onnetworkspawn
Ok
Properly PascalCased
And in that I use rpc?
Call the RPC there
Ok lemme try
What's that?
Method names should be PascalCased, where the first letter of every word is capitalised
This is not PascalCase
Yeah ik
I'm using phone
That's why
I'll do it tomorrow morning that's why
Thanks for the help
navMesh = GetComponent<NavMeshAgent>();
alienObject.SetActive(false); // Hides the alien.
NavMeshHit r;
if(NavMesh.SamplePosition(RandomPointInBounds(gameController.mainRoom.GetComponent<BoxCollider>().bounds), out r, 5, NavMesh.AllAreas))
{
print("Warping NavMeshAgent to " + r.position.ToString());
navMesh.Warp(r.position);
}
navMesh.SetDestination(RandomPointInBounds(gameController.mainRoom.GetComponent<BoxCollider>().bounds));
This code is causing .SetDestination to say itโs not on a NavMesh after itโs been instantiated by Photon. Iโd appreciate any help.
I have an issue Iโm facing (theory)
Ok so Client B can move object A
And then it sends the fact it moved to the server
The server sends that info to all clients except B
But the problem is that if the object is in motion, all of the clients will be sending information to be relayed off the server
so then that means all clients are constantly spamming the server with that info
What should I do instead?
should send it to Client B as well. What if in a Pokemon-type world two people try to go to the same tile at the same time? You'd want to send the result back to everyone so everyone knows where they actually are and if their move has been rejected.
Oh whoops I should have specified
This is a sandbox game
A mod for a sandbox game to specific
Makes sense, thanks!
The problem you're describing is quite common. Ever hear about Tarkov's auctions?
Yes, that game. The flea market
When you search, you see a list of items. They're not constantly updated, so you might get 20 "This item is no longer available" before you actually get to buy it.
That's the opposite of the problem you were discussing, over-communicating
I think it's rather cheap to multi-cast.
It's expensive to debug why a client was on a tile where you thought it should be impossible.
does anyone know why when my client connects it doesnt spawn anything in the clients scene
nvm i didnt figure out why but it stopped doing that
Wouldnโt this be extremely slow and resource intensive
And also wouldnโt it result in objects jittering around?
Jittering is up to you
I mean like, if a client moves an object, then receives that the object should be in the previous position, doesnโt that lock the object?
That's why the Tarkov flea market is frustrating
It's essentially "Yes, I'll buy it" "Oops, it's already been sold!"
Same as the situation you just proposed. What's a better alternative?
One person is sending the position until a significant position change is made on another client that makes the owner change
and for the pokemon world situation, you would have exactly 2 people in the same position
what you are discussing right now is a new situation which I didn't address
You're talking about heuristics
but this is a sandbox game
All I said was: Client A should broadcast to everyone
Yep, I agree, and thatโs implemented
Then why are you saying it's not a good idea here?
But the object can be in continuous motion, so do the rest of the clients keep sending the info of the object to everyone? Because to them the object is in motion, and the server must be updated
welcome to extrapolation
This is not the reason why you pinged me to start with
What you really need is a new conversation with someone else.
since the topic of what you want to discuss is different
I'm already in bed and away from my computer.
that was the intention
.
Hi, I'm using Photon PUN, and I saw somewhere that I don't need to pass the owner or the object to the RPC, because the call will only ever go out to instances of the same PhotonView on other clients. However it seems to affect all instances that object (i.e. rpc call goes out to sync one player's action with all clients, should only affect that player across all the clients, however it affects all players across all clients)
This is my code, it should affect just one player's torch across all clients but it's not for some reason:
public void placeHolderMethod()
{
photonView.RPC(nameof(TorchSync), RpcTarget.All, torchIsOn);
}
[PunRPC]
public void TorchSync(bool torchValue)
{
torchLight.SetActive(torchValue);
}```
I hope it makes sense
Use server authority and have clients only send the intent to move the object to the server which then does the arbritration and updates all clients on the result. What youโve been discussing above is an unsolvable problem in P2P networks
What I was planning to do was that the other clients only send inputs to server, then the server reports the results back
So I think thatโs what you are suggesting
yes
Perfect, thanks!
More on why itโs unsolvable with client authority https://en.m.wikipedia.org/wiki/Two_Generals'_Problem
thanks!
well itโs solvable but only if you trust your clients ๐ค
I mean yeah I do
doesnโt take away the n^2 messages though
yeah, thatโs true
Ight im confused. Im using Netcode and I want to shoot projectile from client and then display it on every client, so that everybody sees it. But server RPC is sent from client to server, so clients dont see it, and client rpc is sent from server to client, so I can't call it from client... what do I do?
Please ping me if anybody answers
You can call a ClientRpc from a ServerRpc
You could spawn the object in a ServerRpc and use NetworkObject's SpawnWithOwnership method
So basically just call ServerRpc from client, and in that function call Client RPC that contains the actual code?
It worked, thank you
One more thing. (The right one is focused window)
For some reason the projectiles are going in the wrong direction on other clients.
That's the function that handles it:
private void ShootProjectileClientRpc()
{
GameObject t_projectile = Instantiate(currentWeaponScript.projectilePrefab, currentWeaponScript.firePoint.position, Quaternion.identity, GameManager.currentGameManager.projectileParent);
currentWeaponScript.firePoint.rotation = Quaternion.Euler(0, 0, playerMovement.angle);
t_projectile.transform.rotation = Quaternion.Euler(0, 0, playerMovement.angle);
t_projectile.GetComponent<Rigidbody2D>().velocity = currentWeaponScript.firePoint.right * currentWeaponScript.projectileVelocity;
t_projectile.GetComponent<ProjectileBehaviour>().weapon = currentWeaponScript;
}
looks like it reads transform.right globally
it always shoots to the right side on other clients.
Figured it out. I had to synchronise the angle as a network variable
Does anyone know if there is a networking asset that's available on the unity store to support multiplayer functionality for an RPG game?
How can I get collisions with Netcode (2D)? I've added rigidbody 2d, network rigidbody 2d, network object and network transform to both objects, and they are not colliding.
The only thing you didn't mention there was a 2D collider
That's there aswell. I had the rigidbody set to kinematic.
Ah
Is there any way to see, how many concurrent users are there currently, when using Relay.
do you even know if that code is causing the issue? doesn't look like it to me
it's saying that somehow a server to client rpc is being called from a client, which is bad for obvious reasons
seems like the rpc that's being called is inside of mirror's NetworkTransform
so maybe you have incorrect settings on a NetworkTransform
ya i already found out why
!Application. isBatchMode doing weird stuff keep by pass
Does anybody know the difference between NetworkManager and NetworkManager.Singleton, if there is any? (netcode)
NetworkManager is a class, NetworkManager.Singleton is a static variable of type NetworkManager that holds a reference to the NetworkManager in the scene
Yes, but the two also share a lot of members. Are the static versions just references to the instance ones?
They share a lot of members because they are the same type
One is just a class name, the other is an instance of the class
Ye ye, but most of the instance members have static counterparts
I know that's how it normally is, but for example OnClientDisconnectCallback exists on both the class and the instance
But why?
And are the static ones the same as their instance counterpart on Singleton or separate?
There literally are no static members except Singleton
You cannot do NetworkManager.StartHost(), you have to call it on an instance NetworkManager.Singleton.StartHost()
Oh wait, NetworkBehaviour has a field called NetworkManager that points to the singleton
Yes it does
Is there a way to pass a GameObject to a ServerRpc?
Hey guys, I need help with the following:
My manager and I are creating a football robot with Arduino. The robot will be an UDP Server. I'm creating an app so you can connect to the robot via your phone in the app, and when you're connected, you can control the robot. The robot has its own network.
The phone controller will be UDP Client
However, I've no idea on how to properly do this.
I want to get access to the robot's Access Point
I should note that I'm an intern and am still studying Game Development, and I've not worked with Networking yet
Can anyone help me?
you would need to pass a reference to a network identifiable object of some kind (custom or built-in), if you have a network id component on the game object in question, you can pass a reference to that as argument in your RPC
How can make no collision system in multiplayer?
Remove the objects colliders
so recently i m using photon to make a game multiplayer
it does this wierd thing
whenever i start the game with 1 player , it works fine
but when i open another , the prefabs swap with each other , i m controlling 2nd person with camera of first and vice versa
and when i include one more player just to test
1 -> 2
2 -> 3
3 -> 1 st player
i tried most solutions on internet , but none of them seem to work
please ping me if anyone has an idea how to solve it ๐
Hello
Currently i am working on car racing game. Everything is working perfectly in my system like 1st, 2nd and 3rd player is getting their points correctly but when i am sending build to client so the 2nd and the 3rd player are getting points of each other
can anyone please help why this issue is coming at the client side
???
I want to create a first person shooter which can be played in multiplayer and singleplayer. What should I do with the multiplayer scripts then?
Hello, I wanted to just ask that sometimes in my netcode I have problems like the player won't move in multiplayer
The player is connected to server
The client transform script is there
The script is correct (I debugged it on a test project)
But still it doesn't work, also no errors on client/server. Please help
someone pls help
Does the player move in single player?
I don't understand your problem. Are you using NetworkVariables?
yes
please help, I am trying to install the client network transform (netcode) via git url, but it doesn't work. It just gives me an error (I copied the url correctly!!)
I also tried to install it directly via the manifest.json file, but It gives me also an error.
https://docs-multiplayer.unity3d.com/netcode/current/components/networktransform/index.html
The position, rotation, and scale of a NetworkObject is normally only synchronized once when that object is spawned. To synchronize position, rotation, and scale at realtime during the game, a NetworkTransform component is needed. NetworkTransform synchronizes the transform from server object to the clients.
https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/ClientAuthority/ClientNetworkTransform.cs Looking at the component in question, you could just write it out yourself
Or copy it from there
thanks



