Search Unity

Object reference not set to an instance of an Object C#

Discussion in 'Scripting' started by georetro, Feb 4, 2014.

Thread Status:
Not open for further replies.
  1. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    I forgot to mention I have a Generator and then a button the button is the child of the Generator and the GeneratorCastTrigger is attached to the ButtonObject
     
  2. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    I don't understand what any of that means without more context.

    In the Unity Inspector, Do the gameobjects that GeneratorObject/11/3 reference have a GeneratorCastTrigger/1/2 component attached to them? It can not be on a parent or child of that gameobject.

    EDIT: It sounds like you have attached the components to a child gameobject. GetComponent will not get any components attached to child gameobjects, for that, you want GetComponentInChildren.

    Code (CSharp):
    1.         generatorcasttrigger = GeneratorObject.GetComponentInChildren<GeneratorCastTrigger>();
    2.         generatorcasttrigger1 = GeneratorObjectll.GetComponentInChildren<GeneratorCastTrigger1>();
    3.         generatorcasttrigger2 = GeneratorObject3.GetComponentInChildren<GeneratorCastTrigger2>();
     
  3. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Oh thanks :D

    Edit: I don't think it worked

    and what I meant is that the script is a child of the Door_Script gameobject and the generatorObject
     
  4. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
  5. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    The VariableObject gameobject has the Door_Script and the ButtonObject has the GeneratorCastTrigger
     
  6. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Show the inspector for VariableObject
     
  7. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Unity health inspector.jpg
     
  8. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Here you go
     
  9. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Are you sure that your ButtonObject1 has a "GeneratorCastTrigger2" component, and that your "ButtonObject2" has a "GeneratorCastTrigger1", and that your ButtonObject3 has a "GeneratorCastTrigger"?

    Make sure you have attached the correct script to the correct object. It's looks confusing enough that it would be easy to make a mistake like this (why would a variable called "GeneratorObject3" reference an object called "ButtonObject1" which has a script called "GeneratorCastTrigger2" on it?)
     
  10. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Yes I've triple checked

    Edit: oh oops made a mistake

    Edit: Thank you it worked :D it stressed me out so much!
     
    Last edited: Jul 14, 2020
  11. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    and now the game crashes when I try to interact with the button
     
  12. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    so how do I make it so I can interact with the 3 scripts (acts as a Button) so I can activate all 3 of them
     

    Attached Files:

  13. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Provide the editor log (https://docs.unity3d.com/Manual/LogFiles.html) to help fix crashes.

    This is not really relevant to this thread anymore. You may want to consider posting your new question in a new thread.
     
  14. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    okay thanks for the help
    but what thread tho?
     
  15. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    also it's showing the same message now too "Object reference not set to an instance of an object 51"
    on my interaction script tho
     

    Attached Files:

  16. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Have you tried to debug this yourself? e.g. adding debug statements to see what is null.
     
  17. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Yes But im gonna try this again
     
  18. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    here's the script all three GetComponent isn't working
     

    Attached Files:

  19. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    the interaction Script isn't working
     
  20. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    So...

    What did you discover when you tried debugging the script? e.g. did any of the debug statements get hit? What was the exact error?

    You need to provide more information if you want help with something.
     
  21. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    "NullRefrenceException: Object refrence not set to an instance of an object interact.update() (at Asset/ScriptingFile/interact.cs:20)"
     

    Attached Files:

  22. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    That tells you that whatever your ray hit, it's parent doesn't have a "GeneratorCastTrigger" attached.

    Your next step should be checking to see specifically what object your ray is hitting, and verifying that it's parent has the script you are trying to access.
     
  23. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    How do I do that?
     
  24. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. public class Interact : MonoBehaviour
    5. {
    6.     public float interactDistance = 5f;
    7.  
    8.     void Update()
    9.     {
    10.      if (Input.GetKeyDown(KeyCode.E))
    11.         {
    12.             Ray ray = new Ray(transform.position, transform.forward);
    13.          
    14.             RaycastHit hit;
    15.  
    16.             if (Physics.Raycast (ray, out hit, interactDistance))
    17.             {
    18.                 if (hit.collider.CompareTag("Generator"))
    19.                 {
    20.                     hit.collider.transform.parent.GetComponent<GeneratorCastTrigger>().Restate();
    21.                     Debug.Log("Hit.Collider 1 is working");
    22.  
    23.                     hit.collider.transform.parent.GetComponent<GeneratorCastTrigger2>().Restate();
    24.                     Debug.Log("Hit.Collider 2 is working");
    25.  
    26.                     hit.collider.transform.parent.GetComponent<GeneratorCastTrigger1>().Restate();
    27.                     Debug.Log("Hit.Collider 3 is working");
    28.                 }
    29.             }
    30.              
    31.         }
    32.     }
    33. }
    34.  
    do I add a GetComponenetInChildren
     
  25. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Did you try?

    Try adding GetComponenetInChildren and seeing what happens.

    To find the name of the object the ray is hitting, put it a debug statement:

    Code (CSharp):
    1. Debug.Log(hit.collider.transform)
    Check that that objects parent has the script you are trying to get.
     
  26. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    It doesn't say anything... just says

    "NullRefrenceException: Object refrence not set to an instance of an object interact.update() (at Asset/ScriptingFile/interact.cs:20)"
     
  27. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Where did you put the debug statement? Your posts tend to lack useful details.

    You need to put debug statements everywhere and print everything to find out what is going on. Don't wait for me to tell you where to put them.
     
  28. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Code (CSharp):
    1. public class Interact : MonoBehaviour
    2. {
    3.     public float interactDistance = 5f;
    4.  
    5.     void Update()
    6.     {
    7.      if (Input.GetKeyDown(KeyCode.E))
    8.         {
    9.             Ray ray = new Ray(transform.position, transform.forward);
    10.            
    11.             RaycastHit hit;
    12.  
    13.             if (Physics.Raycast (ray, out hit, interactDistance))
    14.             {
    15.                 if (hit.collider.CompareTag("Generator"))
    16.                 {
    17.                     hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger>().Restate();
    18.                     Debug.Log(hit.collider.transform);
    19.  
    20.                     hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger2>().Restate();
    21.                     Debug.Log(hit.collider.transform);
    22.  
    23.                     hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger1>().Restate();
    24.                     Debug.Log(hit.collider.transform);
    25.                 }
    26.             }
    27.                
    28.         }
    29.     }
    30. }
    31.  
    32. there you go
     
  29. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    How is trying to print the exact same colliders transform 3 times going to be useful in any way?

    Read through your code. First, it detects if you pressed the E key (add a debug statement to verify this works), then it performs a raycast (debug statement to verify that it hit something), then it compares the objects tag (another debug log statement to check what the tag is of the hit object), then it tries to get the GeneratorCastTrigger component of the transforms parent (assign this to a variable, then add another debug statement to verify that it is actually sucessfully getting a script), then it calls Restate() etc etc

    As part of the normal debugging process, your code should end up looking something like this:

    Code (CSharp):
    1. public class Interact : MonoBehaviour
    2. {
    3.     public float interactDistance = 5f;
    4.     void Update()
    5.     {
    6.      if (Input.GetKeyDown(KeyCode.E))
    7.         {
    8.             Debug.Log("Pressed E");
    9.             Ray ray = new Ray(transform.position, transform.forward);
    10.        
    11.             RaycastHit hit;
    12.             if (Physics.Raycast (ray, out hit, interactDistance))
    13.             {
    14.                 Debug.Log("Hit object with tag " + hit.collider.gameObject.tag);
    15.                 if (hit.collider.CompareTag("Generator"))
    16.                 {
    17.                     Debug.Log("parent " + hit.collider.transform.parent);
    18.                     var generator1 = hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger>();
    19.                     Debug.Log("generator1 " + generator1 );
    20.                     generator1 .Restate();
    21.                     // etc
    22.                  
    23.                 }
    24.             }
    25.            
    26.         }
    27.     }
    28. }
    29.  
     
  30. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Same error message
     
  31. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Of course you get the same error message. The point of the above example isn't to fix the bug (it's functionally identical), it's to output useful information to help you track down the bug.
     
  32. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    also heres an image

    The script is in the ButtonObject Component
    UnityComponent.jpg
    I also changed the script
    Code (CSharp):
    1.  void Update()
    2.     {
    3.         if (Input.GetKeyDown(KeyCode.E))
    4.         {
    5.             Debug.Log("Pressed E");
    6.             Ray ray = new Ray(transform.position, transform.forward);
    7.  
    8.             RaycastHit hit;
    9.             if (Physics.Raycast(ray, out hit, interactDistance))
    10.             {
    11.                 if (hit.collider.CompareTag("Generator"))
    12.                 {
    13.                     hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger>().Restate();
    14.                 }
    15.                 if (hit.collider.CompareTag("Generator1"))
    16.                 {
    17.                     hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger1>().ReInitiate();
    18.                 }
    19.                 if (hit.collider.CompareTag("Generator2"))
    20.                 {
    21.                     hit.collider.transform.parent.GetComponentInChildren<GeneratorCastTrigger2>().Recreate();
    22.                 }
    23.             }
    24.         }
    25.     }
    26.  
     
  33. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Use Debug.Log to check what object your ray is hitting, and verify that the children of that objects parent has the GeneratorCastTrigger/1/2 script attached somewhere.
     
  34. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    Turns out the "GetComponentInChildren" Command messes the game up and crashes the game Thank you and sorry to bother you :)
     
  35. deppydep

    deppydep

    Joined:
    Sep 6, 2020
    Posts:
    1
    i got the same problem pls help me here is the script i very new so i need more help

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Numerics;
    using UnityEngine;

    public class Movement : MonoBehaviour
    {
    public float movesp = 10f;
    [SerializeField] private bool isgrounded = false;
    private Animator animator;


    // Start is called before the first frame update
    void Start()
    {
    animator.GetComponent<Animator>();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
    if (other.CompareTag("ground"))
    isgrounded = true;
    }
    private void OnTriggerExit2D(Collider2D other)
    {
    if (other.CompareTag("ground"))
    isgrounded = false;
    }
    // Update is called once per frame

    void Update()
    {
    float m = Input.GetAxis("Horizontal");
    UnityEngine.Vector3 movement = new UnityEngine.Vector3(m, 0, 0);
    transform.position = transform.position + movement * movesp * Time.deltaTime;

    if (Input.GetButtonDown("Jump") && isgrounded == true)
    {
    GetComponent<Rigidbody2D>().AddForce(new UnityEngine.Vector3(0f, 7.5f), ForceMode2D.Impulse);


    }
    if (m != 0)
    {
    animator.SetFloat("speed", 1);
    }
    if (m==0)
    {
    animator.SetFloat("speed", 0);
    }
    }


    }
     
  36. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    you're missing alot of "{}"
    Example
    Code (CSharp):
    1. if (other.CompareTag("ground"))
    2. {
    3. isgrounded = false
    4. }
     
  37. ShiftRapidz

    ShiftRapidz

    Joined:
    Oct 6, 2018
    Posts:
    5
    I am having a similar problem. When I kill and respawn my character the joystick control is disappearing after my character is destroyed.
    Capture.JPG Capture1.JPG .
     
  38. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    The fact that it is bold in the first image tells me that it is a change that has not been applied to the player prefab.

    Apply the change so that the prefab has a reference to the joystick. If you cannot do this (e.g. because your FixedJoystick component exists in the scene and not on the player prefab), then consider another way of fetching a reference to the joystick. For example, you could do something like:

    mj = GameObject.FindObjectOfType<FixedJoystick>();

    in the PlayerMovement's Start function.
     
  39. ShiftRapidz

    ShiftRapidz

    Joined:
    Oct 6, 2018
    Posts:
    5
    Thank you very much
     
  40. ThePrince380610

    ThePrince380610

    Joined:
    Jan 25, 2021
    Posts:
    1
    Hi! I am New to Unity and the I have a problem with my script

    Here is the script:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerController : MonoBehaviour {

    public float speed;
    public float jumpForce;
    public float moveInput;

    private Rigidbody2D rb;

    void start(){
    rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate(){

    moveInput = Input.GetAxis("Horizontal");
    rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
    }

    }


    And here is the error message:

    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.FixedUpdate () (at Assets/PlayerController.cs:20)
     
  41. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    Please don't reply to old posts. It's actually explicitly against forum rules.

    Instead, start your own post.

    For null reference errors, this is literally THE MOST COMMON and THE SIMPLEST ERROR ever.

    The answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    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.

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.
     
  42. cudosmoney

    cudosmoney

    Joined:
    Jun 1, 2021
    Posts:
    1
    thank you LMAOOO
     
  43. grzesko998

    grzesko998

    Joined:
    Jun 20, 2021
    Posts:
    2
    Hey Guys!, i could really use your help, i'm having a problem with my script. Here it is:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class CounterController : MonoBehaviour
    {
    int numberOfBoxes;
    Text counterView;

    // Start is called before the first frame update
    void Start()
    {
    ResetCounter();
    }

    public void IncrementCounter()
    {
    numberOfBoxes++;
    counterView.text = numberOfBoxes.ToString();
    }

    public void ResetCounter()
    {
    numberOfBoxes = 0;
    counterView.text = numberOfBoxes.ToString();
    }
    }

    And this is my error message

    NullReferenceException: Object reference not set to an instance of an object
    CounterController.ResetCounter () (at Assets/CounterController.cs:26)
    CounterController.Start () (at Assets/CounterController.cs:14)
     
  44. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    Please stop replying to posts from 2014 for a simple null reference. Null ref does NOT require a post even.

    Why?

    The answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    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.

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.

    Here is a clean analogy of the actual underlying problem of a null reference exception:

    https://forum.unity.com/threads/nul...n-instance-of-an-object.1108865/#post-7137032
     
  45. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    9,052
    Closing.
    Debugging is critical to any kind of software development. These errors have the line number right in them.
    This thread is several years old and has all the solutions needed for this issue. (Including the post above this one). Read them, follow them. Null refs are a common user error you to learn to solve, not post on the internets looking for help.
     
    Ryiah and Kurt-Dekker like this.
Thread Status:
Not open for further replies.