Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Multiplayer Player Prefab or Camera Script: NullReferenceException

Discussion in 'Multiplayer' started by strudi1986, Oct 18, 2017.

  1. strudi1986

    strudi1986

    Joined:
    Jun 21, 2015
    Posts:
    10
    Hi!

    I have a problem! I want to test multiplayer a little bit so i set up a scene with network manager and the network identity on the player prefab! i dragged the player prefab in the slot in the network manager! the camera control is seperatly and not connected with the player prefab! offline everything works ok, but when i start the multiplayer test i get the following NullReferenceException:

    NullReferenceException: Object reference not set to an instance of an object CameraOrbit.Start () (at Assets/Scripts/Camera Scripts/CameraOrbit.cs:29)

    NullReferenceException: Object reference not set to an instance of an object CameraOrbit.HandleCamera () (at Assets/Scripts/Camera Scripts/CameraOrbit.cs:64) CameraOrbit.Update () (at Assets/Scripts/Camera Scripts/CameraOrbit.cs:45)

    Player Movement is working correctly but the camera wont. ive tried several things now but i cant find the right solution. the error occurs in the camera script. CameraOrbit.cs und CameraZoom.cs are attached to the MainCamera. MainCamera is NOT attached to the player!

    Code (CSharp):
    1.      using System.Collections;
    2.      using System.Collections.Generic;
    3.      using UnityEngine;
    4.    
    5.      public class CameraOrbit : Orbit {
    6.    
    7.          public Vector3 targetOffset = new Vector3 (0, 2, 0);
    8.          public Vector3 cameraPositionZoom = new Vector3 (-0.5f, 0, 0);
    9.          public float cameraLenght = -10f;
    10.          public float cameraLenghtZoom = -5f;
    11.          public Vector2 orbitSpeed = new Vector2 (0.01f, 0.01f);
    12.          public Vector2 orbitOffset = new Vector2 (0, -0.8f);
    13.          public Vector2 angleOffset = new Vector2 (0, -0.25f);
    14.    
    15.          private float _zoomValue;
    16.          private Vector3 _cameraPositionTemp;
    17.          private Vector3 _cameraPosition;
    18.    
    19.          private Transform _playerTarget;
    20.          private Camera _mainCamera;
    21.    
    22.          void Awake ()
    23.          {
    24.            
    25.          }
    26.    
    27.          // Use this for initialization
    28.          void Start () {
    29.                  _playerTarget = GameObject.FindGameObjectWithTag ("Player").transform;
    30.    
    31.                  sphericalVectorData.Lenght = cameraLenght;
    32.                  sphericalVectorData.Azimuth = angleOffset.x;
    33.                  sphericalVectorData.Zenith = angleOffset.y;
    34.    
    35.                  _mainCamera = Camera.main;
    36.    
    37.                  _cameraPositionTemp = _mainCamera.transform.localPosition;
    38.                  _cameraPosition = _cameraPositionTemp;
    39.    
    40.          }
    41.        
    42.          // Update is called once per frame
    43.          void Update () {
    44.    
    45.              HandleCamera ();
    46.          }
    47.    
    48.          void HandleCamera ()
    49.          {
    50.              if ( Input.GetMouseButton (1) )
    51.              {
    52.                  sphericalVectorData.Azimuth += Input.GetAxis ("Mouse X") * orbitSpeed.x;
    53.                  sphericalVectorData.Zenith += Input.GetAxis ("Mouse Y") * orbitSpeed.y;
    54.    
    55.                  sphericalVectorData.Zenith = Mathf.Clamp (sphericalVectorData.Zenith + orbitOffset.x, orbitOffset.y, 0f);
    56.              }
    57.    
    58.                  float distanceToObject = _zoomValue;
    59.                  float deltaDistance = Mathf.Clamp (_zoomValue, distanceToObject, -distanceToObject);
    60.                  sphericalVectorData.Lenght += (deltaDistance - sphericalVectorData.Lenght);
    61.    
    62.                  Vector3 lookAt = targetOffset;
    63.    
    64.                  lookAt += _playerTarget.position;
    65.    
    66.                  base.Update ();
    67.    
    68.                  transform.position += lookAt;
    69.                  transform.LookAt (lookAt);
    70.    
    71.                  if ( _zoomValue == cameraLenghtZoom )
    72.                  {
    73.                      Quaternion targetRotation = transform.rotation;
    74.                      targetRotation.x = 0f;
    75.                      targetRotation.z = 0f;
    76.                      _playerTarget.rotation = targetRotation;
    77.                  }
    78.    
    79.                  _cameraPosition = _cameraPositionTemp;
    80.                  _zoomValue = cameraLenght;
    81.          }
    82.      }
    83.  
    84.  
    ive tried to set the _playerTarget variable public and i saw that this variable stays empty after start. i think thats the problem. can anyone help? Thank you
     
  2. strudi1986

    strudi1986

    Joined:
    Jun 21, 2015
    Posts:
    10
    if i write in the update function

    if ( _playerTarget == null )
    {
    _playerTarget = GameObject.FindGameObjectWithTag ("Player").transform;
    }

    it will work, but at the start i get still the eorror message until the player spawns. is there any other solution for this? what do i wrong? :)
     
  3. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    Do it in OnStartClient instead of Start, but you'll have to make your orbit script inherit from NetworkBehaviour.
     
  4. strudi1986

    strudi1986

    Joined:
    Jun 21, 2015
    Posts:
    10
    Thank you for that advice :) The error is gone, but the _playerTarget variable is still empty and the camera dont work when the player prefab spawned :(
     
  5. dbarrett

    dbarrett

    Joined:
    Sep 6, 2017
    Posts:
    32
    You can try something like this.

    Code (CSharp):
    1. GameObject player = FindObjectOfType<NetworkManager>().client.connection.playerControllers[0].gameObject;
     
  6. strudi1986

    strudi1986

    Joined:
    Jun 21, 2015
    Posts:
    10
    Thank you! Now the variable will be filled with the correct data! Everything works fine instead the camera :(

    The problem is, the camera is not attached to the playerprefab and if i connect with 2 local players, i can only handle the "host" camera with every single client. ive tried several things now, but nothing worked correctly.
     
  7. strudi1986

    strudi1986

    Joined:
    Jun 21, 2015
    Posts:
    10
    These are my scripts ... nothing works for seperate camera control for local players

    CharacterMovement.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class CharacterMovement : NetworkBehaviour {
    7.  
    8.     private MovementMotor motor;
    9.  
    10.     public float moveMagnitude = 0.05f;
    11.     public float speed = 0.7f;
    12.     public float speedMoveWhileAttack = 0.1f;
    13.     public float speedAttack = 1.5f;
    14.     public float turnSpeed = 10f;
    15.     public float speedJump = 20f;
    16.  
    17.     private float speedMoveMultiplier = 1f;
    18.  
    19.     private Vector3 direction;
    20.  
    21.     private Animator anim;
    22.     public Camera mainCamera;
    23.  
    24.     private string PARAMETER_STATE = "State";
    25.  
    26.  
    27.     void Awake ()
    28.     {
    29.         motor = GetComponent<MovementMotor> ();
    30.         anim = GetComponent<Animator> ();
    31.         anim.SetInteger (PARAMETER_STATE, 0);
    32.         //mainCamera.enabled = false;
    33.     }
    34.  
    35.     // Use this for initialization
    36.     void Start () {
    37.         anim.applyRootMotion = false;
    38.         Instantiate (mainCamera, this.transform);
    39.         if ( isLocalPlayer )
    40.         {
    41.  
    42.             mainCamera = Camera.main;
    43.             GameObject.Find ("Main Camera").gameObject.transform.IsChildOf(this.transform);
    44.             mainCamera.enabled = false;
    45.         }
    46.  
    47.     }
    48.  
    49.     public override void OnStartLocalPlayer ()
    50.     {
    51.         mainCamera.enabled = true;
    52.     }
    53.  
    54.     // Update is called once per frame
    55.     void FixedUpdate ()
    56.     {
    57.         if ( isLocalPlayer)
    58.         {
    59.             MovementAndJumping ();
    60.         }
    61.     }
    62.  
    63.     private Vector3 MoveDirection
    64.     {
    65.         get { return direction; }
    66.         set { direction = value * speedMoveMultiplier;
    67.  
    68.             if ( direction.magnitude > 0.1f )
    69.             {
    70.                 var newRotation = Quaternion.LookRotation (direction);
    71.                 transform.rotation = Quaternion.Lerp (transform.rotation, newRotation, Time.deltaTime * turnSpeed);
    72.             }
    73.  
    74.             direction *= speed * (Vector3.Dot (transform.forward, direction) + 1f) * 5f;
    75.             motor.Move (direction);
    76.  
    77.             AnimationMove (motor.charController.velocity.magnitude * 0.1f);
    78.         }
    79.     }
    80.  
    81.     void Moving (Vector3 dir, float mult)
    82.     {
    83.         speedMoveMultiplier = 1 * mult;
    84.         MoveDirection = dir;
    85.     }
    86.  
    87.     void Jump ()
    88.     {
    89.         anim.SetInteger (PARAMETER_STATE, 2);
    90.         motor.Jump (speedJump);
    91.     }
    92.  
    93.     void AnimationMove (float magnitude)
    94.     {
    95.         if ( magnitude > moveMagnitude )
    96.         {
    97.             float speedAnimation = magnitude * 2f;
    98.  
    99.             if ( speedAnimation < 1f )
    100.             {
    101.                 speedAnimation = 1f;
    102.             }
    103.  
    104.             if ( anim.GetInteger (PARAMETER_STATE) != 3 )
    105.             {
    106.                 anim.SetInteger (PARAMETER_STATE, 1);
    107.                 anim.speed = speedAnimation;
    108.             }
    109.         }
    110.         else
    111.         {
    112.             if ( anim.GetInteger (PARAMETER_STATE) != 3 )
    113.             {
    114.                 anim.SetInteger (PARAMETER_STATE, 0);
    115.                 anim.Play ("Idle");
    116.             }
    117.            
    118.         }
    119.     }
    120.  
    121.  
    122.         void MovementAndJumping ()
    123.         {
    124.             Vector3 moveInput = Vector3.zero;
    125.             Vector3 forward = Quaternion.AngleAxis (-90, Vector3.up) * mainCamera.transform.right;
    126.  
    127.             moveInput += forward * Input.GetAxis ("Vertical");
    128.             moveInput += mainCamera.transform.right * Input.GetAxis ("Horizontal");
    129.  
    130.             moveInput.Normalize ();
    131.             Moving (moveInput.normalized, 1f);
    132.  
    133.         if ( Input.GetKeyDown (KeyCode.Space))
    134.         {
    135.             Jump ();
    136.         }
    137.  
    138.  
    139.         }
    140.     }
    141.  
    MovementMotor.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MovementMotor : MonoBehaviour {
    6.  
    7.     public float gravityMultiplier = 1f;
    8.     public float lerpTime = 10f;
    9.  
    10.     private Vector3 moveDirection = Vector3.zero;
    11.     private Vector3 targetDirection = Vector3.zero;
    12.     private float fallVelocity = 0f;
    13.  
    14.     [HideInInspector]
    15.     public CharacterController charController;
    16.  
    17.     public float distanceToGround = 0.1f;
    18.  
    19.     private bool isGrounded;
    20.  
    21.     private Collider myCollider;
    22.  
    23.     void Awake ()
    24.     {
    25.         charController = GetComponent<CharacterController> ();
    26.         myCollider = GetComponent<Collider> ();
    27.     }
    28.  
    29.     // Use this for initialization
    30.     void Start () {
    31.         distanceToGround = myCollider.bounds.extents.y;
    32.     }
    33.    
    34.     // Update is called once per frame
    35.     void Update () {
    36.         isGrounded = OnGroundCheck ();
    37.  
    38.         moveDirection = Vector3.Lerp (moveDirection, targetDirection, Time.deltaTime * lerpTime);
    39.         moveDirection.y = fallVelocity;
    40.  
    41.         charController.Move (moveDirection * Time.deltaTime);
    42.  
    43.         if ( !isGrounded )
    44.         {
    45.             fallVelocity -= 90f * gravityMultiplier * Time.deltaTime;
    46.         }
    47.     }
    48.  
    49.     public bool OnGroundCheck ()
    50.     {
    51.         RaycastHit hit;
    52.  
    53.         if ( charController.isGrounded )
    54.         {
    55.             return true;
    56.         }
    57.  
    58.         if(Physics.Raycast(myCollider.bounds.center, -Vector3.up, out hit, distanceToGround + 0.1f) )
    59.         {
    60.             return true;
    61.         }
    62.  
    63.         return false;
    64.     }
    65.  
    66.     public void Move(Vector3 dir)
    67.     {
    68.         targetDirection = dir;
    69.     }
    70.  
    71.     public void Stop ()
    72.     {
    73.         moveDirection = Vector3.zero;
    74.         targetDirection = Vector3.zero;
    75.     }
    76.  
    77.     public void Jump(float jumpSpeed)
    78.     {
    79.         if ( isGrounded )
    80.         {
    81.             fallVelocity = jumpSpeed;
    82.         }
    83.     }
    84. }
    CameraOrbit.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class CameraOrbit : Orbit{
    7.  
    8.     public Vector3 targetOffset = new Vector3 (0, 2, 0);
    9.     public Vector3 cameraPositionZoom = new Vector3 (-0.5f, 0, 0);
    10.     public float cameraLenght = -10f;
    11.     public float cameraLenghtZoom = -5f;
    12.     public Vector2 orbitSpeed = new Vector2 (0.01f, 0.01f);
    13.     public Vector2 orbitOffset = new Vector2 (0, -0.8f);
    14.     public Vector2 angleOffset = new Vector2 (0, -0.25f);
    15.  
    16.     private float _zoomValue;
    17.     private Vector3 _cameraPositionTemp;
    18.     private Vector3 _cameraPosition;
    19.  
    20.     public Transform _playerTarget;
    21.     private Camera _mainCamera;
    22.  
    23.     void Awake ()
    24.     {
    25.    
    26.     }
    27.  
    28.     // Use this for initialization
    29.     void Start () {
    30.  
    31.         _playerTarget = GameObject.FindGameObjectWithTag ("Player").transform;
    32.    
    33.         sphericalVectorData.Lenght = cameraLenght;
    34.         sphericalVectorData.Azimuth = angleOffset.x;
    35.         sphericalVectorData.Zenith = angleOffset.y;
    36.  
    37.         _mainCamera = Camera.main;
    38.  
    39.         _cameraPositionTemp = _mainCamera.transform.localPosition;
    40.         _cameraPosition = _cameraPositionTemp;
    41.     }
    42.    
    43.     // Update is called once per frame
    44.     void Update () {
    45.  
    46.         if ( _playerTarget == null )
    47.         {
    48.             _playerTarget = GameObject.FindGameObjectWithTag ("Player").transform;
    49.         }
    50.  
    51.         if (_playerTarget != null)
    52.         {
    53.                 HandleCamera ();
    54.         }
    55.  
    56.     }
    57.  
    58.     void HandleCamera ()
    59.     {
    60.         if ( Input.GetMouseButton (1))
    61.         {
    62.                 sphericalVectorData.Azimuth += Input.GetAxis ("Mouse X") * orbitSpeed.x;
    63.                 sphericalVectorData.Zenith += Input.GetAxis ("Mouse Y") * orbitSpeed.y;
    64.  
    65.                 sphericalVectorData.Zenith = Mathf.Clamp (sphericalVectorData.Zenith + orbitOffset.x, orbitOffset.y, 0f);
    66.  
    67.         }
    68.  
    69.             float distanceToObject = _zoomValue;
    70.             float deltaDistance = Mathf.Clamp (_zoomValue, distanceToObject, -distanceToObject);
    71.             sphericalVectorData.Lenght += (deltaDistance - sphericalVectorData.Lenght);
    72.  
    73.             Vector3 lookAt = targetOffset;
    74.  
    75.             lookAt += _playerTarget.position;
    76.  
    77.             base.Update ();
    78.  
    79.             transform.position += lookAt;
    80.             transform.LookAt (lookAt);
    81.  
    82.             if ( _zoomValue == cameraLenghtZoom )
    83.             {
    84.                 Quaternion targetRotation = transform.rotation;
    85.                 targetRotation.x = 0f;
    86.                 targetRotation.z = 0f;
    87.                 _playerTarget.rotation = targetRotation;
    88.             }
    89.  
    90.             _cameraPosition = _cameraPositionTemp;
    91.             _zoomValue = cameraLenght;
    92.     }
    93. }
    94.  
    Orbit.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5.  
    6. public class Orbit : MonoBehaviour {
    7.  
    8.     public SphericalVector sphericalVectorData = new SphericalVector (0, 0, 1);
    9.  
    10.     protected virtual void Update ()
    11.     {
    12.         transform.position = sphericalVectorData.Position;
    13.     }
    14.  
    15. }
    16.