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. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    Usually the error tells you exactly what line the problem is on. So without seeing the error itself, I'm guessing the GameObject.FindGameObjectWithTag is failing to find the player, leaving target null. Add a Debug.Log or Debug.Assert to ensure the target actually exists.
     
  2. zumbeemods

    zumbeemods

    Joined:
    Sep 26, 2018
    Posts:
    2
    It seems to indicate that it's on line 15, I'm not sure about that but it says this exactly: NullReferenceException: Object reference not set to an instance of an object FollowAI.Update () (at Assets/FollowAI.cs:15) EDIT: I'm so dumb, the tag for the player was for some reason never set.
     
    Last edited: Sep 27, 2018
  3. BrianMecha

    BrianMecha

    Joined:
    Oct 10, 2018
    Posts:
    4
    I'm having the same problem. I have an audio file and score display that was working before and not working now likely because it's saying "Object reference not set to an instance of an object." I added some tags to my blocks to differentiate between Breakable and Unbreakable blocks. That works fine, and the breakable blocks even disappear as they're supposed to. But they're not making the destruction sound anymore and the blocks that are being destroyed aren't being counted. Here are the two files I'm using.

    Blocks.cs - the issue is the method at the bottom called PlayBlockDestroySFX

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Block : MonoBehaviour {
    6.  
    7.     [SerializeField] AudioClip breakSound;
    8.     //[SerializeField] int hitPoints;
    9.  
    10.     //Cached Reference
    11.     Level level;
    12.  
    13.     //State Variables
    14.     //int timesHit;
    15.  
    16.  
    17.     private void Start()
    18.     {
    19.         CountBlocks();  
    20.     }
    21.  
    22.     private void CountBlocks()
    23.     {
    24.         level = FindObjectOfType<Level>();
    25.         if (tag == "Breakable")
    26.         {
    27.             level.CountBreakableBlocks(); //call method in level script to count blocks
    28.         }
    29.     }
    30.  
    31.  
    32.     private void OnCollisionEnter2D(Collision2D collision)
    33.     {
    34.         if (tag == "Breakable")
    35.         {
    36.             //timesHit++;
    37.             DestroyBlock();
    38.         }  
    39.     }
    40.  
    41.     private void DestroyBlock()
    42.     {
    43.         Destroy (gameObject);
    44.         PlayBlockDestroySFX();
    45.         level.BlockDestroyed();
    46.  
    47.     }
    48.  
    49.     private void PlayBlockDestroySFX()
    50.     {
    51.         FindObjectOfType<GameStatus>().AddToScore();
    52.         AudioSource.PlayClipAtPoint(breakSound, Camera.main.transform.position);
    53.     }

    GameStatus.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5.  
    6. public class GameStatus : MonoBehaviour {
    7.  
    8.     //Parameters
    9.     [SerializeField] int pointsPerBlockDestroyed = 10;
    10.     [SerializeField] TextMeshProUGUI scoreText;
    11.  
    12.     //State Variables
    13.     [SerializeField] int currentScore = 0; //set initial score to 0
    14.  
    15.     private void Awake()
    16.     {
    17.         int gameStatusCount = FindObjectsOfType<GameStatus>().Length;
    18.         if (gameStatusCount > 1)
    19.         {
    20.             Destroy(gameObject);
    21.         }
    22.         else
    23.         {
    24.             DontDestroyOnLoad(gameObject);  
    25.         }  
    26.     }
    27.  
    28.     // Use this for initialization
    29.     void Start ()
    30.     {
    31.         scoreText.text = currentScore.ToString();
    32.      
    33.     }
    34.  
    35.     // Update is called once per frame
    36.     void Update () {
    37.      
    38.     }
    39.  
    40.     public void AddToScore()
    41.     {
    42.         currentScore = currentScore + pointsPerBlockDestroyed;
    43.         scoreText.text = currentScore.ToString();
    44.  
    45.     }
    46.  
    47.     public void ResetGame()
    48.     {
    49.         Destroy(gameObject);
    50.  
    51.     }
    52. }
     
  4. BrianMecha

    BrianMecha

    Joined:
    Oct 10, 2018
    Posts:
    4
    Nevermind, I figured out what the problem was because I have two scenes and I was wondering why it was working on one scene and not the other...so I realized it wasn't the code. Somehow GameStatus.cs got deleted in Scene 1 from the Hierarchy. Luckily, it was Prefab'd, so I was able to just drag it back over LOL
     
  5. laraibmansha11

    laraibmansha11

    Joined:
    Sep 20, 2018
    Posts:
    2
    plzz!! tell me how to change script this problem of NULL Reference?
     
  6. laraibmansha11

    laraibmansha11

    Joined:
    Sep 20, 2018
    Posts:
    2
     
  7. NaturalSalt

    NaturalSalt

    Joined:
    Nov 11, 2018
    Posts:
    2
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class enemyFollowscript : MonoBehaviour
    6. {
    7.  
    8.     public float speed;
    9.     private Transform Target;
    10.  
    11.  
    12.  
    13.     void start()
    14.     {
    15.         Target = GameObject.FindGameObjectWithTag("Player").transform;
    16.     }
    17.  
    18.     void Update()
    19.     {
    20.         transform.position = Vector2.MoveTowards(transform.position, Target.position, speed * Time.deltaTime);
    21.     }
    22. }
    it works if i change private transform to public.
    but i need it in private
     
  8. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    "start" needs a capitalized s, so it should be:

    Code (CSharp):
    1.     void Start()
    2.     {
    3.         Target = GameObject.FindGameObjectWithTag("Player").transform;
    4.     }
     
  9. NaturalSalt

    NaturalSalt

    Joined:
    Nov 11, 2018
    Posts:
    2
    Thanks!!!
     
  10. greatangelboy

    greatangelboy

    Joined:
    Dec 14, 2018
    Posts:
    1
    I'm trying to make a simple version of Space Invaders. I've been trying to create a point system, and Unity throws me this error "NullReferenceException: Object reference not set to an instance of an object
    ShotController.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/ShotController.cs:37)
    ". My code is as follows

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ShotController : MonoBehaviour {
    6.  
    7.     PointSystemController pointsystem;
    8.     Rigidbody2D sRigidbody2D;
    9.     public float speed = 10;
    10.  
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         sRigidbody2D = this.GetComponent<Rigidbody2D>();
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void FixedUpdate ()
    19.     {
    20.         sRigidbody2D.velocity = new Vector2(0, speed);
    21.  
    22.         Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
    23.  
    24.         if (screenPos.y > Screen.height && screenPos.y < 0)
    25.         {
    26.             Destroy(this.gameObject);
    27.             pointsystem.RemovePoint();
    28.         }
    29.     }
    30.  
    31.     private void OnTriggerEnter2D(Collider2D collision)
    32.     {
    33.         if ( collision.gameObject.tag == "Enemy" )
    34.         {
    35.             Destroy(collision.gameObject);
    36.             Destroy(this.gameObject);
    37.             pointsystem.AddPoint();
    38.         }
    39.     }
    40. }
    41.  
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6.  
    7. public class PointSystemController : MonoBehaviour {
    8.     public int playerScore;
    9.     public int highScore = 0;
    10.     public Text PlayerScore;
    11.     public Text HighScore;
    12.  
    13.     // Use this for initialization
    14.     void Start()
    15.     {
    16.         playerScore = 0;
    17.         HighScore.text = "HighScore: " + highScore.ToString();
    18.         UpdateScore();
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.  
    25.     }
    26.  
    27.     public void AddPoint()
    28.     {
    29.         playerScore = playerScore + 1;
    30.         UpdateScore();
    31.     }
    32.     public void RemovePoint()
    33.     {
    34.         playerScore = playerScore - 3;
    35.         UpdateScore();
    36.     }
    37.     void UpdateScore()
    38.     {
    39.         if (playerScore > highScore)
    40.         {
    41.             PlayerScore.text = " Player Score: " + playerScore.ToString();
    42.             HighScore.text = "HighScore: " + highScore.ToString();
    43.         }
    44.         else
    45.         {
    46.             PlayerScore.text = " Player Score: " + playerScore.ToString();
    47.         }
    48.     }
    49. }
    50.  
    anyone able to see what causing this error, and possibly how I can fix it? It's supposed to add 1 point to the playerScore when there is a collision; an enemy is hit by a shot.
     
    Last edited: Dec 14, 2018
  11. Lgia

    Lgia

    Joined:
    Jan 6, 2019
    Posts:
    1
    Hello guys I'm having the same error in my test for input and color changes, here is my script :
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ObjectColor : MonoBehaviour
    6. {
    7.     public Color changedColor = Color.white;
    8.     public Color originalColor = Color.black;
    9.     Renderer rend;
    10.    
    11.     void Awake ()
    12.     {
    13.         originalColor = this.rend.material.color;
    14.         Debug.Log ("color is: " + originalColor);
    15.     }
    16.    
    17.     void Update ()
    18.     {
    19.         if (Input.GetKeyDown (KeyCode.G))
    20.         {
    21.             this.rend.material.color = changedColor;
    22.        
    23.         }
    24.         else if (Input.GetKeyUp (KeyCode.G))
    25.         {
    26.             this.rend.material.color = originalColor;
    27.         }
    28.     }
    29. }
    30.  

    I don't see where this can come from :/
    It says the error is on line 13
     

    Attached Files:

    Last edited: Jan 6, 2019
  12. Sterile_D

    Sterile_D

    Joined:
    Apr 6, 2015
    Posts:
    16
    Any help would be grand.

    I am getting this error:


    NullReferenceException: Object reference not set to an instance of an object
    NPCController.Awake () (at Assets/Scripts/NPCController.cs:24)

    Here is what that script looks like:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5. public class NPCController : MonoBehaviour
    6. {
    7.     public float patrolTime = 10f;
    8.     public float aggroRange = 10f;
    9.     public Transform[] waypoints;
    10.     private int index;
    11.     private float speed, agentSpeed;
    12.     private Transform player;
    13.     //private Animator anim;
    14.     private NavMeshAgent agent;
    15.     private void Awake()
    16.     {
    17.         //anim = GetComponent<Animator>();
    18.         agent = GetComponent<NavMeshAgent>();
    19.         if (agent != null) { agentSpeed = agent.speed; }
    20.         player = GameObject.FindGameObjectWithTag("Player").transform;
    21.         index = Random.Range(0, waypoints.Length);
    22.         InvokeRepeating("Tick", 0, 0.5f);
    23.         if (waypoints.Length > 0)
    24.         {
    25.             InvokeRepeating("Patrol", 0, patrolTime);
    26.         }
    27.     }
    28.     void Patrol()
    29.     {
    30.         index = index == waypoints.Length - 1 ? 0 : index + 1;
    31.     }
    32.     void Tick()
    33.     {
    34.         agent.destination = waypoints[index].position;
    35.     }
    36. }
     
  13. In the future, please do not duplicate your posts. I already answered you at your other post. Also please don't hijack other people's thread unless you have the same and exact problem. Which you didn't. So opening your own thread and waiting on the answer is the right move.
     
    VGGD and Ryiah like this.
  14. TheLEGOGamer_

    TheLEGOGamer_

    Joined:
    Aug 6, 2018
    Posts:
    1
    I keep getting "Object not Set to an Instance of an object on line 34 of this code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player_Movement : MonoBehaviour
    6. {
    7.  
    8.     public float speed = 6.0f;
    9.     public float gravity = -9.8f;
    10.  
    11.     private CharacterController _charCont;
    12.  
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.  
    17.         _charCont = GetComponent<CharacterController>();
    18.  
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.  
    25.         float deltaX = Input.GetAxis("LeftRight") * speed;
    26.         float deltaZ = Input.GetAxis("UpDown") * speed;
    27.         Vector3 movement = new Vector3(deltaX, 0, deltaZ);
    28.         movement = Vector3.ClampMagnitude(movement, speed);
    29.  
    30.         movement.y = gravity;
    31.  
    32.         movement *= Time.deltaTime;
    33.         movement = transform.TransformDirection(movement);
    34.         _charCont.Move(movement);
    35.  
    36.     }
    37. }
    38.  
    Also FYI: I did change Horizontal and Vertical to LeftRight & UpDown.
     
  15. FasoleWarrior

    FasoleWarrior

    Joined:
    Mar 16, 2019
    Posts:
    1
    i have the same problem, please tell me what to do.

    the message:
    NullReferenceException: Object reference not set to an instance of an object
    PlayerMovement.FixedUpdate () (at Assets/PlayerMovement.cs:39)
     

    Attached Files:

  16. SeriousPooh

    SeriousPooh

    Joined:
    Mar 25, 2019
    Posts:
    2
    Error message appeared

    " NullReferenceException: Object reference not set to an instance of an object PointClickMovement.Update () (at Assets/Scripts/PointClickMovement.cs:43)"

    I'm trying to instruct the player move according to user's mouse click, appreciate if somebody can advise.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(CharacterController))]
    6. public class PointClickMovement : MonoBehaviour
    7. {
    8.     [SerializeField] private Transform target;
    9.  
    10.     public float moveSpeed = 6.0f;
    11.     public float rotSpeed = 15.0f;
    12.     public float jumpSpeed = 15.0f;
    13.     public float gravity = -9.8f;
    14.     public float terminalVelocity = -20.0f;
    15.     public float minFall = -1.5f;
    16.     public float pushForce = 3.0f;
    17.  
    18.     public float deceleration = 25.0f;
    19.     public float targetBuffer = 1.5f;
    20.     private float _curSpeed = 0f;
    21.     private Vector3 _targetPos = Vector3.one;
    22.  
    23.     private float _vertSpeed;
    24.     private ControllerColliderHit _contact;
    25.  
    26.     private CharacterController _charController;
    27.     private Animator _animator;
    28.  
    29.     void Start()
    30.     {
    31.         _vertSpeed = minFall;
    32.  
    33.         _charController = GetComponent<CharacterController>();
    34.         _animator = GetComponent<Animator>();
    35.     }
    36.  
    37.     void Update()
    38.     {
    39.         Vector3 movement = Vector3.zero;
    40.  
    41.         if (Input.GetMouseButton(0))
    42.         {
    43.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    44.             RaycastHit mouseHit;
    45.             if (Physics.Raycast(ray, out mouseHit))
    46.             {
    47.                 _targetPos = mouseHit.point;
    48.                 _curSpeed = moveSpeed;
    49.             }
    50.         }
    51.  
    52.         if (_targetPos != Vector3.one)
    53.         {
    54.             if (_curSpeed > moveSpeed * .5f)
    55.             {
    56.                 Vector3 adjustedPos = new Vector3(_targetPos.x, transform.position.y, _targetPos.z);
    57.                 Quaternion targetRot = Quaternion.LookRotation(adjustedPos - transform.position);
    58.                 transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, rotSpeed * Time.deltaTime);
    59.             }
    60.  
    61.             movement = _curSpeed * Vector3.forward;
    62.             movement = transform.TransformDirection(movement);
    63.  
    64.             if (Vector3.Distance(_targetPos, transform.position) < targetBuffer)
    65.             {
    66.                 _curSpeed -= deceleration * Time.deltaTime;
    67.                 if (_curSpeed <= 0)
    68.                 {
    69.                     _targetPos = Vector3.one;
    70.                 }
    71.             }
    72.         }
    73.         _animator.SetFloat("Speed", movement.sqrMagnitude);
    74.  
    75.         bool hitGround = false;
    76.         RaycastHit hit;
    77.         if (_vertSpeed < 0 && Physics.Raycast(transform.position, Vector3.down, out hit))
    78.         {
    79.             float check = (_charController.height + _charController.radius) / 1.9f;
    80.             hitGround = hit.distance <= check;
    81.         }
    82.  
    83.         if (hitGround)
    84.         {
    85.             //if (Input.GetButtonDown("Jump"))
    86.             //{
    87.             //    _vertSpeed = jumpSpeed;
    88.             //}
    89.             //else
    90.             //{
    91.                 _vertSpeed = minFall;
    92.                 _animator.SetBool("Jumping", false);
    93.             //}
    94.         }
    95.         else
    96.         {
    97.             _vertSpeed += gravity * 0.9f * Time.deltaTime;
    98.             if (_vertSpeed < terminalVelocity)
    99.             {
    100.                 _vertSpeed = terminalVelocity;
    101.             }
    102.             if (_contact != null)
    103.             {
    104.                 _animator.SetBool("Jumping", true);
    105.             }
    106.  
    107.             if (_charController.isGrounded)
    108.             {
    109.                 if (Vector3.Dot(movement, _contact.normal) < 0)
    110.                 {
    111.                     movement = _contact.normal * moveSpeed;
    112.                 }
    113.                 else
    114.                 {
    115.                     movement += _contact.normal * moveSpeed;
    116.                 }
    117.             }
    118.         }
    119.         movement.y = _vertSpeed;
    120.  
    121.         movement *= Time.deltaTime;
    122.         _charController.Move(movement);
    123.     }
    124.  
    125.     void OnControllerColliderHit(ControllerColliderHit hit)
    126.     {
    127.         _contact = hit;
    128.  
    129.         Rigidbody body = hit.collider.attachedRigidbody;
    130.         if (body != null && !body.isKinematic)
    131.         {
    132.             body.velocity = hit.moveDirection * pushForce;
    133.         }
    134.     }
    135. }
     
  17. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Your main camera is probably either disabled, or not tagged "MainCamera".
     
  18. SeriousPooh

    SeriousPooh

    Joined:
    Mar 25, 2019
    Posts:
    2
    Hi thanks for your guidance, thing resolved by Camera > Inspector > Tag > select “MainCamera”
     
    Last edited: Apr 6, 2019
  19. WorldRock

    WorldRock

    Joined:
    Jul 23, 2019
    Posts:
    1
    I am new to Unity and was creating a hazard script, but it keeps on saying:
    NullReferenceException: Object reference not set to an instance of an object
    Hazard.SomethingIsTouching (UnityEngine.GameObject ThingColliding) (at Assets/Assets/Scripts/Hazard.cs:31)
    Hazard.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Assets/Scripts/Hazard.cs:19)

    My script is:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class Hazard : MonoBehaviour
    {
    // Start is called before the first frame update
    private void SomethingIsTouching(GameObject ThingColliding)
    {
    if (ThingColliding.tag == "Player")
    {
    int lives = --FindObjectOfType<GameVars>().currentLives;
    GameObject text = GameObject.FindGameObjectWithTag("LivesText");
    text.GetComponent<NumberText>().NumUpdate(lives);
    Destroy(ThingColliding);
    }
    }


    private void OnCollisionEnter2D(Collision2D collision)
    {
    SomethingIsTouching(collision.gameObject);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
    SomethingIsTouching(collision.gameObject);
    }




    }
     
  20. ArshidaGames

    ArshidaGames

    Joined:
    Feb 9, 2019
    Posts:
    93
    Code (CSharp):
    1.         HighScore = GameObject.FindGameObjectWithTag("GameCoins").GetComponent<Text>();
    2.  
    For me it does not working.

    my ui text is in the child of another gameobject.
    i attached above script to another empty game manager and i try to reference that ui text but it does not show it in the inspector.
    what is wrong? i am using unity 2019 version.
    my ui text is child of a ui image which at the beginning of the game is inactive.
    someone help me please.
     
  21. sullaysur

    sullaysur

    Joined:
    Dec 26, 2018
    Posts:
    8
    Hey,

    I have this issue in my Resolution Settings.

    Here is the Code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using System.IO;
    6. using TMPro;
    7. using UnityEngine.UI;
    8.  
    9. public class Settings_Manager : MonoBehaviour{
    10.  
    11.     #region Attributes
    12.  
    13.     [SerializeField]
    14.     private Text resolutionText;
    15.  
    16.     private Resolution[] resolutions;
    17.     private int currentResolutionIndex = 0;
    18.  
    19.     private const string RESOLUTION_PREF_KEY = "Resolution";
    20.  
    21.     #endregion
    22.  
    23.     void Start(){
    24.  
    25.         Resolution[] resolutions = Screen.resolutions;
    26.  
    27.         currentResolutionIndex = PlayerPrefs.GetInt(RESOLUTION_PREF_KEY, 0);
    28.  
    29.         resolutionText.text = Screen.currentResolution.width + "x" + Screen.currentResolution.height + "@" + Screen.currentResolution.refreshRate;
    30.     }
    31.  
    32.     #region Resolution
    33.     private void SetResolutionText(Resolution resolution){
    34.         resolutionText.text = resolution.width + "x" + resolution.height + "@" + resolution.refreshRate;
    35.     }
    36.     public void SetNextResolution(){
    37.         currentResolutionIndex = GetNextWrappedIndex(resolutions, currentResolutionIndex);
    38.         SetResolutionText(resolutions[currentResolutionIndex]);
    39.     }
    40.  
    41.     public void SetPreviousResolution()
    42.     {
    43.         currentResolutionIndex = GetPreviousWrappedIndex(resolutions, currentResolutionIndex);
    44.         SetResolutionText(resolutions[currentResolutionIndex]);
    45.     }
    46.  
    47.     private int GetNextWrappedIndex<T>(IList<T> collection, int currentIndex){
    48.         if (collection.Count < 1) return 0;
    49.         return (currentIndex + 1) % collection.Count;
    50.     }
    51.  
    52.     private int GetPreviousWrappedIndex<T>(IList<T> collection, int currentIndex){
    53.         if (collection.Count < 1) return 0;
    54.         if ((currentIndex - 1) < 0) return collection.Count - 1;
    55.         return (currentIndex - 1) % collection.Count;
    56.     }
    57.  
    58.     private void SetAndApplyResolution(int newResolutionIndex){
    59.         currentResolutionIndex = newResolutionIndex;
    60.         ApplyCurrentResolution();
    61.     }
    62.  
    63.     private void ApplyCurrentResolution(){
    64.         ApplyResolution(resolutions[currentResolutionIndex]);
    65.     }
    66.  
    67.     private void ApplyResolution(Resolution resolution){
    68.         SetResolutionText(resolution);
    69.  
    70.         Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen, Screen.currentResolution.refreshRate);
    71.         PlayerPrefs.SetInt(RESOLUTION_PREF_KEY, currentResolutionIndex);
    72.     }
    73.  
    74.     #endregion
    75.  
    76.     public void ApplyChanges(){
    77.         SetAndApplyResolution(currentResolutionIndex);
    78.     }
    79. }
    80.  
    An the 3 Errors

    NullReferenceException: Object reference not set to an instance of an object
    Settings_Manager.GetNextWrappedIndex[T] (System.Collections.Generic.IList`1[T] collection, System.Int32 currentIndex)



    NullReferenceException: Object reference not set to an instance of an object
    Settings_Manager.GetNextWrappedIndex[T] (System.Collections.Generic.IList`1[T] collection, System.Int32 currentIndex)



    NullReferenceException: Object reference not set to an instance of an object
    Settings_Manager.ApplyCurrentResolution ()
     
  22. credits

    credits

    Joined:
    Sep 10, 2019
    Posts:
    1
    i'm getting the same error on line 33 of the unity standard assets head bob script:

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityStandardAssets.Utility;
    4.  
    5. namespace UnityStandardAssets.Characters.FirstPerson
    6. {
    7.     public class HeadBob : MonoBehaviour
    8.     {
    9.         public Camera Camera;
    10.         public CurveControlledBob motionBob = new CurveControlledBob();
    11.         public LerpControlledBob jumpAndLandingBob = new LerpControlledBob();
    12.         public RigidbodyFirstPersonController rigidbodyFirstPersonController;
    13.         public float StrideInterval;
    14.         [Range(0f, 1f)] public float RunningStrideLengthen;
    15.  
    16.        // private CameraRefocus m_CameraRefocus;
    17.         private bool m_PreviouslyGrounded;
    18.         private Vector3 m_OriginalCameraPosition;
    19.  
    20.  
    21.         private void Start()
    22.         {
    23.             motionBob.Setup(Camera, StrideInterval);
    24.             m_OriginalCameraPosition = Camera.transform.localPosition;
    25.        //     m_CameraRefocus = new CameraRefocus(Camera, transform.root.transform, Camera.transform.localPosition);
    26.         }
    27.  
    28.  
    29.         private void Update()
    30.         {
    31.           //  m_CameraRefocus.GetFocusPoint();
    32.             Vector3 newCameraPosition;
    33.             if (rigidbodyFirstPersonController.Velocity.magnitude > 0 && rigidbodyFirstPersonController.Grounded)
    34.             {
    35.                 Camera.transform.localPosition = motionBob.DoHeadBob(rigidbodyFirstPersonController.Velocity.magnitude*(rigidbodyFirstPersonController.Running ? RunningStrideLengthen : 1f));
    36.                 newCameraPosition = Camera.transform.localPosition;
    37.                 newCameraPosition.y = Camera.transform.localPosition.y - jumpAndLandingBob.Offset();
    38.             }
    39.             else
    40.             {
    41.                 newCameraPosition = Camera.transform.localPosition;
    42.                 newCameraPosition.y = m_OriginalCameraPosition.y - jumpAndLandingBob.Offset();
    43.             }
    44.             Camera.transform.localPosition = newCameraPosition;
    45.  
    46.             if (!m_PreviouslyGrounded && rigidbodyFirstPersonController.Grounded)
    47.             {
    48.                 StartCoroutine(jumpAndLandingBob.DoBobCycle());
    49.             }
    50.  
    51.             m_PreviouslyGrounded = rigidbodyFirstPersonController.Grounded;
    52.           //  m_CameraRefocus.SetFocusPoint();
    53.         }
    54.     }
    55. }
    56.  
     
  23. unknownsk

    unknownsk

    Joined:
    Jan 16, 2020
    Posts:
    36
    Pls help me too reply me and i will send you my info about my unity project i have same error :(
     
  24. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Stop posting this comment on other threads. Make a new thread, describe your problem, post your code (with code tags), copy and paste the error message you're getting. Literally no one will help you when you make comment replies like this.
     
  25. adeight

    adeight

    Joined:
    Jan 10, 2020
    Posts:
    8
    I finally solved:
    I have 2 scripts: GameManager, Player. I need to call some method from GameManager in Player and vice versa.
    GameManager is a GameObject that has GameManager script.
    Player is prefab with Player script.
    First EDIT Player tag to Player.
    Note: Find("GameManager"), in Find or FindGameObjectWithTag we have to write exactly the same name of the gameobject that script is attached
    in Player.cs:
    GameManager gm ;
    gm = GameObject.Find("GameManager").GetComponent<GameManager>();
    //then do whatever you want with gm

    in GameManager.cs:
    Player player;
    player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
     
  26. Oka043

    Oka043

    Joined:
    Feb 24, 2020
    Posts:
    1


    Do you find the answer? I have the same problem now
     
  27. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Make sure your main camera is tagged "Main"
     
  28. Brogan89

    Brogan89

    Joined:
    Jul 10, 2014
    Posts:
    244
    Holy S*** that was long time ago. But yea it looks like it would've been because I didn't have the Camera tagged as "Main Camera"
     
  29. MoxieMan

    MoxieMan

    Joined:
    Mar 22, 2020
    Posts:
    1
    hey i'm getting the same error, I would greatly appreciate if someone could tell me what i could do.
    public class New : MonoBehaviour
    {
    public float[] distance = new float[14];
    public float ShortestDistance = 9999;
    public float CubeNumber = 3;
    public float startTime;
    public float checkDelay;
    private Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
    rb = GetComponent<Rigidbody>();
    }
    public int speed = 10;
    // Update is called once per frame
    void Update()
    {
    InvokeRepeating("FindDistances", startTime, checkDelay);
    transform.LookAt(GameObject.Find($"Cube ({CubeNumber})").transform);
    transform.position += transform.forward * 1f * Time.deltaTime;
    Debug.Log($"Cube {CubeNumber} is the closest cube");
    }
    void FindDistances()
    {
    for (int i = 9; i < 13; i++)
    {
    distance = Vector3.Distance(transform.position, GameObject.Find($"Cube ({i})").transform.position);
    Debug.Log("cube " + i + "has distance of " + distance);
    }
    for (int i = 9; i < 13; i++)
    {
    if (distance < ShortestDistance)
    {
    ShortestDistance = distance;
    CubeNumber = i;
    Debug.Log("CUBE " + i + "IS THE CLOSEST CUBE");
    Debug.Log("the shortest distance is " + ShortestDistance);
    }
    }

    Debug.Log("the shortest distance is " + ShortestDistance);
    Debug.Log($"Cube {CubeNumber} is the closest cube");
    }
    }
     
  30. Brogan89

    Brogan89

    Joined:
    Jul 10, 2014
    Posts:
    244
    Its impossible to tell from that code. There is a lot of places it could be happening.
    NullReferenceException is probably the most common error you will encounter in Unity development so it will be good practice to figure out a process that works well for you.

    A process you could to take is:
    1. Find which line is causing the null error.
    2. find out which object is null in that line - you can do this in a couple of ways but the simplistic is to log our all the objects in that line. don't worry about structs as they can never be null. e.g `Debug.Log($is this null: {myObject == null})`
    3. Then find out why its null. There could be many reasons for it...

    I would start with the GameObject.Find() instances as GameObject.Find() may not be finding the object in your scene.

    On a side note. Don't call `InvokeRepeating` in the update function. For one, the function your are wanting to invoke is not returning an IEnumerator. And two its redundant because you are calling every frame rather than the delay time you are supplying. Call it from Start().
     
  31. kondik0405

    kondik0405

    Joined:
    Mar 23, 2020
    Posts:
    1
    Hello, I also have problems on line 26. Anybody help me?

    NullReferenceException: Object reference not set to an instance of an object
    Game.Update () (at Assets/Game.cs:26)


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

    public class Game : MonoBehaviour
    {

    public Text scoreText;
    public float currentScore;
    public float hitPower;
    public float scoreIncreasedPerSecond;
    public float x;

    public int shop1prize;
    public Text shop1text;

    public int shop2prize;
    public Text shop2text;

    public Text amount1text;
    public int amount1;
    public float amount1profit;

    public Text amount2text;
    public int amount2; <This one
    public float amount2profit;
    // Start is called before the first frame update
    void Start()
    {
    currentScore = 0;
    hitPower = 1;
    scoreIncreasedPerSecond = 1;
    x = 0f;
    }

    // Update is called once per frame
    void Update()
    {
    scoreText.text = (int)currentScore+" $";
    scoreIncreasedPerSecond = x * Time.deltaTime;
    currentScore = currentScore + scoreIncreasedPerSecond;

    shop1text.text = "Niewolnik Krzysiu: "+shop1prize+" $";
    shop2text.text = "Niewolnik Bob: "+shop2prize+" $";

    amount1text.text = "Niewolnik Krzysiu: "+amount1+" arts $"+amount1profit+"/s";
    amount2text.text = "Niewolnik Bob: "+amount2+" arts $"+amount2profit+"/s";


    }

    public void Hit()
    {
    currentScore += hitPower;
    }
    }
     
  32. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Int's can't be null, so there must be something else going on. Perhaps you have 2 different scripts called "Game"? Post the script using code tags.
     
  33. Kiffolisk

    Kiffolisk

    Joined:
    Apr 17, 2020
    Posts:
    4
    I'm having this problem with an InputField script.
    Here's the code:
    using UnityEngine.SceneManagement;
    using UnityEngine;
    using UnityEngine.UI;

    public class LevelSelect : MonoBehaviour
    {

    public string cool;
    public GameObject input;

    public void LoadScene()
    {
    SceneManager.LoadScene(cool);
    }

    public void StoreName()
    {
    cool = input.GetComponent<InputField>().text;
    LoadScene();
    }
    }
     
  34. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Don't tack a comment onto an old post just because it came up in your Google search. Post a new thread, and put your code in code tags. Also copy and paste the full error message.

    And if you DO reply to an old thread, read the thread at least. Your problem is gonna be the same as everyone else's: you haven't assigned anything to "input" or it doesn't have an InputField component attached.
     
  35. Krepze_Vondola

    Krepze_Vondola

    Joined:
    Apr 30, 2020
    Posts:
    2
    HEY, i have the same problem and solve it. check if you put the tag of your camera to main camera.
     
  36. Krepze_Vondola

    Krepze_Vondola

    Joined:
    Apr 30, 2020
    Posts:
    2
    whats the value of your speed?
     
  37. zeropointblack

    zeropointblack

    Joined:
    Jun 8, 2020
    Posts:
    197
    same deal. trying to get a light to toggle on off for DAYS now. reference null exception error.

    using EXACT copy pasted code from the unity tutorial found here (and dozens of different ones)

    https://learn.unity.com/tutorial/enabling-and-disabling-components

    WORKS if I start a new project (in HDRP) no problem.
    does NOT work in my current project (converted from 3D to HDRP, if that matters??)

    WHAT is going on? there is NOTHING wrong here. same EXACT procedure across both old and new projects, but simply does not work. What could be the problem? Honestly, is this a bug or not.
     
  38. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Did you add the script to the exact same game object as the light?
     
  39. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    I'm having the exact problem on the GetComponent()<> script
     

    Attached Files:

  40. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Which line are you getting this error on?

    I can only assume that it is on line 57,58 or 59. If so, check that the object you attached Door_Script also has a "GeneratorCastTrigger", a "GeneratorCastTrigger1", and a "GeneratorCastTrigger2" on the same object.

    Also consider refactoring these classes into one class.
     
  41. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    I changed it a bit but its on line 51 now and they're actually in different objects tho like your suppose to activate 3 different generator

    Srry I didn't reply
     

    Attached Files:

  42. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,736
    Some notes on how to fix a NullReferenceException in Unity3D (also Unassigned Reference errors):

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

    This is like the simplest error. Stop and read the above steps, PUSH THROUGH IT! It's like forgetting to put a dot over your i or a cross over your t. It's that simple 99.9% of the time.
     
  43. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    also the message isn't displaying in the Visual Studio Script its showing when I start the project/ go into play mode
     
  44. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    You are getting this null reference exception because either

    "GeneratorObject3", "GeneratorObjectll" or "GeneratorObject" have not been assigned to in the inspector (did you forget to drag and drop the generator objects onto your door script?)

    or

    "GeneratorObject" Doesn't have a "GeneratorCastTrigger" component or
    "GeneratorObjectll" Doesn't have a "GeneratorCastTrigger1" componet or
    "GeneratorObject3" Doesn't have a "GeneratorCastTrigger2" component.

    Add Debug.Log statements everywhere to find out which of these is the cause.
     
  45. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    k I will :)
     
  46. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    so I have changed it again and VarAdd isn't working it's not showing the 2nd Debug.Log() and neither is the third Debug.Log()
     

    Attached Files:

  47. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Ok, That means that the nullreference is on line 46, 47 or 48

    Check the log right after your "GeneratorCastTrigger is working correctly" message is printed. It should have a nullreference error, which will tell you which line (and thus which generatorcasttrigger) is problematic.
     
  48. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    So I tried deleting line VarAdd then there was an Error on VarAdd2 and then deleted that same thing happened with VarAdd3 :/
     

    Attached Files:

  49. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    k now for some reason Debug.Log("the variable VarAdd") is working but line 52-53-54 still has error... help
     
  50. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    If you are getting a nullreference on each of those VarAdd lines, that tells you that your generatorcasttrigger/1/2 variables are null.

    GetComponent() will return null if there is no component of that type attached.

    Therefore, it appears that you have not attached your GeneratorCastTrigger/1/2 component to your GeneratorObject/11/3 objects.

    Double check that the objects the field "GeneratorObject/11/3" are referencing have a generatorcasttrigger/1/2 component attached to them.
     
Thread Status:
Not open for further replies.