Array NullReferenceException
Asked Answered
B

1

0

So, i didnt really find anything that helped me in other threads, so here is myproblem:
I want to generate random Quests for my game so i created one script that is not on an object containing the following code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
	
[System.Serializable]

public class QuestsType : System.Object
{
	public string questName;
	public string giverName;
	public int type;
	public int difficulty;
	public int questLength;
}

and then i have this second script, wich i hoped would give me the value of the variable “type” of each of the generated arrays (just for testing):

	public int questAmountMin;
	public int questAmountMax;

	public QuestsType[] quests;

	void Start ()
	{
		GenerateQuests();
	}

	void GenerateQuests()
	{
		quests = new QuestsType[Random.Range(questAmountMin,questAmountMax)];
		for (int i = 0;  i < quests.Length ; i++)
		{
			print(quests*.type);*
  •  }*
    
  • }*
    It will then always (except if the random “quests” array has a length of 0) give me a NullReferenceException: Object reference not set to an instance of an object - error.
    The strange thing now is that it acually works, but only if i manually execute the
  •  for (int i = 0;  i < quests.Length ; i++)*
    
  •  {*
    

_ print(quests*.type);_
_
}_
_
-portion via a button or something, and ONLY IF the inspector shows the Gameobject with the second script. ive never seen something like that before…*_
I would really appreciate your help!

Blairblaire answered 3/7 at 8:51 Comment(0)
R
0

Instantiating the array is a different step from instantiating the objects inside the array.

Because QuestsType is a class, the array QuestsType[] quests is an array of references to QuestsType. And all references are initialized by default as null references (references that point to nothing) until you create something it can point to.

When you first create the array (line 13), it’s an array of references to nothing.

You need to go:


    for (int i = 0; i < quests.Length; i++)
    {
         quests *= new QuestsType();*
 *// then you can do this*
 _print(quests*.type);*_
 _*}*_
_*```*_
_*There's also no need for QuestsType to be declared as QuestsType : System.Object. All declared classes already inherit from System.Object without you writing anything on there.*_
_*What programming language did you come from? So we can point you in more helpful directions.*_
Rosannarosanne answered 6/6, 2023 at 1:47 Comment(2)

Thank you very much! That seems to work. I am learning it by myself and are still very much a scrub, using the internet and those forums a lot, also im coming from JS.

Blairblaire

Holy Pepperoni, I had the same problem and was slowly going insane looking for an answer to it. Finally I found something! You really saved my day, thank you so much!

Hansom

© 2022 - 2024 — McMap. All rights reserved.