Enabling and Disabling a Canvas
Hi,
I have created a C# script which is currently attached to the "PlayerModel" which controls the camera, movement and is the audio listener. In my scene I have an object called "Canvas" which is the parent of buttons, input fields and labels. I need to be able to enable and disable the checkbox in the Canvas component in Canvas.
I have tried declaring a public GameObject called menu and in the inspector I have set it to the Canvas. Code below:
public void Update () {
//If the user presses the left mouse button
if (Input.GetMouseButtonDown (0)) {
//The direction called forward is the |forward| x dimension of a vector
Vector3 directionforward = transform.TransformDirection (Vector3.forward);
//If there is an object attached with a collider in front of the object sending out the raycast. This condition is true.
if (Physics.Raycast (transform.position, directionforward)) {
Debug.Log ("You hit something");
Canvas canvas = canvas.GetComponent<Canvas>();
canvas.enabled = !canvas.enabled;
canvas.enabled = true;
}
}
}
The Debug currently works but I can't seen to get the menu to appear. How can I edit this C# script to be able to make the canvas and all UI items as it's children appear and disappear on mouse click.
Thanks!
well that last part canvas.enabled = true should be enough, i Just used it like that, I have it in my script declared and in inspector set up (I'm only using it for the end game to appear so i only needed that one line)
maybe try to have an if statement that checks if canvas.enable == true, then change it to false, and other way around if canvas.enable == false changes it to true
Answer by Adventure-Forge-Studio · Oct 13, 2017 at 11:05 AM
@Valkarth I think .Enable is deprecated at this point. You should use .SetActive(false/true);
canvas.gameObject.SetActive(false/true);
@BenHowick, doublecheck it yourself. I believe, that is not true - not using latest unity version. But on 2017.1 everything is fine.
".enabled" and "gameObject.activeSelf" are two different things, they can't just replace one by another. $$anonymous$$oreover, using ".enabled" for canvas is prefferable than just turning object on/off. You can read about it here: https://unity3d.com/ru/learn/tutorials/topics/best-practices/other-ui-optimization-techniques-and-tips
Your answer
Follow this Question
Related Questions
Select Objects ingame and show information 0 Answers
Making GameObject move in the direction of my mouse (3d) 0 Answers
Toggle UI Text With UI Toggle Button 1 Answer
Mouse Events with Render Texture 0 Answers