System.NullReferenceException: Object reference not set to an instance of an object

Andre 1 Reputation point
2022-09-13T13:52:58.213+00:00

Good Day, I'm programming a game with Unity, but I cannot resolve this error:

NullReferenceException: Object reference not set to an instance of an object
CharacterManager.UpdateCharacter (System.Int32 selectedOption) (at Assets/CharacterManager.cs:47)
CharacterManager.Start () (at Assets/CharacterManager.cs:17) could you help me?
Thanks in advance of the answer

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using UnityEngine.UI;  
  
  
public class CharacterManager : MonoBehaviour  
{  
    public CharacterDatabase characterDB;  
    public Text nameText;  
    public SpriteRenderer artworkSprite;  
    int selectedOption = 0;  
  
    //start is called before the first frame update  
    void Start()  
    {  
        UpdateCharacter(selectedOption);  
    }  
  
    public void NextOption()  
    {  
        selectedOption++;  
  
        if(selectedOption >= characterDB.CharacterCount)  
        {  
            selectedOption = 0;  
        }  
  
        UpdateCharacter(selectedOption);  
    }  
    public void BackOption()  
    {  
        selectedOption--;  
  
        if(0 > selectedOption)  
        {  
            selectedOption = characterDB.CharacterCount - 1;  
        }  
  
        UpdateCharacter(selectedOption);  
    }  
  
    private void UpdateCharacter(int selectedOption)  
    {  
        Character character = characterDB.GetCharacter(selectedOption);  
        artworkSprite.sprite = character.characterSprite;  
        nameText.text = character.characterName;  
    }  
}  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,230 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,366 Reputation points
    2022-09-13T15:31:07.037+00:00

    the variable:

    public CharacterDatabase characterDB;

    is never initialized, so accessing its properties and methods will throw an error.

    0 comments No comments