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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Object reference not set to instance of an object

Discussion in 'Scripting' started by RhinoRunnerGaming29, Jul 3, 2022.

  1. RhinoRunnerGaming29

    RhinoRunnerGaming29

    Joined:
    May 31, 2022
    Posts:
    10
    I do not know what this means

    NullReferenceException: Object reference not set to an instance of an object
    RhinoRunnerGaming.Weapon.RefreshAmmo (UnityEngine.UI.Text p_text) (at Assets/scripts/Weapon.cs:189)
    RhinoRunnerGaming.Player.Update () (at Assets/scripts/Player.cs:126)

    here is my player code

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine.UI;
    4. using UnityEngine;
    5. using Photon.Pun;
    6.  
    7. namespace RhinoRunnerGaming
    8. {
    9.     public class Player : MonoBehaviourPunCallbacks
    10.     {
    11.  
    12.         #region Variables
    13.  
    14.         public float speed;
    15.         public float sprintModifier;
    16.         public Camera playerCamera;
    17.         public GameObject cameraParent;
    18.         public float jumpForce;
    19.         public int maxHealth;
    20.         public Transform weaponParent;
    21.         public Transform groundDetector;
    22.         public LayerMask ground;
    23.  
    24.         private Transform ui_healthbar;
    25.         private Text ui_ammo;
    26.  
    27.         private Rigidbody rig;
    28.  
    29.         private Vector3 targetWeaponBobPosition;
    30.         private Vector3 weaponParentOrgin;
    31.  
    32.         private float movementCounter;
    33.         private float idleCounter;
    34.  
    35.         private float baseFOV;
    36.         private float sprintFOVModifier = 1.5f;
    37.  
    38.         private int currentHealth;
    39.  
    40.         private Manager manager;
    41.         private Weapon weapon;
    42.  
    43.         #endregion
    44.  
    45.         #region Monobehaivier Callbacks
    46.  
    47.         void Start()
    48.         {
    49.  
    50.             manager = GameObject.Find("Manager").GetComponent<Manager>();
    51.             weapon = GetComponent<Weapon>();
    52.  
    53.             currentHealth = maxHealth;
    54.  
    55.             if (photonView.IsMine)
    56.             {
    57.                 gameObject.layer = 8;            
    58.             }
    59.  
    60.             cameraParent.SetActive(photonView.IsMine);
    61.  
    62.             baseFOV = playerCamera.fieldOfView;
    63.             rig = GetComponent<Rigidbody>();
    64.             weaponParentOrgin = weaponParent.localPosition;
    65.  
    66.             if (photonView.IsMine)
    67.             {
    68.                 ui_healthbar = GameObject.Find("HUD/Health/Bar").transform;
    69.                 ui_ammo = GameObject.Find("HUD/Ammo/Text").GetComponent<Text>();
    70.                 RefreshHealthBar();
    71.             }
    72.            
    73.         }
    74.  
    75.         private void Update()
    76.         {
    77.            
    78.  
    79.             //Axis
    80.             float t_hmove = Input.GetAxisRaw("Horizontal");
    81.             float t_vmove = Input.GetAxisRaw("Vertical");
    82.  
    83.             //Controls
    84.             bool sprint = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
    85.             bool jump = Input.GetKeyDown(KeyCode.Space);
    86.  
    87.             //States
    88.             bool isGrounded = Physics.Raycast(groundDetector.position, Vector3.down, 1f, ground);
    89.             bool isJumping = jump && isGrounded;
    90.             bool isSprinting = sprint && t_vmove > 0 && !jump;
    91.  
    92.  
    93.             //Jumping
    94.             if (jump && isGrounded)
    95.             {
    96.                 rig.AddForce(Vector3.up * jumpForce);
    97.             }
    98.  
    99.             if (Input.GetKeyDown(KeyCode.U))
    100.             {
    101.                 TakeDamage(100);
    102.             }
    103.  
    104.             //Head Bob
    105.             if (t_hmove == 0 && t_vmove == 0)
    106.             {
    107.                 HeadBob(idleCounter, 0.025f, 0.025f);
    108.                 idleCounter += Time.deltaTime;
    109.                 weaponParent.localPosition = Vector3.Lerp(weaponParent.localPosition, targetWeaponBobPosition, Time.deltaTime * 2f);
    110.             }
    111.             else if (!isSprinting)
    112.             {
    113.                 HeadBob(movementCounter, 0.035f, 0.035f);
    114.                 movementCounter += Time.deltaTime * 3f;
    115.                 weaponParent.localPosition = Vector3.Lerp(weaponParent.localPosition, targetWeaponBobPosition, Time.deltaTime * 6f);
    116.             }
    117.             else
    118.             {
    119.                 HeadBob(movementCounter, 0.15f, 0.075f);
    120.                 movementCounter += Time.deltaTime * 7f;
    121.                 weaponParent.localPosition = Vector3.Lerp(weaponParent.localPosition, targetWeaponBobPosition, Time.deltaTime * 10f);
    122.             }
    123.  
    124.             // UI Refreshes
    125.             RefreshHealthBar();
    126.             weapon.RefreshAmmo(ui_ammo);
    127.         }
    128.  
    129.         void FixedUpdate()
    130.         {
    131.  
    132.             if (!photonView.IsMine)
    133.             {
    134.                 return;
    135.             }
    136.  
    137.             //Axis
    138.             float t_hmove = Input.GetAxisRaw("Horizontal");
    139.             float t_vmove = Input.GetAxisRaw("Vertical");
    140.  
    141.             //Controls
    142.             bool sprint = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
    143.             bool jump = Input.GetKeyDown(KeyCode.Space);
    144.  
    145.             //States
    146.             bool isGrounded = Physics.Raycast(groundDetector.position, Vector3.down, 1f, ground);
    147.             bool isJumping = jump && isGrounded;
    148.             bool isSprinting = sprint && t_vmove > 0 && !jump;
    149.  
    150.  
    151.             //Movement
    152.             Vector3 t_direction = new Vector3(t_hmove, 0, t_vmove);
    153.             t_direction.Normalize();
    154.  
    155.             float t_adjustedSpeed = speed;
    156.             if (isSprinting) t_adjustedSpeed *= sprintModifier;
    157.  
    158.             Vector3 t_targetVelocity = transform.TransformDirection(t_direction) * t_adjustedSpeed * Time.deltaTime;
    159.             t_targetVelocity.y = rig.velocity.y;
    160.             rig.velocity = t_targetVelocity;
    161.  
    162.            
    163.             //Field of View
    164.             if (isSprinting)
    165.             {
    166.                 playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, baseFOV * sprintFOVModifier, Time.deltaTime * 8);
    167.             }
    168.             else
    169.             {
    170.                 playerCamera.fieldOfView = Mathf.Lerp(playerCamera.fieldOfView, baseFOV, Time.deltaTime * 8);
    171.             }
    172.         }
    173.  
    174.         #endregion
    175.  
    176.         #region Private Methods
    177.  
    178.         void RefreshHealthBar()
    179.         {
    180.             float t_health_ratio = (float)currentHealth / (float)maxHealth;
    181.             ui_healthbar.localScale = Vector3.Lerp(ui_healthbar.localScale, new Vector3(t_health_ratio, 1, 1), Time.deltaTime * 8f);
    182.         }
    183.  
    184.         void HeadBob(float p_z, float p_x_intensity, float p_y_intensity)
    185.         {
    186.            targetWeaponBobPosition = weaponParent.localPosition = weaponParentOrgin + new Vector3(Mathf.Cos(p_z) * p_x_intensity, Mathf.Sin(p_z * 2) * p_y_intensity, 0);
    187.         }
    188.  
    189.         #endregion
    190.  
    191.         #region Public Methods
    192.  
    193.        
    194.         public void TakeDamage (int p_damage)
    195.         {
    196.             if (photonView.IsMine)
    197.             {
    198.                 currentHealth -= p_damage;
    199.                 RefreshHealthBar();
    200.                 Debug.Log(currentHealth);
    201.  
    202.                 if(currentHealth <= 0)
    203.                 {
    204.                     manager.Spawn();
    205.                     PhotonNetwork.Destroy(gameObject);
    206.                 }
    207.             }
    208.            
    209.         }
    210.  
    211.  
    212.  
    213.         #endregion
    214.     }
    215. }

    here is my weapon code

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine.UI;
    4. using UnityEngine;
    5. using Photon.Pun;
    6.  
    7. namespace RhinoRunnerGaming
    8. {
    9.     public class Weapon : MonoBehaviourPunCallbacks
    10.     {
    11.         #region Variables
    12.  
    13.         public Gun[] loadout;
    14.         public Transform weaponParent;
    15.         public GameObject bulletHolePrefab;
    16.         public LayerMask canBeShot;
    17.  
    18.         private float currentCooldown;
    19.         private int currentIndex;
    20.         private GameObject currentWeapon;
    21.  
    22.         private bool isReloading;
    23.  
    24.         #endregion
    25.  
    26.         #region Monobehavior Callbacks
    27.  
    28.         private void Start()
    29.         {
    30.             foreach (Gun a in loadout) a.Initialize();
    31.             Equip(0);
    32.         }
    33.  
    34.         void Update()
    35.         {
    36.  
    37.             if (photonView.IsMine && Input.GetKeyDown(KeyCode.Alpha1))
    38.             {
    39.                 photonView.RPC("Equip", RpcTarget.All, 0);
    40.             }
    41.  
    42.             if (currentWeapon != null)
    43.             {
    44.                 if (photonView.IsMine)
    45.                 {
    46.                     Aim(Input.GetMouseButton(1));
    47.  
    48.                     if (Input.GetMouseButtonDown(0) && currentCooldown <= 0)
    49.                     {
    50.                         if (loadout[currentIndex].FireBullet())
    51.                         {
    52.                             photonView.RPC("Shoot", RpcTarget.All);
    53.                         }
    54.                         else
    55.                         {
    56.                             loadout[currentIndex].Reload();
    57.                         }
    58.                        
    59.                     }
    60.  
    61.                     if (Input.GetKeyDown(KeyCode.R))
    62.                     {
    63.                         StartCoroutine(Reload(loadout[currentIndex].reload));
    64.                     }
    65.  
    66.                     //CoolDown
    67.                     if (currentCooldown > 0)
    68.                     {
    69.                         currentCooldown -= Time.deltaTime;
    70.                     }
    71.                 }
    72.      
    73.                 //weapon position eleasticity
    74.                 currentWeapon.transform.localPosition = Vector3.Lerp(currentWeapon.transform.localPosition, Vector3.zero, Time.deltaTime * 4f);
    75.  
    76.             }
    77.  
    78.         }
    79.  
    80.         #endregion
    81.  
    82.         #region Private Methods
    83.  
    84.         IEnumerator Reload(float p_wait)
    85.         {
    86.             isReloading = true;
    87.             currentWeapon.SetActive(false);
    88.  
    89.             yield return new WaitForSeconds(p_wait);
    90.  
    91.             loadout[currentIndex].Reload();
    92.             currentWeapon.SetActive(true);
    93.             isReloading = false;
    94.         }
    95.  
    96.         [PunRPC]
    97.         void Equip(int p_ind)
    98.         {
    99.             if (currentWeapon != null)
    100.             {
    101.                 if(isReloading) StopCoroutine("Reload");
    102.                 Destroy(currentWeapon);
    103.             }
    104.  
    105.             currentIndex = p_ind;
    106.  
    107.             GameObject t_newWeapon = Instantiate(loadout[p_ind].prefab, weaponParent.position, weaponParent.rotation, weaponParent) as GameObject;
    108.             t_newWeapon.transform.localPosition = Vector3.zero;
    109.             t_newWeapon.transform.localEulerAngles = Vector3.zero;
    110.             t_newWeapon.GetComponent<Sway>().isMine = photonView.IsMine;
    111.  
    112.             currentWeapon = t_newWeapon;
    113.         }
    114.         void Aim(bool p_isAiming)
    115.         {
    116.             Transform t_anchor = currentWeapon.transform.Find("anchor");
    117.             Transform t_state_ads = currentWeapon.transform.Find("states/ADS");
    118.             Transform t_state_hip = currentWeapon.transform.Find("states/hips");
    119.  
    120.             if (p_isAiming)
    121.             {
    122.                 //aim
    123.                 t_anchor.position = Vector3.Lerp(t_anchor.position, t_state_ads.position, Time.deltaTime * loadout[currentIndex].aimspeed);
    124.             }
    125.             else
    126.             {
    127.                 //hip
    128.                 t_anchor.position = Vector3.Lerp(t_anchor.position, t_state_hip.position, Time.deltaTime * loadout[currentIndex].aimspeed);
    129.             }
    130.         }
    131.  
    132.         [PunRPC]
    133.         void Shoot()
    134.         {
    135.             Transform t_spawn = transform.Find("camera/playerCamera");
    136.  
    137.            
    138.  
    139.             //gun fx
    140.             currentWeapon.transform.Rotate(-loadout[currentIndex].recoil, 0, 0);
    141.             currentWeapon.transform.position -= currentWeapon.transform.forward * loadout[currentIndex].kickback;
    142.  
    143.             //setup bloom
    144.             Vector3 t_bloom = t_spawn.position + t_spawn.forward * 1000f;
    145.             t_bloom += Random.Range(-loadout[currentIndex].bloom, loadout[currentIndex].bloom) * t_spawn.up;
    146.             t_bloom += Random.Range(-loadout[currentIndex].bloom, loadout[currentIndex].bloom) * t_spawn.right;
    147.             t_bloom -= t_spawn.position;
    148.             t_bloom.Normalize();
    149.  
    150.             //raycast
    151.             RaycastHit t_hit = new RaycastHit();
    152.             if (Physics.Raycast(t_spawn.position, t_bloom, out t_hit, 1000f, canBeShot))
    153.             {
    154.                 GameObject t_newHole = Instantiate(bulletHolePrefab, t_hit.point + t_hit.normal * 0.001f, Quaternion.identity) as GameObject;
    155.                 t_newHole.transform.LookAt(t_hit.point + t_hit.normal);
    156.                 Destroy(t_newHole, 5f);
    157.  
    158.                 if (photonView.IsMine)
    159.                 {
    160.                     //Shootin other player on network
    161.                     if (t_hit.collider.gameObject.layer == 11)
    162.                     {
    163.                         t_hit.collider.gameObject.GetPhotonView().RPC("TakeDamage", RpcTarget.All, loadout[currentIndex].damage);
    164.                     }
    165.                 }
    166.             }
    167.  
    168.             //cooldown
    169.             currentCooldown = loadout[currentIndex].firerate;
    170.            
    171.         }
    172.  
    173.         [PunRPC]
    174.         private void TakeDamage (int p_damage)
    175.         {
    176.             GetComponent<Player>().TakeDamage(p_damage);
    177.         }
    178.  
    179.  
    180.         #endregion
    181.  
    182.         #region Public Methods
    183.  
    184.         public void RefreshAmmo(Text p_text)
    185.         {
    186.             int t_clip = loadout[currentIndex].GetClip();
    187.             int t_stache = loadout[currentIndex].GetStash();
    188.  
    189.             p_text.text = t_clip.ToString("D2") + " / " + t_stache.ToString("D2");
    190.         }
    191.  
    192.  
    193.         #endregion
    194.     }
    195.  
    196. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
  3. RhinoRunnerGaming29

    RhinoRunnerGaming29

    Joined:
    May 31, 2022
    Posts:
    10
    Thanks, after following your three steps I managed to fix my mistake and realized how simple it was to fix it.