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. Dismiss Notice

So I need some help with my .GetComponent...

Discussion in 'Scripting' started by Fantom7655, May 6, 2021.

  1. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Health : MonoBehaviour
    6. {
    7.     public int health = 100;
    8.     public GameObject deathEffect;
    9.    
    10.     public string enemyType;
    11.  
    12.     //Getting data test
    13.      public GameObject plusSquid;
    14.  
    15.      private Player playerStats;
    16.  
    17.  
    18.  
    19.  
    20.  
    21.     // Update is called once per frame
    22.     public void TakeDamage(int damage)
    23.     {
    24.         health -= damage;
    25.  
    26.         if(health <= 0)
    27.         {
    28.             Die();
    29.         }
    30.     }
    31.  
    32.     void Die()
    33.     {
    34.          if(enemyType == "Squid")
    35.         {
    36.             KilledSquid();
    37.         }
    38.         else if(enemyType == "Guardian")
    39.         {
    40.             KilledGuardian();
    41.         }
    42.  
    43.  
    44.         playerStats = GetComponent<Player>();
    45.  
    46.         Instantiate(deathEffect, transform.position, transform.rotation);
    47.        
    48.         Destroy(gameObject);
    49.     }
    50.  
    51.     void KilledSquid()
    52.     {  
    53.         playerStats.squidKilled = playerStats.squidKilled + 1;
    54.  
    55.         Debug.Log("You have killed " + playerStats.squidKilled + " Squid!");
    56.     }
    57.     void KilledGuardian()
    58.     {
    59.         playerStats.gaurdiansKilled = playerStats.gaurdiansKilled + 1;
    60.  
    61.         Debug.Log("You have killed " + playerStats.gaurdiansKilled + " Guardians!");
    62.  
    63.         //Yes, I know I misspelled "Guardians" I'm just to lazy to fix the Typo in all the different scripts.
    64.     }
    65.  
    66. }
    67.  
    So I am trying to take the "squidKilled" and "guardiansKilled" Variables from another Script entitled "Player".
    I have the line of code "Private Player playerStats;" to call the script's class. Every time I run the program and kill a squid it gives me this error: NullReferenceException: Object reference not set to an instance of an object. I have no clue what It's talking about. I've checked and everything is in place on the models, aka All the GameObjects are in the right places I intended them to be. So.. I'm kinda lost, I've looked over my script and VS Code isn't giving me any errors. It also says the error occurs on Line 49. Again, VS code isn't giving me an error and Idk what I did wrong.

    I had the script running earlier and all I changed was the name of the Script I'm referencing. my last script just looked like this:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Health : MonoBehaviour
    6. {
    7.     public int health = 100;
    8.     public GameObject deathEffect;
    9.    
    10.     public string enemyType;
    11.  
    12.     //Getting data test
    13.      public GameObject plusSquid;
    14.  
    15.      private Stats stats;
    16.  
    17.  
    18.  
    19.  
    20.  
    21.     // Update is called once per frame
    22.     public void TakeDamage(int damage)
    23.     {
    24.         health -= damage;
    25.  
    26.         if(health <= 0)
    27.         {
    28.             Die();
    29.         }
    30.     }
    31.  
    32.     void Die()
    33.     {
    34.          if(enemyType == "Squid")
    35.         {
    36.             KilledSquid();
    37.         }
    38.         else if(enemyType == "Guardian")
    39.         {
    40.             KilledGuardian();
    41.         }
    42.  
    43.  
    44.         stats = GetComponent<Stats>();
    45.  
    46.         Instantiate(deathEffect, transform.position, transform.rotation);
    47.        
    48.         Destroy(gameObject);
    49.     }
    50.  
    51.     void KilledSquid()
    52.     {  
    53.         stats.squidKilled = stats.squidKilled + 1;
    54.  
    55.         Debug.Log("You have killed " + stats.squidKilled + " Squid!");
    56.     }
    57.     void KilledGuardian()
    58.     {
    59.         stats.gaurdiansKilled = stats.gaurdiansKilled + 1;
    60.  
    61.         Debug.Log("You have killed " + stats.gaurdiansKilled + " Guardians!");
    62.  
    63.         //Yes, I know I misspelled "Guardians" I'm just to lazy to fix the Typo in all the different scripts.
    64.     }
    65.  
    66. }

    Any help is appreciated! :)
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,656
    So the way you've written it, GetComponent will look on itself and try and find the Player script on itself. I assume this script is on the Squids/Guardians, hence why it looks on itself and finds nothing, thus returns null. Trying to access something that's null with throw the error you've found.

    You will need to find some way to link the squids to the player. The most basic is making the field public or put a [SerializedField] attribute on the Player variable, and then put the player's instance of the script in the scene into the field in the inspector.

    ALTERNATIVELY, if you're just passing numbers around, I would always promote the use of scriptable objects for such a purpose. This video explains the beauty of it:
     
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,896
    also this line seems to be called after you tried to access it, inside Die()
    Code (CSharp):
    1. playerStats = GetComponent<Player>();
    *tip: (in visual studio) you can select your gaurdiansKilled variable, press F2, to rename it across whole project. (except from commented lines)
     
  4. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    Thanks a lot! I'm gonna keep on working to fix it and try what you suggested! Thanks again for taking your time to help! :)
     
  5. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    Thanks for the tip, I didn't know that!
     
  6. Omniglitch

    Omniglitch

    Joined:
    May 29, 2017
    Posts:
    37
    The only thing I see in the code provided that would cause a NullReferenceException error is the line that tries to Instantiate the deathEffect. You declared the reference variable on line 8. (It's a reference variable because it stores a reference to a game object rather than a value, like an integer, float, etc.)

    Reference variables start off having a value of null until they're set. You can either set them in code, or in the inspector. Since you code doesn't set deathEffect, then I suspect you meant to set it in the inspector but forgot to.

    Whenever you try to use a reference variable that is still null, you will get a NullReferenceException error, but only at runtime. The compiler will not catch these errors.
     
  7. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    Okay, So I had the solution in front of me the whole time! I had the Player Script on another object but I, being really dumb, never put the gameObject before the .GetComponent. After you made me think of that, I went in and fixed it and BAM, It works like a charm! Thanks again for your help!!!
     
  8. Fantom7655

    Fantom7655

    Joined:
    Oct 13, 2018
    Posts:
    9
    Yeah, I fixed that just a few minutes ago. Thanks for taking the time to share your wisdom! :) It's very appreciated!!!