Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Unity Multiplayer IsLocalPlayer (mirror) return NullPointerException

Discussion in 'Multiplayer' started by swordcat13, Oct 19, 2020.

  1. swordcat13

    swordcat13

    Joined:
    May 23, 2018
    Posts:
    3
    Hi everyone!
    In my game, a multiplayer FPS, all the players move at once if only one press a key.
    I tryed to test for
    Code (CSharp):
    1. GetComponent<NetworkIdentity>().isLocalPlayer
    , but it doesnt not work, and it return the following error:

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. PlayerMovement.FixedUpdate () (at Assets/FPS_Movement_Rigidbody-master/PlayerMovement.cs:76)
    Here is my full code:

    Code (CSharp):
    1. // Some stupid rigidbody based movement by Dani
    2. //Updated to shoot, and be 'a little bit' multiplayer
    3. using System;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. using UnityEngine.Networking;
    7. public class PlayerMovement : MonoBehaviour {
    8.  
    9.     //Assingables
    10.     public Transform playerCam;
    11.     public Transform orientation;
    12.    
    13.     //Other
    14.     private Rigidbody rb;
    15.  
    16.     //Rotation and look
    17.     private float xRotation;
    18.     private float sensitivity = 50f;
    19.     private float sensMultiplier = 1f;
    20.    
    21.     //Movement
    22.     public float moveSpeed = 4500;
    23.     public float maxSpeed = 20;
    24.     public bool grounded;
    25.     public LayerMask whatIsGround;
    26.    
    27.     public float counterMovement = 0.175f;
    28.     private float threshold = 0.01f;
    29.     public float maxSlopeAngle = 35f;
    30.  
    31.     //Crouch & Slide
    32.     private Vector3 crouchScale = new Vector3(1, 0.5f, 1);
    33.     private Vector3 playerScale;
    34.     public float slideForce = 400;
    35.     public float slideCounterMovement = 0.2f;
    36.  
    37.     //Jumping
    38.     private bool readyToJump = true;
    39.     private float jumpCooldown = 0.25f;
    40.     public float jumpForce = 550f;
    41.    
    42.     //Shooting (SC)
    43.     public GameObject bullet;
    44.  
    45.     //Life (SC)
    46.     public float life=100;
    47.     public Text lifetext;
    48.     private GameObject spawne;
    49.     public GameObject dede;
    50.     public GameObject selfi;
    51.     //Input
    52.     float x, y;
    53.     bool jumping, sprinting, crouching;
    54.    
    55.     //Sliding
    56.     private Vector3 normalVector = Vector3.up;
    57.     private Vector3 wallNormalVector;
    58.  
    59.     void Awake() {
    60.         rb = GetComponent<Rigidbody>();
    61.         lifetext=GameObject.Find("LIFE").GetComponent<Text>();
    62.         spawne=GameObject.Find("Spawns");
    63.     }
    64.    
    65.     void Start() {
    66.         playerScale =  transform.localScale;
    67.         Cursor.lockState = CursorLockMode.Locked;
    68.         Cursor.visible = false;
    69.     }
    70.  
    71.    
    72.     private void FixedUpdate() {
    73.         //if(GetComponent<NetworkIdentity>().isMine)
    74. //{
    75.         //Debug.Log(GetComponent<NetworkIdentity>().isLocalPlayer());
    76.         if(GetComponent<NetworkIdentity>().isLocalPlayer)//GetComponent<NetworkIdentity>().isLocalPlayer)
    77.             Movement();
    78.     //}
    79.     }
    80.     private Vector3 getRespawn(){
    81.         int children = transform.childCount;//Hi!
    82.         Transform[] cows=new Transform[children];
    83.          for (int i = 0; i < children; ++i){
    84.              cows[i]=transform.GetChild(i);
    85.          }
    86.    
    87.      Vector3 meow=cows[UnityEngine.Random.Range(0, cows.Length)].position;
    88.      return meow;
    89.     }
    90.     private void ded(){
    91.         GameObject cow=Instantiate(dede, transform.position, transform.rotation);
    92.         //GameObject gerbil=Instantiate(selfi, transform.position, transform.rotation);//Respawn
    93.         //Destroy(gameObject);
    94.         Destroy(cow, 10f);
    95.         Debug.Log("DEED");
    96.         life=100;
    97.         GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag("spawn");
    98.         GameObject currentPoint;
    99.         int index=0;
    100.          index = UnityEngine.Random.Range (0, spawnPoints.Length);
    101.          currentPoint = spawnPoints[index];
    102.         transform.position=currentPoint.transform.position;//boo
    103.     }
    104.     private void Update() {
    105.         //if(GetComponent<NetworkIdentity>().isMine){
    106.         if(GetComponent<NetworkIdentity>().isLocalPlayer){//GetComponent<NetworkIdentity>().isLocalPlayer){
    107.         MyInput();
    108.         Look();
    109.         lifetext.text="Life: "+life;
    110.         if (life<0f) {
    111.             ded();
    112.         }
    113.     }
    114.    // }
    115.  
    116.     }
    117.  
    118.     /// <summary>
    119.     /// Find user input. Should put this in its own class but im lazy
    120.     /// </summary>
    121.    
    122.     private void MyInput() {
    123.         x = Input.GetAxisRaw("Horizontal");
    124.         y = Input.GetAxisRaw("Vertical");
    125.         jumping = Input.GetButton("Jump");
    126.         crouching = Input.GetKey(KeyCode.LeftControl);
    127.         //Shooting(SC)
    128.      
    129.  
    130.      
    131.         //Crouching
    132.         if (Input.GetKeyDown(KeyCode.LeftControl))
    133.             StartCrouch();
    134.         if (Input.GetKeyUp(KeyCode.LeftControl))
    135.             StopCrouch();
    136.     }
    137.  
    138.     private void StartCrouch() {
    139.         transform.localScale = crouchScale;
    140.         transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
    141.         if (rb.velocity.magnitude > 0.5f) {
    142.             if (grounded) {
    143.                 rb.AddForce(orientation.transform.forward * slideForce);
    144.             }
    145.         }
    146.     }
    147.  
    148.     private void StopCrouch() {
    149.         transform.localScale = playerScale;
    150.         transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
    151.     }
    152.  
    153.     private void Movement() {
    154.         //Extra gravity
    155.         rb.AddForce(Vector3.down * Time.deltaTime * 10);
    156.        
    157.         //Find actual velocity relative to where player is looking
    158.         Vector2 mag = FindVelRelativeToLook();
    159.         float xMag = mag.x, yMag = mag.y;
    160.  
    161.         //Counteract sliding and sloppy movement
    162.         CounterMovement(x, y, mag);
    163.        
    164.         //If holding jump && ready to jump, then jump
    165.         if (readyToJump && jumping) Jump();
    166.  
    167.         //Set max speed
    168.         float maxSpeed = this.maxSpeed;
    169.        
    170.         //If sliding down a ramp, add force down so player stays grounded and also builds speed
    171.         if (crouching && grounded && readyToJump) {
    172.             rb.AddForce(Vector3.down * Time.deltaTime * 3000);
    173.             return;
    174.         }
    175.        
    176.         //If speed is larger than maxspeed, cancel out the input so you don't go over max speed
    177.         if (x > 0 && xMag > maxSpeed) x = 0;
    178.         if (x < 0 && xMag < -maxSpeed) x = 0;
    179.         if (y > 0 && yMag > maxSpeed) y = 0;
    180.         if (y < 0 && yMag < -maxSpeed) y = 0;
    181.  
    182.         //Some multipliers
    183.         float multiplier = 1f, multiplierV = 1f;
    184.        
    185.         // Movement in air
    186.         if (!grounded) {
    187.             multiplier = 0.5f;
    188.             multiplierV = 0.5f;
    189.         }
    190.        
    191.         // Movement while sliding
    192.         if (grounded && crouching) multiplierV = 0f;
    193.  
    194.         //Apply forces to move player
    195.         rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
    196.         rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
    197.     }
    198.  
    199.     private void Jump() {
    200.         if (grounded && readyToJump) {
    201.             readyToJump = false;
    202.  
    203.             //Add jump forces
    204.             rb.AddForce(Vector2.up * jumpForce * 1.5f);
    205.             rb.AddForce(normalVector * jumpForce * 0.5f);
    206.            
    207.             //If jumping while falling, reset y velocity.
    208.             Vector3 vel = rb.velocity;
    209.             if (rb.velocity.y < 0.5f)
    210.                 rb.velocity = new Vector3(vel.x, 0, vel.z);
    211.             else if (rb.velocity.y > 0)
    212.                 rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
    213.            
    214.             Invoke(nameof(ResetJump), jumpCooldown);
    215.         }
    216.     }
    217.    
    218.     private void ResetJump() {
    219.         readyToJump = true;
    220.     }
    221.    
    222.     private float desiredX;
    223.     private void Look() {
    224.         float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    225.         float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    226.  
    227.         //Find current look rotation
    228.         Vector3 rot = playerCam.transform.localRotation.eulerAngles;
    229.         desiredX = rot.y + mouseX;
    230.        
    231.         //Rotate, and also make sure we dont over- or under-rotate.
    232.         xRotation -= mouseY;
    233.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    234.  
    235.         //Perform the rotations
    236.         playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0);
    237.         orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
    238.     }
    239.  
    240.     private void CounterMovement(float x, float y, Vector2 mag) {
    241.         if (!grounded || jumping) return;
    242.  
    243.         //Slow down sliding
    244.         if (crouching) {
    245.             rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideCounterMovement);
    246.             return;
    247.         }
    248.  
    249.         //Counter movement
    250.         if (Math.Abs(mag.x) > threshold && Math.Abs(x) < 0.05f || (mag.x < -threshold && x > 0) || (mag.x > threshold && x < 0)) {
    251.             rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * -mag.x * counterMovement);
    252.         }
    253.         if (Math.Abs(mag.y) > threshold && Math.Abs(y) < 0.05f || (mag.y < -threshold && y > 0) || (mag.y > threshold && y < 0)) {
    254.             rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * -mag.y * counterMovement);
    255.         }
    256.        
    257.         //Limit diagonal running. This will also cause a full stop if sliding fast and un-crouching, so not optimal.
    258.         if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maxSpeed) {
    259.             float fallspeed = rb.velocity.y;
    260.             Vector3 n = rb.velocity.normalized * maxSpeed;
    261.             rb.velocity = new Vector3(n.x, fallspeed, n.z);
    262.         }
    263.     }
    264.  
    265.     /// <summary>
    266.     /// Find the velocity relative to where the player is looking
    267.     /// Useful for vectors calculations regarding movement and limiting movement
    268.     /// </summary>
    269.     /// <returns></returns>
    270.     public Vector2 FindVelRelativeToLook() {
    271.         float lookAngle = orientation.transform.eulerAngles.y;
    272.         float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
    273.  
    274.         float u = Mathf.DeltaAngle(lookAngle, moveAngle);
    275.         float v = 90 - u;
    276.  
    277.         float magnitue = rb.velocity.magnitude;
    278.         float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
    279.         float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
    280.        
    281.         return new Vector2(xMag, yMag);
    282.     }
    283.  
    284.     private bool IsFloor(Vector3 v) {
    285.         float angle = Vector3.Angle(Vector3.up, v);
    286.         return angle < maxSlopeAngle;
    287.     }
    288.  
    289.     private bool cancellingGrounded;
    290.    
    291.     /// <summary>
    292.     /// Handle ground detection
    293.     /// </summary>
    294.     private void OnCollisionStay(Collision other) {
    295.         //Make sure we are only checking for walkable layers
    296.         int layer = other.gameObject.layer;
    297.         if (whatIsGround != (whatIsGround | (1 << layer))) return;
    298.  
    299.         //Iterate through every collision in a physics update
    300.         for (int i = 0; i < other.contactCount; i++) {
    301.             Vector3 normal = other.contacts[i].normal;
    302.             //FLOOR
    303.             if (IsFloor(normal)) {
    304.                 grounded = true;
    305.                 cancellingGrounded = false;
    306.                 normalVector = normal;
    307.                 CancelInvoke(nameof(StopGrounded));
    308.             }
    309.         }
    310.  
    311.         //Invoke ground/wall cancel, since we can't check normals with CollisionExit
    312.         float delay = 3f;
    313.         if (!cancellingGrounded) {
    314.             cancellingGrounded = true;
    315.             Invoke(nameof(StopGrounded), Time.deltaTime * delay);
    316.         }
    317.     }
    318.  
    319.     private void StopGrounded() {
    320.         grounded = false;
    321.     }
    322.    
    323. }
    324.  
    Have a good day(and please, help me).
     
  2. vis2k

    vis2k

    Joined:
    Sep 4, 2015
    Posts:
    4,283
    Check out our documentation and examples.
    NetworkMovement needs to be of type NetworkBehaviour and you need a NetworkIdentity component too :)
     
  3. swordcat13

    swordcat13

    Joined:
    May 23, 2018
    Posts:
    3
    I added a NetworkIdentity, checked it twice (or more?)
    Also, i checked examples, and they use isLocalPlayer, and it work fine...
    Here is a screenshot of my NetworkIdentity on player (Player_Used):
     
  4. swordcat13

    swordcat13

    Joined:
    May 23, 2018
    Posts:
    3
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,824
    Check that your GetComponent<NetworkIdentity>() call is actually returning an instance of NetworkIdentity instead of null before you try to use it.