0

Everytime I want to play my Game with this script attached:

//...

    public Sprite[][] ObjectTypestobuy;
    public Sprite[] Characters;     
    public Sprite[] Helmets;
    public Sprite[] Weapons;
    public Sprite[] Mantles;
    public Sprite[] Shields;

void Start()
{
        ObjectTypestobuy[0] = Characters; //This is the line where the error message points to
        ObjectTypestobuy[1] = Helmets;
        ObjectTypestobuy[2] = Weapons;
        ObjectTypestobuy[3] = Mantles;
        ObjectTypestobuy[4] = Shields;
}

...it throws the following error: NullReferenceException:

> Object reference not set to an instance of an object (wrapper
> stelemref) object:stelemref (object,intptr,object) Shop_Handler.Start
> () (at Assets/Shop_Handler.cs:88)

The line which is marked as error is this one:

ObjectTypestobuy[0] = Characters;

I think the problem is, because it says I should edit public Sprite[][] ObjectTypestobuy; in the Inspector. But I can't find it in the inspector.

Any help would be precated.

Jul
  • 79
  • 1
  • 1
  • 9
  • 2
    Possible duplicate of [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) – Fabjan Jun 11 '18 at 14:58

2 Answers2

2

Before you can set a value in an array, the array must be created.

void Start()
{
        ObjectTypestobuy = new Sprite[5][10]; // for example
        ObjectTypestobuy[0] = Characters; //this is the error line
        ObjectTypestobuy[1] = Helmets;
        ObjectTypestobuy[2] = Weapons;
        ObjectTypestobuy[3] = Mantles;
        ObjectTypestobuy[4] = Shields;
}

Without creating the array, you can't put anything in it. You get the null exception because you're trying to put something in a non-existent object.

N.D.C.
  • 1,601
  • 10
  • 13
1

Unfortunately, you haven't actually initialized the array yet. This type of array is called a "Jagged" array.

So, the answer is here in this page here from Microsoft.

int[][] jaggedArray = new int[3][];

And then using initializers, the array can be filled:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

It's unfortunate that Unity doesn't serialize Dictionary collections. Given that limitation, a common work around to accomplish what I think you're trying to achieve is to do the following:

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

[Serializable]
public struct InventoryCollection
{
    public string Name;
    public List<Sprite> Sprites;
}

public class Inventory: MonoBehaviour
{
    public List<InventoryCollection> ObjectTypesToBuy = new List<InventoryCollection>();
}

You'll notice that now you can enter the items directly in to the Inspector window in Unity, and the "name" field will also name the items in the Inspector, as a convenience.

Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24