Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Can't fix error : "NullReferenceException: Object reference not set to an instance of an object"

Discussion in 'Scripting' started by JustaDuck97, Mar 24, 2020.

  1. JustaDuck97

    JustaDuck97

    Joined:
    Jul 31, 2019
    Posts:
    40
    I keep getting the following error on a script for this top down follow enemy:
    NullReferenceException: Object reference not set to an instance of an object
    Trapswan.MovePos (UnityEngine.Vector2 direction) (at Assets/Trapswan.cs:25)
    Trapswan.FixedUpdate () (at Assets/Trapswan.cs:30)


    Here is the related code:

    Code (CSharp):
    1. public class Trapswan : MonoBehaviour
    2. {
    3.     public Transform player;
    4.     private Rigidbody2D rb;
    5.     private Vector2 movement;
    6.     public float moveSpeed = 5f;
    7.     public float SwanHealth = 15f;
    8.    
    9.     void Update()
    10.     {
    11.         Vector3 direction = player.position - transform.position;
    12.         rb = this.GetComponent<Rigidbody2D>();
    13.         float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    14.         rb.rotation = angle;
    15.         movement = direction;
    16.  
    17.     }
    18.  
    19.     void MovePos(Vector2 direction)
    20.     {
    21.         rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime))
    22.         //this is the error causer
    23.     }
    24.  
    25.     void FixedUpdate()
    26.     {
    27.         MovePos(movement);
    28.     }
    29.  
    30.     void OnCollisionEnter(Collision collision)
    31.     {
    32.         if (collision.gameObject.CompareTag("Bullet"))
    33.         {
    34.             damaged();
    35.             Debug.Log("Calling Damaged");
    36.         }
    37.  
    38.     }
    39.  
    40.     void damaged()
    41.     {
    42.         SwanHealth = SwanHealth - 1;
    43.         if(SwanHealth <= 0)
    44.         {
    45.             Destroy(gameObject);
    46.         }
    47.     }
    48. }
    I've looked at other similar issues online and they said the message means that something on the line doesn't exist, but everything on that line does exist.
     
  2. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    388
    Move this
    rb = this.GetComponent<Rigidbody2D>();
    to Start(). You should never use GetComponent() inside of Update. It's very heavy.

    Try doing that and let us know if it helped.
     
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    8,996
    Yeah as @Dextozz said, don't GetComponent every frame like that. Just do it once in Start or set it with an inspector reference. After you do that it should fix the issue.

    You could additionally change MovePos in case you later mess up getting this reference in Start again though.

    Code (csharp):
    1.  
    2.     void MovePos(Vector2 direction)
    3.     {
    4.         if (rb == null)
    5.         {
    6.             Debug.Log("Trapswan.MovePos was called with rb null, setting rb");
    7.             rb = GetComponent<Rigidbody2D>();
    8.         }
    9.         rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime))
    10.         //this is the error causer
    11.     }
    12.  
     
  4. JustaDuck97

    JustaDuck97

    Joined:
    Jul 31, 2019
    Posts:
    40
    I made this post a few days ago and have sense written completely new code to replace this one. I learned in the few days between now and this original post that putting GetCompnent() inside of Update is a BIG NO NO
     
  5. astracat111

    astracat111

    Joined:
    Sep 21, 2016
    Posts:
    626
    When you're making a method, it's common to have this:

    Code (CSharp):
    1. private void MyMethod() {
    2.     if (myComponent == null)
    3.        return;
    4.  
    5.     //My code goes here.
    6. }
    To check if the component is null, that's if the value isn't necessarily always going to equal something.
     
  6. MakerAz

    MakerAz

    Joined:
    Dec 16, 2015
    Posts:
    4
    Hello!

    Please help.

    Unity throws the following error:
    NullReferenceException: Object reference not set to an instance of an object
    Game_CNT+<ScoreUpdater>c__Iterator4.MoveNext () (at Assets/Scripts/Game_CNT.cs:499)
    UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

    I have 2 game objects in a scene:
    1) Game_CNT
    2) MP_Scripts

    Game_CNT game object has "Game_CNT" script attached to it.
    MP_Scripts game object has "MarketingScripts" script attached to it

    When I call a method of the "MarketingScripts" from the "Game_CNT" it throws the error above.

    Game_CNT:
    Code (CSharp):
    1. public class Game_CNT : MonoBehaviour
    2. {
    3.  
    4. GameObject MP_Scripts; // Get Reference of MP_Scripts
    5.  
    6. void ShowVideoAd()
    7. {
    8. MP_Scripts.GetComponent<MarketingScripts>().ShowUnityAdVideo(); // This one is in line 499
    9. }
    10.  
    11. }

    MarketingScripts:
    Code (CSharp):
    1. public class MarketingScripts : MonoBehaviour
    2. {
    3.  
    4.   string gameID = "123456";
    5.  
    6.     void Start()
    7.     {
    8.         Advertisement.Initialize(gameID, true); // Initializing Unity Ads
    9.     }
    10.  
    11.  
    12. public void ShowUnityAdVideo() //To show Simple Skippable Video Ads
    13.     {
    14.         if (Advertisement.IsReady("video"))
    15.             Advertisement.Show("video");
    16.         else return;
    17.     }
    18.  
    19. }
    What am I missing here?
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    8,455
    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.
     
  8. MakerAz

    MakerAz

    Joined:
    Dec 16, 2015
    Posts:
    4
    Fixed it by just creating a new MarketingScripts class variable.
    There is actually no need to reference MP_Scripts GameObject.

    Game_CNT modified as below:
    Code (CSharp):
    1.         //Show Simple Skippable Unity Video Ad
    2.  
    3.         MarketingScripts mpScript = new MarketingScripts();
    4.         mpScript.ShowUnityAdVideo();
     
unityunity