- Home /
Display timer when power up is in use (C#)
So i have this problem with a text variable that I'm trying to show on the screen. I want to be able to see the text when the power up is in use and when the power up is NOT in use, it shouldn't be rendered or active in the hierarchy.
I tried using SetActive function and set the bool to true and it works if the object is active when the game starts, but if I disable it in the hierarchy. I get the usual message that the "object reference not set to an instance of an object"
What would be the best way to solve this? Since I just want to show the timer when the power up is in use? Here's a bit of code:
if(powerUp4 == true)
{
GameObject.Find("PowerUpText").SetActive(true);
destroyEnemiesTimer -= Time.deltaTime;
}
and here's when I disable it:
if(destroyEnemiesTimer <= 0.0f)
{
GameObject.Find("PowerUpText").SetActive(false);
powerUp4 = false;
}
Answer by blueteak · Jun 20, 2016 at 08:51 PM
You can't use GameObject.Find to find an inactive object. You need to save a reference of the variable at start so that you can activate/deactivate it at will without calling GameObject.Find each time (also better performance if the scene is large).
GameObject powerUpText;
void Start()
{
powerUpText = GameObject.Find("PowerUpText");
powerUpText.SetActive(false) //If you want it to be disabled at start
}
void ToggleActivation()
{
powerUpText.SetActive(powerUpText.activeSelf);
if(!powerUpText.activeSelf)
powerUp4 = false;
else
destroyEnemiesTimer -= Time.deltaTime;
}
Sorry I totally forgot I asked this question? :$ That looks logical, it should probably work, but I still think there's a problem, and that is that the variable "powerUpText" in my code is a public "Text" and not a "GameObject:
public Text powerUpTimer;
how can i convert this? Since I place the Text font in the hierarchy? @blue$$anonymous$$k
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Select Car - Multiple prefabs 1 Answer
Displaying PDF in unity 5.1.2f1 0 Answers
Photon - Hide/Show Object 1 Answer