- Home /
Instantiate on click if enough gold / ressources
Hi there, I have made an UI with some buttons and I'd like to instantiate things when i click those, but only if i have enough gold. Spawning works fine without the if statement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnCreep : MonoBehaviour
{
public GameObject Creep;
public Transform Spawnpoint;
public int Cost;
private crntGold gold;
public void SpawnThis()
{
//gold = GetComponent<crntGold>();
// if (gold.gold >= 10)
// {
Instantiate(Creep, Spawnpoint.position, Spawnpoint.rotation);
// gold.gold = gold.gold - Cost;
// }
}
}
how come, and how could i change this? for sake of completeness, here is my gold script, maybe the error is there:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class crntGold : MonoBehaviour
{
public int gold;
public Text uigold;
private GoldCounter goldCounter;
void Start()
{
gold = 100;
uigold.text = "Gold:" + gold.ToString();
goldCounter = GetComponent<GoldCounter>();
}
// Update is called once per frame
void Update()
{
if (goldCounter.timer == 0.0f) ;
{
uigold.text = "Gold:" + gold.ToString();
}
}
}
thanks for any replys in advance!
Are you sure the component crntGold component is attached to the same object that the SpawnCreep script is attached to?
Answer by Mr_parkour10021 · Mar 08, 2019 at 04:14 AM
Hi there, @kaji0tt try to Debug.Log();
your gold.gold
to check the actual value.
It says "NullReferenceException: Object reference not set to an instance of an object" as gold.gold appears.. however, im succesfully fetching this instance with my income counter script. It adds 10 gold to the crntGold evéry 10 seconds, with the same procedure of geting the component
Just checked Income Counter with Debug - works great, i have 100 "gold.gold" at start, +10 every 10 seconds.
Answer by kaji0tt · Mar 08, 2019 at 04:01 PM
The Tab get component was opened for the last 15 hours, however it took me this time to realise, that i had to fetch the gold parameter with "gold = Manager.GetComponent();" with my script manager added to the button.
Thank you @Mr_parkour10021 for introducing me to debugging - probably this was the more efficent way of learning.
Your answer
Follow this Question
Related Questions
How do i make the perfect button? 1 Answer
void dont show up in on click 1 Answer
OnClick() animation 0 Answers
[Solved] Button OnClick properties are missing after loading the scene 4 Answers