How to update NFT metadata attributes in Unity using C#?

I’m working on an NFT project in Unity and I’m stuck on updating the metadata attributes. Here’s my code structure:

public class NFTData
{
    public string info;
    public string link;
    public string picture;
    public string title;
    public Feature[] features;
}

[System.Serializable]
public class Feature
{
    public string category;
    public string detail;
}

public void UpdateNFTInfo()
{
    NFTData nftData = new NFTData();
    nftData.info = "NFT description";
    nftData.picture = "image_url";
    nftData.link = "external_link";
    nftData.title = "NFT name";
    nftData.features[0].category = "class";
    nftData.features[0].detail = "warrior";
}

I’m trying to add values to the features array, but I keep getting a NullReferenceException. How can I properly initialize and populate the features array in my UpdateNFTInfo() method? Any help would be appreciated!

hey there ray84! i’m also working on nft stuff in unity, so i totally get your frustration. have you tried initializing the features array before adding values to it? something like this might work:

public void UpdateNFTInfo()
{
    NFTData nftData = new NFTData();
    nftData.info = "NFT description";
    nftData.picture = "image_url";
    nftData.link = "external_link";
    nftData.title = "NFT name";
    
    // Initialize the features array
    nftData.features = new Feature[1];
    nftData.features[0] = new Feature();
    nftData.features[0].category = "class";
    nftData.features[0].detail = "warrior";
}

this way, you’re creating the array and the Feature object before trying to access them. let me know if that helps!

btw, what kind of nft project are you working on? sounds interesting!

Ray84, I’ve encountered similar issues when working with NFTs in Unity. Here’s a suggestion that might help:

Instead of using an array for features, consider using a List. It’s more flexible and easier to work with. You can modify your NFTData class like this:

public class NFTData
{
// Other properties remain the same
public List features = new List();
}

Then in your UpdateNFTInfo method, you can simply add features like this:

nftData.features.Add(new Feature { category = “class”, detail = “warrior” });

This approach eliminates the need for manual array initialization and allows you to add as many features as you need dynamically. It should resolve your NullReferenceException issue.

Hope this helps with your NFT project. Let us know if you need any further assistance.

yo ray84, ben_comics gave a solid tip. another way is using List instead of an array. it’s more flexible:

public class NFTData
{
    // ... other properties
    public List<Feature> features = new List<Feature>();
}

// in UpdateNFTInfo
nftData.features.Add(new Feature { category = "class", detail = "warrior" });

this way u can add features without worrying about array size. hope it helps!