0

Ill be the first to admit, Im not fluent in C#, but I started this project for school and I have 2 scripts; Game_Handler, and Game_Set_Handler. Game_Handler does the actual game while the Set_Handler handles my dictionary.

Heres Game_Set_Handler

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.UI;
using System.Threading.Tasks;
using System.Diagnostics;
using Random = System.Random;


public class Game_Set_Handler : MonoBehaviour
{
    public class Set
    {
        public string? Question { get; set; }
        public int StartingPoints { get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string? Answer4 { get; set; }
        public string? Answer5 { get; set; }

    }

    public Dictionary<int, Set> Sets;

    public void Handler()
    {
        Sets = new Dictionary<int, Set>()
        {
            {1,new Set { Question="sports to play outside", StartingPoints=250, Answer1 = "football", Answer2 = "baseball", Answer3 = "basketball", Answer4 = "soccer", Answer5 = "golf"}},
            {2,new Set { Question="board games", StartingPoints=375, Answer1 = "chess", Answer2 = "checkers", Answer3 = "monopoly",Answer4 = "battleship",Answer5 = "mancala"}},
            {3,new Set { Question="famous religions", StartingPoints=400, Answer1 = "christianity", Answer2 = "islam", Answer3 = "judaism",Answer4 = "buddhism",Answer5 = "hinduism"}},
            {4,new Set { Question="types of bread in the USA", StartingPoints=225, Answer1 = "banana", Answer2 = "sourdough", Answer3 = "white",Answer4 = "wheat",Answer5 = "pumpkin"}},
            {5,new Set { Question="car brands in the USA", StartingPoints=100, Answer1 = "ford", Answer2 = "chevrolet", Answer3 = "toyota",Answer4 = "honda",Answer5 = "volkswagen"}},

        };
    }

    void Start()
    {
        Handler();
    }


    public int Get_Question()
    {
        int value = new Random().Next(0, Sets.Count + 1);
        return value;
    }
}

And here is how I link the two (this is Game_Handler):

var dictionary = Parent.GetComponent<Game_Set_Handler>().Sets; //Parent is the Canvas, both scripts are connected to it
int dict_key = Parent.GetComponent<Game_Set_Handler>().Get_Question();

It works absolutely fine, until I've tested the Unity project 6 or 7 times, then it throws this error every-time I test it afterwards:

Its worth noting that if I copy the same exact script, make a new script, and paste it(obviously changing the class name), it works just fine until I test it 6 or 7 times.

NullReferenceException: Object reference not set to an instance of an object
Game_Set_Handler.Get_Question () (at Assets/Scripts/Game_Set_Handler.cs:53)
Game_Handler.Start_Game () (at Assets/Scripts/Game_Handler.cs:60)
Game_Handler.Start () (at Assets/Scripts/Game_Handler.cs:121)

Ive been stuck on this for the last 2 days and I'm about to take the L and move on, if anyone could help I would appreciate it.

I've tried replacing the function with a different one but the error still proceeds, I've copied it 3 times over just for testing purposes but I feel as if when I export it into an executable, it will happen then aswell.

  • 1
    You haven't shown us how you're *using* the result of `Get_Question`, but why would you want it to give one of *six* different values (0-5) when you only have *five* questions? – Jon Skeet May 12 '23 at 13:20
  • I did the +1 because it wouldnt give me set 5 at first, but its not there now, this is how im using Get_Question() `dict_key = Parent.GetComponent().Get_Question();` `question = dictionary[dict_key].Question;` – Issaiah Teneyck May 12 '23 at 13:24
  • What do you expect to happen if `Random.Next()` returns 0? (It doesn't sound like you really need a dictionary at all... if you're only accessing the elements by index, just use a list...) – Jon Skeet May 12 '23 at 13:25
  • Well im making this solely based on my knowledge of Lua and Python, and I've made the same game before in those languages and dictionaries just made sense, but I still hardly understand dictionaries here. my original thought was to have something like `{ ["question used to reference"] = {Answer_Points, {"list of answers"}}` and thats the best I came up with. The point is so i could loop through, get a random question, and stats associated with the question – Issaiah Teneyck May 12 '23 at 13:28
  • This could happen if Get_Question() is called before Handler() (or Start()) Sets would be null and you can't access Count off a null value. You can fix that issue or check that Sets isn't null inside Get_Question and handle it from there. – Ceres May 12 '23 at 15:57
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – sujoybyte May 13 '23 at 01:46

2 Answers2

0
    int value = new Random().Next(0, Sets.Count);//remove +1 may fix your problem

try this approach:

public int Get_Question()
{
    if (Sets == null)
    {
       Handler();
        //Debug.LogError("Sets dictionary is null!");
        //return -1;
        
        
    }

    int value = new Random().Next(0, Sets.Count);
    return value;
}

also move the following codeblock to top of file:

void Start()
{
    Handler();
}
Zen Of Kursat
  • 2,672
  • 1
  • 31
  • 47
0

Okay so I genuinely have ZERO idea why this fixed it, maybe it will break again down the line, but it makes no sense. I partially used the answer above and it did not work, then I realised there was nothing wrong with Game_Set_Handler, it was my Game_Handler, my public Dictionary was not accessible for whatever reason so I added a print statement above the error and the error went away.

Old Code(snippet):

    void Start_Game()
    {
        if (timerOn == false){
            timerOn = true;
        }
        if (gamePlaying == false){
            gamePlaying = true;
        }
        var dictionary = Parent.GetComponent<Game_Set_Handler>().Sets; // NullRefError at this line
        string question = dictionary[dict_key].Question;

Code that is currently working:

    void Start_Game()
    {
        if (timerOn == false){
            timerOn = true;
        }
        if (gamePlaying == false){
            gamePlaying = true;
        }
        print(Parent.GetComponent<Game_Set_Handler>().Get_Question());
        var dictionary = Parent.GetComponent<Game_Set_Handler>().Sets; // No error at all now
        string question = dictionary[dict_key].Question;

If anyone has an explanation to why this is I'd love to hear it but it doesn't make much sense to me(Get_Question is called before its index is used, that was my only explanation so it doesn't work)