Please
read before this question is reported / taken offline! This question has already been taken offline on StackOverflow and I was pointed to the resolution of a general NullReferenceException. But these solutions somehow don't work for me 😥. Also, I'm a beginner 😅.
I get the well-known 'NullReferenceException: Object reference not set to an instance of an object' error. The detailed description: 'Coin.OnTriggerEnter2D (UnityEngine.Collider2D col) (at Assets/Space Adventure/Scripts/Game/Coin.cs:34)'.
These are my two scripts:
Coin Script (where I try to execute the SendBitcoin):
using UnityEngine;
public class Coin : MonoBehaviour
{
private Animation anim;
private AudioSource audioSource;
private bool taken;
void Start()
{
anim = this.GetComponent<Animation>();
audioSource = this.GetComponent<AudioSource>();
taken = false;
}
void OnTriggerEnter2D(Collider2D col)
{
if(!taken)
{
if(col.name == "Front" || col.name == "Back")
{
Wallet.SetAmount(Wallet.GetAmount() + 1);
anim.Play("Coin-Destroy-Down");
audioSource.Play();
taken = true;
BitcoinController.Instance.SendBitcoin();
}
}
}
}
Bitcoin Controller (where the Bitcoin should be send):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class GamerTagSend {
public string gamertag;
public string amount;
public string description;
}
public class BitcoinController : MonoBehaviour
{
public static BitcoinController Instance;
private void Awake()
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
public void SendBitcoin()
{
StartCoroutine(SendBitcoinCont());
}
IEnumerator SendBitcoinCont()
{
UnityWebRequest request = new UnityWebRequest("[here is the url]", "POST");
GamerTagSend postData = new GamerTagSend();
postData.gamertag = "gamertag";
postData.amount = "1";
postData.description = "It works : )";
string myjson = JsonUtility.ToJson(postData);
byte[] postDataBytes = System.Text.Encoding.UTF8.GetBytes(myjson);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.uploadHandler = (UploadHandlerRaw)new UploadHandlerRaw(postDataBytes);
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("apikey", "[here is my api key]");
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError("Error " + request.downloadHandler.text);
}
else
{
Debug.Log("sent!");
}
}
}
I hope you can help me. Thanks in advance. I've been trying to solve this problem for ages. I don't get it.
Please suggest code changes.
What I have tried:
Asking on StackOverflow (removed), searching the web, and searching the official Unity documentation.