**EDIT:** Code below ended up working fine. Still, *any critique of my code is very much appreciated* because I am still a bit confused about my code.
I'm not new to Unity anymore, but new to networking. Trying to make a multiplayer fps prototype.
I definitely do not understand something, watching tutorials doesn't really help.
**PROBLEM**: On host (server + client) side raycast shooting works perfect but client is unable to register a hit. Please help!!
void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse0) && isLocalPlayer)
{
if(isServer)
Shoot(netId);
else
CmdShoot(netId);
}
}
[Server]
public void Shoot(uint owner)
{
RaycastHit hit;
// My guess is it doesn't work because playerCamera is different on different players (?)
if(Physics.Raycast(playerCamera.position, playerCamera.forward, out hit, weaponRange))
{
if(hit.collider.CompareTag("Player"))
{
PlayerMovement hitPlayer = hit.collider.GetComponent();
if(hitPlayer.netId == owner)
return;
if(hitPlayer.isServer)
hitPlayer.ChangeHealthValue(-1);
else
hitPlayer.CmdChangeHealthValue(-1);
}
else
{
Debug.Log("No player was hurt");
}
}
}
[Command]
public void CmdShoot(uint owner)
{
Shoot(owner);
}
↧
How to handle raycast shooting in multiplayer (Mirror)?
↧
(UNITY MIRROR) Server/Client functions not being called from instantiated objects
So I'm new to Mirror so bare with me.
I'm currently working on a multiplayer project where players control wizards, casting spells at each other. However, I seem to have a problem with objects "spells" the wizard player character instantiates, with them not being able to call any Command or Rpc functions. Maybe my understanding is a little off but here's the main rundown.
The wizard_player script calls this command function to spawn the currently selected spell.
CmdSpawnSpell(selectedElements[spellToCast].castType, index); ////THIS WORKS FINE
}
[Command]
private void CmdSpawnSpell(SpellIndex.CastType t, int index)
{
RpcSpawnSpell(t, index);
}
[ClientRpc]
private void RpcSpawnSpell(SpellIndex.CastType t, int index)
{
SpawnSpell(t, index, true);
}
private void SpawnSpell(SpellIndex.CastType t, int index, bool isParented)
{
GameObject newSpell;
switch (t)
{
case SpellIndex.CastType.Spray:
newSpell = Instantiate(SpellIndex.SI.spray[index], castPoint.position, castPoint.rotation);
break;
case SpellIndex.CastType.Beam:
newSpell = Instantiate(SpellIndex.SI.beam[index], castPoint.position, castPoint.rotation);
break;
case SpellIndex.CastType.Projectile:
newSpell = Instantiate(SpellIndex.SI.projectile[index], castPoint.position, castPoint.rotation);
break;
case SpellIndex.CastType.Shield:
newSpell = Instantiate(SpellIndex.SI.shield[index], castPoint.position, castPoint.rotation);
break;
default:
return;
}
if (isParented)
{
newSpell.transform.SetParent(castPoint);
currentSpell = newSpell.GetComponent();
currentSpell.NormalCast();
}
}
So far all is well, this successfully spawns the spell on the server and all clients.
But then for some reason the Command/Rpc functions on the newly instantiated object never get called/listened too.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Spell : NetworkBehaviour
{
public Wizard_SpellManager.Element.Type elementType;
public float castTime = 3f;
public float castingMovePenaltyPercentage = 0f;
protected bool casting = false;
public float damage = 10f;
public virtual void NormalCast()
{
casting = true;
RpcCast(); //////////DON'T WORK????
CmdCast(); //////////DON'T WORK????
}
[ClientRpc]
private void RpcCast()
{
Debug.Log("HI CLIENT");
}
[Command]
private void CmdCast()
{
Debug.Log("HI SERVER");
}
They all have networkidentity and networktransform. Not only that, but if I replace the playerprefab in the network manager with the spell object, the above code starts working.
Is there a step that I've missed? Do I need to somehow register the newly created object to the network manager so that it can call the server and client commands?
↧
↧
Mesh mirror with bisect-trimming in realtime?
Any way to mirror a mesh over a given axis with a script at runtime and trim anything that runs over the axis? Similarly to how Blender's mirror modifier works with bisect:
![alt text][1]
I'm just trying to make procedural baseboard pieces for whatever angle the wall corner turns out as so if there's an easier way to do that lmk.
To be clear this is the end result I'm looking for:
![alt text][2]
[1]: /storage/temp/181532-capture.jpg
[2]: /storage/temp/181533-capture.jpg
↧
Mirror multiplayer player color update not showing on other clients
The code below is on the player and successfully updates the color of the several materials used for this player. This is called during the game to change the color after spawn and called again to change the player back to the original color.
[Command]
public void CmdHandlePlayerColorChange(Color newColor)
{
foreach (MeshRenderer mr in meshes)
{
currColor = newColor;
mr.material.color = currColor;
}
}
However, the other clients do not pickup the color change (the color stays the same as set at spawntime). I tried Command/ClientRpc (below), but this crashed the other client.
[ClientRpc]
void RpcPlayerColorChange(Color newColor)
{
foreach (MeshRenderer mr in meshes)
{
currColor = newColor;
mr.material.color = currColor;
}
}
[Command]
public void CmdHandlePlayerColorChange(Color newColor)
{
RpcPlayerColorChange(newColor);
}
I appreciate any suggestions to get the other clients to pick up the color change.
↧
Mirror Networking - can't connect to hosted server from phone client
Right, so I'm going to post as much information as I can with the hopes someone out there can help me because I'm losing my mind here.
My game concept is as follows: I am hosting a server at home. I connect my phone as a client, which controls a cross-hair in-game using the accelerometer data. This only needs to be accessible to me as it's a performance drawing device, so I don't care about security. I will be projecting the game using a third device, a computer as a client off-site. I am able to establish a server - client relationship when my phone is connected to my home's wifi. But I am unable to establish a connection when I use my phone data. As I will be off-site, I need this connection to pass.
I establish my server using NetworkManager.singleton.StartServer();
I connect a client to the server using (hiding IP with xxx just for this post) NetworkManager.singleton.networkAddress = "141.168.xxx.xxx"; NetworkManager.singleton.StartClient(); NetworkServer.Listen(7777);
Because I can connect locally I know this connection is viable. I've created a port-forwarding rule in my gateway (I use Belong) ![alt text][1] [1]: /storage/temp/182023-capture.png
I've made sure my internet is using a static IP
I've made rules in my firewall to allow my program to pass UDP traffic on 7777
I've uninstalled my anti-virus, and tried turning my firewall off entirely
I CANNOT for the life of me get this to work. Please God, or anyone. Help me.
My game concept is as follows: I am hosting a server at home. I connect my phone as a client, which controls a cross-hair in-game using the accelerometer data. This only needs to be accessible to me as it's a performance drawing device, so I don't care about security. I will be projecting the game using a third device, a computer as a client off-site. I am able to establish a server - client relationship when my phone is connected to my home's wifi. But I am unable to establish a connection when I use my phone data. As I will be off-site, I need this connection to pass.
I establish my server using NetworkManager.singleton.StartServer();
I connect a client to the server using (hiding IP with xxx just for this post) NetworkManager.singleton.networkAddress = "141.168.xxx.xxx"; NetworkManager.singleton.StartClient(); NetworkServer.Listen(7777);
Because I can connect locally I know this connection is viable. I've created a port-forwarding rule in my gateway (I use Belong) ![alt text][1] [1]: /storage/temp/182023-capture.png
I've made sure my internet is using a static IP
I've made rules in my firewall to allow my program to pass UDP traffic on 7777
I've uninstalled my anti-virus, and tried turning my firewall off entirely
I CANNOT for the life of me get this to work. Please God, or anyone. Help me.
↧
↧
inspector not show details and use mirror to change Scene
Hello i want to ask some question
1.why my inspector now show any details of png image and can't use them how i can fix it
![alt text][1]
2.i use mirror to create multiplayer game i create lobby and use code to change lobby to game scene but when i press start game it show ui from lobby scene and not disappear how can i use other code to change scene?
![alt text][2]
this is code that i use
public void BeginGame()
{
CmdBeginGame();
}
[Command]
void CmdBeginGame()
{
MatchMaker.instance.BeginGame(matchID);
Debug.Log("Game Beginning");
}
public void StartGame()
{
TargetBeginGame();
}
[TargetRpc]
void TargetBeginGame()
{
Debug.Log($"MatchID: {matchID} | Beginning ");
//Additively load game scene
SceneManager.LoadSceneAsync(2, LoadSceneMode.Additive);
}
[1]: /storage/temp/182667-99.jpg
[2]: /storage/temp/182668-98.jpg
↧
Mirror NetworkTransformChild not working?
I'm trying to create a third person multiplayer game in Unity 2019 using Mirror. Using built-in NetworkTransform is OK, but I need to sync player spine rotation, which is obviously a child game object of player. I've tried to use NetworkTransformChild and select spine as target, but nothing happens. When testing, player spine not synced, but in editor (Host player) a remote client creates a grey sphere in zero coords, which axis is rotating like player spine must. Read a few topcis and official Mirror docs, but don't understand what I'm doing wrong. Please help! Addit. info: Spine is a child of 'Hips' gameobject, which is a child of player. Player model downloaded from Mixamo.com!
↧
Unity2D: Mirror Multiplying - How to view an opponent's screen in a match 3 game.
Hi, I'm making my own match 3 multiplayer game, the concept is to have two people face off against each other person can face off another person by swapping tiles to make a line of the same form. I want to introduce multiplayer by connecting two players together and allowing each person to see their opponent's screen, as well as syncing their moves. So far, I have a simple match 3 game (I created one using different tutorials, mainly this playlist) and followed a simple multiplayer tutorial (Mirror) for a player to host or be a client. My problem is that I have no idea how to show both players their opponent's screen to each other. I even found an example of what I want the multiplayer mode in my game to be like. Can anyone point me in the right direction, please and thank you. Additional information: I'm using mirror for multiplayer I created a network manager gameobject and added the necessary components to it. I also added the game pieces into the 'registered spawnable prefabs' and created an empty gameobject, called player for the player prefab. Each game piece has a network transform and network identity component attached. The player prefab object has a camera child under it to. This is what I want my game to look like:
https://imgur.com/ZqNGmKt
Overall, I want to have player's view each other's screen:
https://imgur.com/2QO3eD7
As you can see, both player's are connected, what I want to do it to allow each player see their opponent's screen. Does anyone have an idea on how I can do it?
Thank you! :)
↧
Problem with calling a function from client to NetworkPlayer(Mirror)
Hey would anyone be able to help me with a mirror/unity issue?
I am trying to implement a feature that whenever a player vehicle dies, it calls a function on the networkplayer script that reduces the lives. The vehicle with the script that calls the function is not a child of the networkplayer, but has the same identity and such. The problem however, is that it only works on the host, and it doesnt work on the client. I think it has to do with server callbacks and stuff, but I wasnt the one who set those up initially on these functions so idk which one is for what reason. Any help would be awesome!
Heres the code on the vehicle, and a projectile code that calls the initial function on the vehicle
Projectile:
[ServerCallback]
private void OnTriggerEnter(Collider co)
{
if (!co.TryGetComponent(out var health))return;
health.DealDamage(damageAmount);
NetworkServer.Destroy(gameObject);
/* if (co.TryGetComponent(out var networkIdentity))
{
if (networkIdentity.connectionToClient == connectionToClient) { return; }
}*/
}
Health.cs on vehicle:
[ServerCallback]
public void DealDamage(int damageAmount)
{
currentHealth = Mathf.Max(currentHealth - damageAmount, 0);
if (currentHealth == 0 && gameObject.tag == "Building")
{
StartCoroutine(Respawn());
}
else if (currentHealth == 0)
{
StartCoroutine(Respawn());
NetworkIdentity thisObject = GetComponent();
MyPlayer player = connectionToClient.identity.GetComponent();
player.ReduceLives();
if (player.GetLives() == 0) { return; }
FindObjectOfType().TargetEnableVehicleViewer(thisObject.connectionToClient, true);
}
}
↧
↧
How to setup a instantiated gameobject with mirror networking correctly?
In my procedural game worlds, I have a habitus of instantiating new objects like this:
GameObject character = (GameObject.Instantiate(characterPfb, location.position,
location.rotation, transform));
NetworkServer.Spawn(character);
DragAndDrop dnd = character.GetComponent();
dnd.startPos = location;
dnd.mainCam = Camera.main;
dnd.gameState = gameState;
So I create the gameobject, get its script and fill it with all variables it needs to function.
Now, this doesn't seem to work with mirror since the fields stay empty in the new object.
I have tried to pass all the variables to the Player script and let it set the variables via command.
Still, the fields remain empty.
I hate networking for how everything that would otherwise just work perfectly has simply no effect at all. As if I'd write all the code for nothing.
I would be very happy if someone could redeem me, and show me how to set up an instantiated gameobject correctly with mirror, so it has all its variables set.
Thank you!
↧
Unity Mirror networking take damage
Can someone help me, I need to deal damage from my weapon script(gun shot) to the player script
↧
Unity Mirror: SocketException: could not resolve host ' ',Unity Mirror: How to Fix "SocketException: could not resolve host ' ' "
Hello! Please Help Me Fix this Issue I was having this Issue since Yesterday. I Created a Multiplayer Game using Mirror Asset. But When I Click the Join Button, it shows me the Error says "SocketException: could not resolve host ' ' " I was Searching Whole the Time to Find a Solution but cannot Find One. I check my JoinLobbyScript but there's nothing Wrong with it. I Check my Network Manager and UIMenu but Everything is Fine, but when I test, The Host is Working but cannot Join. Please Help me. Thank you!,Hello so I was having this Problem with the Unity Mirror. I Created a Multiplayer Game but the Problem is I cannot Join and the Error says "SocketException: could not resolve host" I Check my JoinLobby Script and there's nothing Wrong with it. I Search for a Solution since Yesterday but I cannot find one.
here is my Join Lobby Script;
↧
Unity Mirror Problem Client Recv: failed to connect to ip=localhost port=7777 reason=System.Net.Sockets.SocketException (0x80004005): Could not resolve host 'localhost'
Hello! So I was having this Problem. I'm using Unity Mirror. When I Test the Host, the Host was Perfectly Working, and When I was testing the Join, I cant join keeps showing me this Error "Client Recv: failed to connect to ip=localhostport=7777 reason=System.Net.Sockets.SocketException (0x80004005): Could not resolve host 'localhost' ". Please Help Me solve this issue. Thank You
↧
↧
Spawning too many Objects when loading the World (k_eresultlimitexceeded)
I am trying to add a Multiplayer to my game, but the way I currently try to load the World on the Client does not work and only loads around half of the world.
Currently when loading the world on the server I use NetworkServer.Spawn() on every important Object (these being Chunks, Items, harvestables and animals), I do this because this is the only way I know how to spawn the Objects on the Client without respawning the world everytime someone joins.
This has the added negative of not being able to control how much information is send at once, thus when a Client joins they get too much information and after a short while of loading the server gets first a warning then an error ("k_EresultLimitExceeded") and the world is only half loaded on the Client, I don't know any way to slow the transfer of data down or to load one chunk at a time without doing so on every client at once.
So my question is, is there any way of either Spawning something on one Client at a time (being able to request a spawn as Client), slow down the transfer when joining or just raise the limit of how much you are able to send.
↧
How to port forward via script in unity
Trying to make a multiplayer game so my friends and I (and other people that wants to download it) can play together, but the problem is that we don't live under the same router, which gave me the problem of port forwarding. A lot of my friends don't understand this stuff (including me) so I want to make it so they don't have to do it. I've seen some forums talking about UPnP, but many of the guides/tutorials are vague or have nothing to do with my problem.
If you know a guide/tutorial bout port forwarding via script in unity please tell me, because that will help a lot!
↧
Different Prefab for each new connected client?
Trying to make it so that the second player joining the server would receive different prefab. This is what I believed would do the job:
public class CustomNetwork : NetworkManager
{
public Transform player1Position;
public Transform player2Position;
public GameObject player1Prefab;
public GameObject player2Prefab;
public override void OnServerAddPlayer(NetworkConnection conn)
{
if (numPlayers == 0)
{
Transform start1 = player1Position;
GameObject player1 = Instantiate(player1Prefab, start1.position, start1.rotation);
NetworkServer.AddPlayerForConnection(conn, player1);
}
else
{
Transform start2 = player2Position;
GameObject player2 = Instantiate(player2Prefab, start2.position, start2.rotation);
NetworkServer.AddPlayerForConnection(conn, player2);
}
}
}
But as result i can see 2 different player in the host client (and can move the player 1), but on the connected client I see 0 players, not mine and not the host.
This is the error I receive:
![alt text][1]
[1]: /storage/temp/185135-fusa0.png
↧
Unity Mirror - cancel command if it got it to late
I got a problem, if I have a high ping and I attack a player, the player take the damage very late, so I want to cancel it if the player have a high ping.
↧
↧
how to create start the game automatically when all the players are joined using mirror networking?
I'm creating a multiplayer game, and I want all the players are joined and then game should be start.
Is there any way to do this.? (Hope you understand my question).
Thanks in advance.
↧
Mirror uses the same input for every client
Hello world! I used Mirror Networking quite a few times, but every time I get stuck at this problem.
To test the game I build and run the game and connect to the editor playmode, everything works until I try to move a player: both players move at the same time with the same movement. I Tried to fix this putting the attribute `[Client] ` from the Mirror namespace at every method but it didn't work. How can I solve this problem? Thanks in advice...
↧
I need to make a mirror object.
I'll try to be as clear as possible. I need a script with the following behaviour. I have a camera, and this camera determines the mirror axis. On one side of the axis there's the original object (a cube, cilinder etc) and on the other side there's a copy of this object moving the same way as the original object. Just like a real life mirror. I need the camera to look only at the copy object, not the original one. Here's a sketch showing the idea. ![alt text][1]
[1]: /storage/temp/186000-mirror.png
Thanks in advance for your help.
↧