- Home /
Best way to assign and work with Canvas
I have had a lot of problems with SetActive and things getting left inactive and not being able to be found later. So I started using .GetComponent() to show and hide my overlays. I am new and not exactly sure how to work with this or if this is even an ideal way. So, for example, if I have this:
public GameObject overlay;
void Start(){
overlay.GetComponent<Canvas>().enabled = false;
}
public void showOverlay(){
overlay.GetComponent<Canvas>().enabled = true;
}
do I need to keep using GetComponent every time I want to use it? If not how can I assign it to a variable? Do I need to create a separate GameObject variable to assign the Canvas component to? Or should I keep calling GetComponent everytime I want to manipulate the Canvas? Or am I going about this all wrong? The showOverlay method is to be used with a button's OnClick in the inspector.
Answer by viodf · Apr 11, 2017 at 10:26 AM
Hi, You can simply assign it to a local variable, reuse that and it would be more performant than using GetComponent each and every time. See example below:
public GameObject overlay;
private Canvas overlayCanvas;
void Start(){
overlayCanvas = overlay.GetComponent<Canvas>();
overlayCanvas.enabled = false;
}
public void showOverlay(){
overlayCanvas.enabled = true;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612114418im_/https://answers.unity.com/themes/thub/images/avi.jpg)