I'm working in a Unity 3D app where I have 2 methods that connects to a service by using Oauth: one retrieves the token, and the other retrieves the JSON output from the service, based on the token. Once the JSON is ready then I change the text on a TextMesh. Everything running in the start method of the TextMesh script. Something like this:
void Start()
{
string authToken = getAuthToken();
CustomerGroups data = getCustGroups(authToken);
TextMesh curText = (TextMesh)gameObject.GetComponent(typeof(TextMesh));
curText.text = data.value[0].Field1+ "-" + data.value[0].Field2;
}
Oddly enough, this works great when I use "Attach to Unity" in Visual Studio and run the GameObject in the Unity player, but when I run it without debugging (like running a couple steps) I always get:
NullReferenceException: Object reference not set to an instance of an object
HelloWorldInteractive.getAuthToken () (at Assets/HelloWorldInteractive.cs:106)
HelloWorldInteractive.Start () (at Assets/HelloWorldInteractive.cs:15)
The actual method is:
public string getAuthToken()
{
string token = string.Empty;
Dictionary<string, string> content = new Dictionary<string, string>();
TokenClassName json = null;
content.Add("tenant_id", "https//...");
content.Add("grant_type", "client_credentials");
content.Add("client_id", "xxxx");
content.Add("client_secret", "xxxx");
content.Add("resource", "https://...");
UnityWebRequest www = UnityWebRequest.Post("https://login...", content);
//Send request
www.SendWebRequest();
if (!www.isNetworkError)
{
string resultContent = www.downloadHandler.text;
json = JsonUtility.FromJson<TokenClassName>(resultContent);
//Return result
token = json.access_token;
}
return token;
}
And again, if I don't debug it, it fails, but when I debug while running it, it works great. I'm assuming that it could be related to executing them in the Start method...maybe I need to do it somewhere else? I just need to have the JSON data ready so I can change the value of the TextMesh right at the start.