I'm creating an object where the type is a class, and instantiating it using only constant values, but it keeps failing. I have the class in another file, with public subclasses. I'm accessing those subclasses, by using the class name, and then the type, because my instantiation of it, doesn't have the subclasses. It then tells me I have a null reference error on that line. I was originally using dynamic values, but since that failed, I substituted them with constants.
Here my code is.
Requests.cs
public class Requests
{
// Start is called before the first frame update
public class PostData{
public Dictionary<string, Time> fields;
}
public class Time{
public double doubleValue;
}
}
Main.cs
public void SaveButtonClicked()
{
requestLib = new Requests();
}
private IEnumerator SaveData()
{
Requests.PostData postData = new Requests.PostData {fields = {{"Richard", new Requests.Time{doubleValue = 6.44}}}};
var request = requestLib.CreateRequest($"https://firestore.googleapis.com/v1/projects/xxx/databases/(default)/documents/levels/{FinishScreen.level}", Requests.RequestType.PATCH, postData);
Debug.Log("hi");
yield return request.SendWebRequest();
}
The error is on this line Requests.PostData postData = new Requests.PostData {fields = {{"Richard", new Requests.Time{doubleValue = 6.44}}}};
All the values are hardcoded, but I'm still getting NullReferenceException: Object reference not set to an instance of an object
.
Sorry, I'm new to C#, so I'm not able to find why the error has appeared.
CodePudding user response:
When you call the object initialiser for fields
, you aren't instantiating a new object:
fields = {{"Richard", new Requests.Time{doubleValue = 6.44}}}
This is trying to call the method Add(string, Time)
, but is doing so against a null reference.
You need to do this instead:
fields = new Dictionary<string, Requests.Time>
{
{ "Richard", new Requests.Time { doubleValue = 6.44 } }
}