I’m trying to use the Instance() command to spawn a GameObject but I get weird results. The first time I place the object into the GameObject public variable, the object spawns fine, but the second time, and each one after, the console prints out NullReferenceException: Object reference not set to an instance of an object. The problem seems to come from the Update method in this script:
public class ResourceScript : MonoBehaviour, IOnClick
{
public Text materialCounter;
public void OnClickAction()
{
GameManager.material += GameManager.multiplier;
PlayerPrefs.SetInt("material", GameManager.material);
}
/*private void MiningMechanic()
{
if (miningPoints > 4)
{
Destroy(solidMaterial);
Instantiate(crackedMaterial, Vector3.zero, Quaternion.identity);
miningPoints++;
Debug.Log("You have" + miningPoints + "miningPoints");
}
}*/
private void Update()
{
materialCounter.text = "Rocks: " + GameManager.material;
}
}
Also, here is the script I use for spawning objects:
public class Spawner : MonoBehaviour, IOnClick
{
public GameObject solidMaterial;
public GameObject crackedMaterial;
int miningPoints = 0;
void Start()
{
Instantiate(solidMaterial, Vector3.zero, Quaternion.identity);
solidMaterial.AddComponent<ResourceScript>();
//solidMaterial.AddComponent<Text>();
}
public void OnClickAction()
{
MiningMechanic();
Debug.Log("MiningMechanic Activated");
}
private void MiningMechanic()
{
if (miningPoints > 4)
{
Destroy(solidMaterial);
Instantiate(crackedMaterial, Vector3.zero, Quaternion.identity);
miningPoints++;
Debug.Log("You have" + miningPoints + "miningPoints");
}
}
}
This is how it looks the first time I spawn a Prefab
And this is the second time
However, after the error starts appearing trying to instance the Prefab even inside of the most basic instancing script prints out the same error:
public class Test : MonoBehaviour
{
public GameObject solidMaterial;
// Start is called before the first frame update
private void Start()
{
Instantiate(solidMaterial, Vector3.zero, Quaternion.identity);
}
}
Does anyone have a clue why this is happening?