-1

I am trying to add some data to the attribute parameters of below code in C# but every time it gives me the NullObjectRefrence exception. If anyone know about it please.

 public class RootObject
{
    public string description;
    public string external_url;
    public string image;
    public string name;
    public Attribute[] attributes;

    
}

    [System.Serializable]
    public class Attribute
    {
    
        public string trait_type;
        public string value;
    
    }

In The updatethePlayerData() function below i am trying to add the values of trait_type and its corresponding value.

 public void updatethePlayerData()
{
     RootObject rootObject = new RootObject();
    rootObject.description = "aaa";
    rootObject.image = "bbb";
    rootObject.external_url = "ccc";
    rootObject.name = "dddd";
    rootObject.attributes[0].trait_type = "character_class";
    rootObject.attributes[0].value = "name of cahracter";
  
 
}
Everts
  • 10,408
  • 2
  • 34
  • 45
immi khan
  • 67
  • 1
  • 10
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Selvin Dec 07 '22 at 10:34
  • 1
    you have a reference for an Attribute array but the array is not created, you need a new Attribute [length]; – Everts Dec 07 '22 at 10:53
  • @Everts can you explain a little bit, if possible write the code please. – immi khan Dec 07 '22 at 11:51

1 Answers1

0

Finally, I found the solution.

  1. In the "RootObject" class changed the Attribute array to a list as follows:
public List <Attribute> attributes;
  1. in the calling function create an object of the "Attribute" class as follows:
Attribute attribute = new Attribute();

Now I can assign values to the list as follows:

attribute.trait_type = "Some Value";

Hope this helps if someone looking around!

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42
immi khan
  • 67
  • 1
  • 10