how can i enable a component when another on gets disabled?
Hello I'm having some trouble on this script its for enabling a component when another one gets disabled, there's no errors it just does not work I think it's a logical error, here's the code.
using UnityEngine; using UnityEngine.UI; using System.Collections;
public class YouDiedTextScript : MonoBehaviour {
public Text youDiedText;
public PlayerController playerControllerScript;
void Start()
{
youDiedText.enabled = !youDiedText.enabled;
}
void Update()
{
if (playerControllerScript == !enabled)
{
youDiedText.enabled = youDiedText.enabled;
}
}
}
Answer by DiegoSLTS · Oct 18, 2015 at 01:19 PM
youDiedText.enabled = youDiedText.enabled;
That line in the Update method does nothing, I guess you want to set it to "true" directly, or set it to the oppositve value like you did in the Start method.
Also, MonoBehaviours have OnEnable and OnDisable methods to do things only when the component is enabled or disabled, check those too. Doing what you're doing in Update will call the code inside the if on EVERY frame when the condition is true, "enabling" it on every frame (this could add bugs if you combine this with the OnEnable or OnDisable methods).
Answer by Nikaas · Oct 18, 2015 at 06:34 PM
You can try something along the lines of :
private ComponentOne cOne; // The one that will be disabled
private ComponentTwo cTwo; // The one you want to enable
void Start()
{
cOne = GetComponent<ComponentOne>();
cTwo = GetComponent<ComponentTwo>();
}
void Update()
{
if (!cOne.enabled) {
cTwo.enabled = true;
}
}
Of course you must replace ComponentOne and ComponentTwo with your respective components.
But doing it this way is far from ideal. You can read here for an idea how to make your code not execute on every frame (Update) and instead run only when a component is disabled.
Thanks very much ,this has helped me out a lot thanks again
Your answer
Follow this Question
Related Questions
Cant Disable Script on Another Gameobject 1 Answer
On Renderer Was Enabled? (C#) 0 Answers