I’m working on an NFT project in Unity and C#. I’ve got a class structure for the metadata, but I’m running into issues when trying to set the attribute values. Here’s what I’ve got so far:
public class NFTMetadata
{
public string description;
public string externalUrl;
public string imageUrl;
public string nftName;
public TraitAttribute[] traits;
}
[System.Serializable]
public class TraitAttribute
{
public string traitName;
public string traitValue;
}
I’m trying to populate this data in a method like this:
But I keep getting a NullReferenceException when trying to set the trait values. What am I doing wrong here? How can I properly initialize and set these attributes?
hey there Hugo_41Cook! i’ve worked with NFTs in Unity before and ran into similar issues. the problem is you’re not initializing the traits array before trying to access it. here’s a quick fix:
this should solve your NullReferenceException. but i’m curious, how many traits are you planning to have for each NFT? have you thought about using a List instead of an array for more flexibility? what kind of NFT project are you working on? sounds interesting!
I’ve encountered this issue before when working on NFT projects in Unity. The root cause is that you’re not initializing the traits array. Here’s a more robust approach:
This method uses object initializer syntax, which is more concise and less error-prone. It also allows you to initialize the traits array and its contents in one go. Consider using a List if you need to add traits dynamically in the future.