Search Unity

Null Reference Exception in my BeatEmUp

Discussion in 'Editor & General Support' started by Numonic, Dec 27, 2017.

  1. Numonic

    Numonic

    Joined:
    Mar 22, 2009
    Posts:
    241
    I keep getting a
    NullReferenceException: Object reference not set to an instance of an object
    FootDoDamage.FootTakeDamage () (at Assets/Scripts/FootDoDamage.cs:139)
    FootDoDamage.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/FootDoDamage.cs:184)

    My Footsolder is a prefab and is tied to a Attack inside a list.

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(AudioSource))]
    6.  
    7. public class FootDoDamage : MonoBehaviour
    8. {
    9.  
    10.  
    11.     GameManager gameManager;
    12.     CharacterStats characterStats;
    13.     PlayerController playerController;
    14.     public Animator anim;
    15.     public GameObject explosionPrefab;
    16.  
    17.     public AudioSource footExplosionSound;
    18.  
    19.  
    20.     public EnemySight enemySight;
    21.     public GameObject punchAttackObj;
    22.     public GameObject kickAttackObj;
    23.  
    24.     public int footHealth = 100;
    25.     public int footScore = 1;
    26.  
    27.     void Start()
    28.     {
    29.  
    30.  
    31.  
    32.  
    33.         if (explosionPrefab ==null)
    34.         {
    35.             explosionPrefab = GetComponent<GameObject>();
    36.         }
    37.    
    38.         if(footExplosionSound == null)
    39.         {
    40.             footExplosionSound = GetComponent<AudioSource>();
    41.         }
    42.    
    43.         footExplosionSound = GetComponent<AudioSource>();
    44.  
    45.  
    46.         if (anim == null)
    47.         {
    48.             anim = GetComponent<Animator>();
    49.         }
    50.  
    51.         if (playerController == null)
    52.         {
    53.             playerController = GetComponent<PlayerController>();
    54.         }
    55.  
    56.         if (enemySight == null)
    57.         {
    58.             enemySight = GetComponent<EnemySight>();
    59.         }
    60.  
    61.         if (gameManager == null)
    62.         {
    63.             gameManager = GetComponent<GameManager>();
    64.  
    65.         }
    66.    
    67.          if(characterStats == null)
    68.         {
    69.             characterStats = GetComponent<CharacterStats>();
    70.  
    71.         }
    72.  
    73.  
    74.         if (footHealth <0)
    75.         {
    76.             characterStats.AddScore();
    77.         }
    78.    
    79.     }
    80.  
    81.     // Update is called once per frame
    82.     void Update()
    83.     {
    84.  
    85.  
    86.     }
    87.  
    88.     public void FootScore()
    89.     {
    90.         if (footHealth <= 0)
    91.         {
    92.             footScore++;
    93.             print("FootSolderLossing Health.");
    94.         }
    95.     }
    96.  
    97.     public void HidePunchAttack()
    98.     {
    99.         enemySight.anim.SetBool("attackcombo", false);
    100.         punchAttackObj.SetActive(false);
    101.     }
    102.  
    103.     public void ShowPunchAttack()
    104.     {
    105.         enemySight.anim.SetBool("attackcombo", true);
    106.         punchAttackObj.SetActive(true);
    107.     }
    108.  
    109.     public void HideKickAttack()
    110.     {
    111.         enemySight.anim.SetBool("attackcombo", false);
    112.  
    113.         kickAttackObj.SetActive(false);
    114.     }
    115.  
    116.     public void ShowKickAttack()
    117.     {
    118.         enemySight.anim.SetBool("attackcombo", true);
    119.  
    120.         kickAttackObj.SetActive(true);
    121.     }
    122.  
    123.     public void FootTakeDamage()
    124.     {
    125.  
    126.         if (this.gameObject != null)
    127.  
    128.             {
    129.                 // Taking away health based on sword attack
    130.                 footHealth -= 25; // take away 50 from attack
    131.        
    132.             anim.SetBool("hit", true);
    133.             anim.SetBool("attackcombo", false);
    134.             anim.SetBool("walk", false);
    135.             gameObject.SetActive(true);
    136.  
    137.             if (footHealth <= 0)
    138.             {
    139.                 characterStats.AddScore();
    140.                 anim.SetBool("hit", false);
    141.                 anim.SetBool("defeated", true);
    142.                 CancelInvoke("FootSolder");
    143.                 StartCoroutine(HideFootSolder()); // Call the coroutine here and hide object
    144.  
    145.                 enemySight.navMeshAgent.updateRotation = false;
    146.                 enemySight.navMeshAgent.angularSpeed = 0;
    147.                 enemySight.navMeshAgent.isStopped = true;
    148.                //enemySight.navMeshAgent.enabled = false;
    149.             }
    150.         }
    151.  
    152.  
    153.  
    154.     }
    155.     // Hide object in Coroutine instead of out right destroying it and causing errors.
    156.     IEnumerator HideFootSolder()
    157.     {
    158.         //There was a major Missing Component exception and it seemed to be fixed.
    159.         yield return new WaitForSeconds(1.5f);
    160.  
    161.         try {
    162.               footExplosionSound.Play();
    163.               Instantiate(explosionPrefab, transform.position, Quaternion.identity);
    164.               //Destroy(gameObject, 1.5f);
    165.               gameObject.SetActive(false);
    166.  
    167.               //GetComponent<CapsuleCollider>().enabled = false;
    168.               // GetComponent<CharacterController>().enabled = false;
    169.  
    170.             }
    171.  
    172.             catch (MissingComponentException)
    173.             {
    174.                 footExplosionSound = FindObjectOfType<AudioSource>();
    175.  
    176.             }
    177.  
    178.     }
    179.  
    180.     void OnTriggerEnter(Collider other)
    181.     {
    182.         if (other.tag == "lkatana" || other.tag == "rkatana" || other.tag == "leorfootattack")
    183.         {
    184.             FootTakeDamage();
    185.    
    186.             // To Do Get the Blocked Colliders to turn off when players are defeated
    187.             print("Leo is hitting FootSolder.");
    188.         }
    189.  
    190.     }
    191.  
    192.  
    193. }
    194.  
    195.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityStandardAssets.Utility;
    5.  
    6. public class Enemies : MonoBehaviour {
    7.  
    8.  
    9.     public Transform []spawnPosition;
    10.     public GameObject footPrefab; //footPrefab2, //footPrefab3;
    11.     public List<Transform> enemiesSpawned = new List<Transform>();
    12.  
    13.     public FollowTarget followTarget;
    14.     public CameraFollow cameraFollow;
    15.     public GameObject blockColliders;
    16.  
    17.     public bool wave1;
    18.     public bool wave2;
    19.     public bool wave3;
    20.  
    21.     public int spawnRateMax = 6;
    22.     public int spawnRateMin = 1;
    23.     public float spawnTime = 3f;
    24.  
    25.     public float countdown;
    26.     private float currentTime;
    27.  
    28.  
    29.     // Use this for initialization
    30.     void Awake ()
    31.     {
    32.         currentTime = countdown;
    33.  
    34.        // InvokeRepeating("Wave1Attack", spawnTime, spawnTime);
    35.  
    36.         if(cameraFollow == null)
    37.         {
    38.             cameraFollow = GetComponent<CameraFollow>();
    39.  
    40.         }
    41.  
    42.  
    43.         if(blockColliders ==null)
    44.         {
    45.             blockColliders = GetComponent<GameObject>();
    46.         }
    47.  
    48.  
    49.         if(followTarget == null)
    50.         {
    51.             followTarget = GetComponent<FollowTarget>();
    52.  
    53.         }
    54.     }
    55.  
    56.  
    57.     // Update is called once per frame
    58.     void Update ()
    59.     {
    60.  
    61.  
    62.         /*
    63.         countdown -= Time.deltaTime;
    64.  
    65.         if(countdown <= 0)
    66.         {
    67.             wave1 = true;
    68.              Wave1Attack();
    69.  
    70.             // camera stops following player when a wave is on
    71.             cameraFollow.enabled = false;
    72.             wave1 = false;
    73.  
    74.             //print("time is up.");
    75.         }
    76.  
    77.         else
    78.         {
    79.             wave1 = false;
    80.             CancelInvoke("Wave1Attack");
    81.             cameraFollow.enabled = true;
    82.         }
    83.         */
    84.  
    85.         /*
    86.         if(wave1 )
    87.         {
    88.             wave1 = true;
    89.             Wave1Attack();
    90.         }
    91.  
    92.         if(!wave1)
    93.         {
    94.             wave1 = false;
    95.             CancelInvoke("Wave1Attack");
    96.         }
    97.          */
    98.     }
    99.  
    100.  
    101.     public void BlockCollidersOn()
    102.     {
    103.         blockColliders.SetActive(true);
    104.         followTarget.enabled = true;
    105.     }
    106.  
    107.     public void BlockCollidersOff()
    108.     {
    109.         blockColliders.SetActive(false);
    110.         followTarget.enabled = false;
    111.     }
    112.  
    113.  
    114.  
    115.     public void SpawnEnemies()
    116.       {
    117.           int ranValue = Random.Range(spawnRateMin, spawnRateMax +1);
    118.  
    119.           for (int i = 0; i < ranValue; i++)
    120.           {
    121.               int ranSpawn = Random.Range(0, spawnPosition.Length);
    122.               GameObject go = Instantiate(footPrefab, spawnPosition[ranValue].position, Quaternion.identity) as GameObject;
    123.               enemiesSpawned.Add(go.transform);
    124.           }
    125.       }
    126.  
    127.  
    128.  
    129.   /*
    130.     public void Wave1Attack()
    131.     {
    132.  
    133.         int spawnPointIndex = Random.Range(0, spawnPosition.Length);
    134.  
    135.         Instantiate (footPrefab, spawnPosition[spawnPointIndex].position, spawnPosition[spawnPointIndex].rotation);
    136.     }
    137.     */
    138.    }
    139.  
    140.  
    141.  
    142.  
     

    Attached Files:

    Last edited: Dec 27, 2017
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    I believe it is possible for OnTriggerEnter to be called before Start if there is a collider there to trigger it when the gameobject activates. Try moving everything from Start into Awake except for that last if (footHealth < 0) part. If that doesn't work then I'd try setting all those components as serializable fields or setting them to public and make all those component references in the inspector, so they are all established before OnTriggerEnter can be called.
     
  3. Numonic

    Numonic

    Joined:
    Mar 22, 2009
    Posts:
    241

    Hey thanks for the reply I do have those references called on the Awake() method I also have the components as public. I know it has something to do with it being a prefab maybe as well. I took the prefab model into the scene and added the characterStats component on to the inspector and applied it to the prefab by pressing apply. I'll try and make those serializable fields to test it out.
     
  4. Numonic

    Numonic

    Joined:
    Mar 22, 2009
    Posts:
    241
    Hopefully I can be of some help to anyone with this problem I was dealing with.
    I wound up in my awake method for FootDoDamageScript.
    I wound up reference the GameObject and the script together, that seemed to fix it and remove the NullReference I was getting.
    Awake()
    {
    characterStats = GameObject.Find("characterStats").GetComponent<CharacterStats>();
    }