I am back again after making much progress in quest for unity and c# knowledge. I have become stumped yet again by how to enable a canvas that is attached to my prefab. Here is the situation:
I am using C# on unity 5.5.0f3.
I have UI buttons that instantiate a defense based on a prefab. That prefab has a Canvas attached to it which has a health bar attached to it. Currently, the canvas is disabled so that the health bar does not show at all times. I am trying to make it appear only when I hold down a button, in this case "Z", and disappear when I release Z. My code is letting this work if I place a prefab before hand and set the GameObject reference in the editor. I want to get it to work for any object that has this canvas attached to it. This code does not work for all of the prefabs even if I take the canvas from the prefab and make it the reference.
I have tried to use an array like I have with other things that are currently working, but it does not work the same.
Here is my code:
public class DefenseHealthToggle : MonoBehaviour
{
public GameObject defenseHealthBars;
private bool isShowing;
void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
isShowing = !isShowing;
defenseHealthBars.SetActive(isShowing);
}
if (Input.GetKeyUp(KeyCode.Z))
{
isShowing = false;
defenseHealthBars.SetActive(isShowing);
}
}
}
While this is a minor detail in the game, I am trying to not let any of the ideas go if it is because I could just not figure out how to do it. I think I will learn the most if I don't give up every time I hit a wall and so far it has improved my knowledge tremendously! Anyone point me in the right direction or help me with some code? Thank you for your time!