Host's camera on network game isn't working correctly - c#

So, I'm doing an FPS game in Unity5, and some days ago I started looking at multiplayer tutorials at the official site of Unity.
However, I changed some bit of the code to fit in an FPS, but I had a problem when started doing this. The client's camera moved fine, but the host's one did not: It used the client's camera to see, but his player to move, sort of a third-person view.
All players have the same code, and the camera has a Network Identity with Local Player Authority turned on. Also, it has this C# script:
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class VisionControl : NetworkBehaviour {
void Start () {
Cursor.lockState = CursorLockMode.Locked;
}
void Update () {
if(!isLocalPlayer){
return;
}
transform.Rotate (new Vector3 (-Input.GetAxis ("Mouse Y")*5.0f,0.0f,0.0f));
}
}

Your camera should not have a network identiy.
It is used only by the local clients to get a perspective of the game world, so they do not need to be networked.
Each camera exists on the current client.for the current client only.
Each game instance should have 1 camera running, that of the Local Player.
Attach a simple non-networked camera component to your player prefab and test again.

Fixed! I removed the VisionControl script and putted this one on the player's movement script:
public override void OnStartLocalPlayer ()
{
if (isLocalPlayer) {
FindObjectOfType<Camera> ().gameObject.transform.position = this.transform.position+new Vector3(0f,0.5f,0f);
FindObjectOfType<Camera>().gameObject.transform.SetParent (this.transform);
}
}

Related

Unity3d crashes every time I run my game because of the spawner Game object spawning Enemy prefabs

I am about half way done with the firs prototype of my new game-idea, and I am tring to implement a spawner that randomly spawns one of 3 enemy prefabs. This enemy spawning hasn't been working very well for me, as I have always found little problems here and there. One of these problems was major and caused Unity to crash every time I pressed Play ind the editor. I wasn't sure what the problem was, and so I Build the game I tried running the build, and it crashed as well. Then eventually I scraped my spawner and tried a new one. This one also crashed Unity every time, so I tried to spawn a random sphere with no components to it, and this seems to be working perfectly fine.
While running the game In the Unity Editor, I simultaneously open the task manager to see what was going on. It told me Unity was running like a charm, although it used about 1.5 gigs of Ram. Is it a lot? TBH, I don't know if that's the reason it keeps crashing, but I wouldn't know why it takes these amounts of ram. As soon as I deactivated the spawner it stopped crashing, so is it the spawner? I personally don't think so because I was able to spawn the sphere without the game crashing, but as soon as I try to spawn the enemies breaks down.
-> edit: The game doesn't really crash, it just starts loading into infinity, forcing me to end the application and reopen it hands why I am not able to provide any error codes.
Here is the spawner script I used:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public GameObject[] enemyPrefabs;
public float spawnRate = 1.0f; //The frequency at which enemies spawn.
private float nextSpawn = 0.0f; //used to trigger the next spawn
void Update()
{
//Make enemy spawn on a countdown timer
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate; // Trigger next spawn
Debug.Log("Spawn");
//Spawn the enemy in the same place as the spawner
GameObject piClone = Instantiate(enemyPrefabs[Random.Range(0, enemyPrefabs.Length)], transform.position, transform.rotation) as GameObject;
}
}
}

UnityEngine Video3DLayout.SideBySide3D code not working

I'm new to C# and Unity, but I'm trying to code an app with Unity which would play my customer's 3D Side by Side VR video. I'm using script from here https://docs.unity3d.com/ScriptReference/Video.VideoPlayer.html to get the video running and it works great, BUT it doesn't play as Side By Side VR video, but just a flat video with two screens for both eyes.
UnityEngine.Video has Video3DLayout.SideBySide3d enumeration (https://docs.unity3d.com/ScriptReference/Video.Video3DLayout.html) that could solve the problem, but I don't know what is the right syntax for that. Here is the code I have tried:
using UnityEngine;
using System.Collections;
public class Movie : MonoBehaviour{
enum Video3DLayout {No3D, SideBySide3D, OverUnder3D};
void Start(){
Video3DLayout myLayout;
myLayout = Video3DLayout.SideBySide3D;
// Will attach a VideoPlayer to the main camera.
GameObject camera = GameObject.Find("Main Camera");
// VideoPlayer automatically targets the camera backplane when it is added
// to a camera object, no need to change videoPlayer.targetCamera.
var videoPlayer = camera.AddComponent<UnityEngine.Video.VideoPlayer>();
// Play on awake defaults to true. Set it to false to avoid the url set
// below to auto-start playback since we're in Start().
videoPlayer.playOnAwake = false;
// By default, VideoPlayers added to a camera will use the far plane.
// Let's target the near plane instead.
videoPlayer.renderMode = UnityEngine.Video.VideoRenderMode.CameraNearPlane;
// Set the video to play.
videoPlayer.url = "movie.mp4";
// Start playback. This means the VideoPlayer may have to prepare (reserve
// resources, pre-load a few frames, etc.). To better control the delays
// associated with this preparation one can use videoPlayer.Prepare() along with
// its prepareCompleted event.
videoPlayer.Play();
}
}
I have feeling that I'm introducing the enumerations wrong way and I hope that someone could guide me to right direction. I have tried to use this tutorial https://unity3d.com/learn/tutorials/topics/scripting/enumerations to understand more about enumerations, but this way my code is not working.
There's 2 reasons why it isn't working. You're creating a new enum, instead of using the UnityEngine.Video.Video3DLayout enum. Also you're not assigning myLayout to the videoPlayer.
using UnityEngine;
using System.Collections;
using UnityEngine.Video;
public class Movie : MonoBehaviour
{
public Video3DLayout myLayout;
void Start()
{
// Will attach a VideoPlayer to the main camera.
GameObject camera = GameObject.Find("Main Camera");
// VideoPlayer automatically targets the camera backplane when it is added
// to a camera object, no need to change videoPlayer.targetCamera.
var videoPlayer = camera.AddComponent<UnityEngine.Video.VideoPlayer>();
videoPlayer.targetCamera3DLayout = myLayout;
// Play on awake defaults to true. Set it to false to avoid the url set
// below to auto-start playback since we're in Start().
videoPlayer.playOnAwake = false;
// By default, VideoPlayers added to a camera will use the far plane.
// Let's target the near plane instead.
videoPlayer.renderMode = UnityEngine.Video.VideoRenderMode.CameraNearPlane;
// Set the video to play.
videoPlayer.url = "movie.mp4";
// Start playback. This means the VideoPlayer may have to prepare (reserve
// resources, pre-load a few frames, etc.). To better control the delays
// associated with this preparation one can use videoPlayer.Prepare() along with
// its prepareCompleted event.
videoPlayer.Play();
}
}

Unity 5: Raycast not finding blocks

Hey guys I've been working on a 2D terraria-like game, from a tutorial I found on Youtube. I've been using Quads as blocks. The link to the series is:
https://www.youtube.com/watch?v=KONw5GX0Ixs
The only difference is I've been in a 2D project rather than a 3D. I'm trying to implement a mining system, but the clicks aren't detected much less the blocks that I'm clicking on. The system doesn't even detect the clicking, much less the blocks I'm clicking on. I'm new to coding so I'm not sure how to fix this, anything helps, thanks.
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mining : MonoBehaviour {
public Vector2 direction;
void Update() {
if (Input.GetMouseButtonDown (0)) {
Vector3 c = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit2D = Physics2D.Raycast(this.gameObject.transform.position, direction);
Debug.Log ("hello");
if (hit2D.collider.gameObject != null) {
Debug.Log (hit2D.collider.gameObject);
Destroy (hit2D.collider.gameObject);
}
}
}
}
First of all, change
Input.GetMouseButtonDown(0)
to
Input.GetMouseButton(0)
as its
Returns whether the given mouse button is held down.
tell me if that fix your problem. If not, I will try to figure sth out:)

Client not executing Commands in Unet

Edit
Okay, so I partially solved the problem by adding a rigid body component to the capsule. I read somewhere that apparently you have to have one in order to move on the server.
Problem 2
The next problem I have is that I can now move a capsule that is spawned by the client fine and the host can move it as well as many times as they like. The problem I am getting now is that when the host spawns a capsule the client cannot move it at all and I get a sort of glitch effect on the client side and the capsule still doesn't move on the host side. Is there a reason why it would only work one way and not the other way around? I thought at first it might have to do with Spawn vs SpawnWithClientAuthority but that doesn't seem to make a difference.
Project Summary
I have a pretty simple multiplayer project, all I want to do is have one player host and the other join as a client. Once they are joined together the two players can spawn a capsule and then when the user clicks on a capsule. They should be able to pick it up and move it around the scene and the other player should be able to see this action. I can get both players to connect to the server and spawn their own capsule and both players can see this. The movement script is done as well. However, it is only transmitted on the host side. When the client picks up the object it does not update on the server.
Problem
I have done a bit of debugging and have found that when I call the command on the client it is not being executed at all through line breaks and simple debug statements.
Code
public void OnInputClicked(InputClickedEventData eventData)
{
Debug.Log("clicked");
if (isLocalPlayer)
{
if (Physics.Raycast(transform.position, direction: transform.forward, hitInfo: out hit, maxDistance: range))
{
Debug.Log("Hit capsule");
objectID = GameObject.Find(hit.transform.name);
objNetId = objectID.GetComponent<NetworkIdentity>();
CmdAssignAuthority(objNetId);
Debug.Log("Cmd done");
}
else
{
//else if the player is releasing the object we want to release authority
if (objNetId != null)
{
CmdAssignAuthority(objNetId);
}
}
}
[Command]
void CmdAssignAuthority(NetworkIdentity target)
{
Debug.Log("inside cmd");
NetworkConnection current = target.clientAuthorityOwner;
if (current != null && current != connectionToClient)
{
target.RemoveClientAuthority(current);
target.AssignClientAuthority(connectionToClient);
}
else
{
if (current != null)
{
target.RemoveClientAuthority(current);
}
if (current == null)
{
target.AssignClientAuthority(connectionToClient);
}
}
}
Question
Am I calling this command correctly? The script is attached to a player prefab and the capsule prefab contains a network id and a network transform. I am pretty new to Unet and this feels like a noob mistake.

Unity Multiplayer FPS Client/Server Interaction Problems

I have a simple FPS where a player can fire a gun. I want the clients to see the bullet holes. I am trying to accomplish this by invoking a server side method when the client tries to fire the gun. The server side method should then raycast from the players camera and spawn a bullet hole for everyone to see..
I can get this to work partially by passing the player as a parameter to the server method. However, since my raycasting needs to be done based off the player camera, the bullet holes end up appearing at character height, since it's using the player and not the camera.
It won't allow me to pass a camera through. I have also tried creating an empty game object called bullet spawn and passing that through but I was getting a "object reference not set to instance of an object." This same error seems to surface for any Child element of the player I attempt to pass to the server side method.
I am unsure of the right way to accomplish this.
void Update()
{
if (isLocalPlayer)
{
if (Input.GetButton("Fire1"))
{
CmdFire(BulletSpawn);
}
}
}
[Command]
void CmdFire(GameObject Player)
{
Ray shooterRay = new Ray(Player.transform.position, Player.transform.forward);
if (Physics.Raycast(shooterRay, out Hit, 10000))
{
Debug.Log("player hit");
GameObject Bullet_Hole = (GameObject)Instantiate(BulletHole_Prefab, Hit.point, Quaternion.FromToRotation(Vector3.up, Hit.point));
NetworkServer.Spawn(Bullet_Hole);
}
}
Think about it this way. What is it that you need to fire your weapon? You need the firing point and the firing direction (in your simple case). So try to pass just that information. Your CmdFire should look like void CmdFire(Vector3 firingPoint, Vector3 firingDirection). Remember that when you pass the player gameobject, it gets serialized and sent to the server which causes a lot of unneeded network traffic. Stick to value types and simple objects for commands.
This is what ultimately led me to the solution. Thank you for the advice. I simply passed two Vector3 parameters as you suggested which represent the raycast position and direction. I can now shoot from both client and server and see the bullet holes on both as well. Here is the code that fixed it in case anyone runs into this later on:
void Update() {
if (isLocalPlayer) {
if (Input.GetButton("Fire1")) {
Vector3 FiringSpot = PlayerCam.transform.position;
Vector3 FireDirection = PlayerCam.transform.forward;
CmdFire(FiringSpot, FireDirection);
}
}
}
[Command]
void CmdFire(Vector3 firingPoint, Vector3 firingDirection) {
Ray shooterRay = new Ray(firingPoint, firingDirection);
if (Physics.Raycast(shooterRay, out Hit, 10000)) {
GameObject Bullet_Hole = (GameObject)Instantiate(bullet_Hole_Prefab, Hit.point, Quaternion.FromToRotation(Vector3.up, Hit.point));
NetworkServer.Spawn(Bullet_Hole);
Destroy(Bullet_Hole, 10);
}
}

Categories

Resources