C# Unity NullReferenceException when setting NFT metadata attributes for OpenSea

I keep getting a NullReferenceException when trying to populate attribute data for NFT metadata in my Unity C# project. The error happens every time I try to assign values to the attributes array. Can someone help me figure out what I’m doing wrong?

public class MetadataContainer
{
    public string desc;
    public string website_link;
    public string picture;
    public string title;
    public Property[] properties;
}

[System.Serializable]
public class Property
{
    public string category;
    public string data;
}

In my setupMetadata() method I’m trying to assign the category and data values but it throws the null reference error:

public void setupMetadata()
{
    MetadataContainer container = new MetadataContainer();
    container.desc = "test description";
    container.picture = "image url";
    container.website_link = "external link";
    container.title = "token name";
    container.properties[0].category = "hero_type";
    container.properties[0].data = "warrior class";
}

lol so true! totally a common issue. just make sure to initialize your properties array like container.properties = new Property[size]; or it’ll be null. then create each Property object before trying to set the values. good luck!

This happens because arrays in C# are reference types and default to null unless you initialize them. Your MetadataContainer’s properties array isn’t allocated any memory, so when you try to access container.properties[0], you’re dereferencing a null pointer. I ran into this same issue when I was integrating blockchain stuff in a game. You need to initialize the array and create Property instances: csharp public void setupMetadata() { MetadataContainer container = new MetadataContainer(); container.desc = "test description"; container.picture = "image url"; container.website_link = "external link"; container.title = "token name"; container.properties = new Property[1]; container.properties[0] = new Property(); container.properties[0].category = "hero_type"; container.properties[0].data = "warrior class"; } Or just initialize the properties array in your MetadataContainer constructor instead.

Oh I see what’s happening! You’re trying to access container.properties[0] but never initialized the properties array. When you create new MetadataContainer(), the properties field is still null.

Try this before assigning values:

container.properties = new Property[1]; // or however many you need
container.properties[0] = new Property();

For multiple properties:

container.properties = new Property[2];
container.properties[0] = new Property();
container.properties[1] = new Property();

Question though - do you have a fixed number of properties or does it vary per NFT? What metadata standards are you using for OpenSea? Working on something similar and wondering if you’re using their attribute format or going custom.