I have a game, where when an object is deleted, money is added. The amount of money the player has should be displayed on text. When I run the game, and when money should be added to the text, the text doesn’t change. The prefab of the text shows the correct amount of money, and it is updating with every object that is deleted. When I stop and start the game in unity, the text then updates, and stays at the value of money that was in the code at the start. Please help me with this… Thanks.
Here is my code to destroy the object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Despawn_ : MonoBehaviour {
public Moneyy mmoney;
public float localMoney = 0.0f;
public float waitTime = 15.1f;
public float Value = 1.0f;
public float zero = 0;
void OnCollisionEnter(Collision col)
{
if (zero == 0)
{
if (col.gameObject.name == "Despawner")
{
DestroyObjectDelayed();
AddMoney();
zero++;
}
}
}
void AddMoney()
{
mmoney.Money += Value;
}
void DestroyObjectDelayed()
{
Destroy(gameObject, waitTime);
}
}
Here is my code to add the money to the text.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Moneyy : MonoBehaviour {
public UnityEngine.UI.Text moneyDisplay;
public float Money = 0.0f;
void Update()
{
moneyDisplay.text = "$" + Money;
}
}
I’m not sure why this is happening, maybe to update the float money while the game is running? idk…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Despawn_ : MonoBehaviour {
public Moneyy mmoney;
public float localMoney = 1.0f;
public float waitTime = 15.1f;
public float Value = 1.0f;
public float zero = 0;
void Start() //added this
{
mmoney = GameObject.FindObjectOfType<Moneyy>();
}
void OnCollisionEnter(Collision col)
{
if (zero == 0)
{
if (col.gameObject.name == "Despawner")
{
AddMoney(); //moved this befor the destroy
DestroyObjectDelayed();
zero++;
}
}
}
void AddMoney()
{
mmoney.Money += localMoney; //changed this to use localMoney
}
void DestroyObjectDelayed()
{
Destroy(gameObject, waitTime);
}
}