Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Enabling canvases that are prefabs?

Discussion in 'Prefabs' started by clurpslurp, Jul 21, 2023.

  1. clurpslurp

    clurpslurp

    Joined:
    Jul 3, 2023
    Posts:
    23
    I want an instantiated object to be present, and when it is, on button press, I want to activate a canvas, and then deactivate it after another key is pressed.
    However, because the instantiated object is a prefab, i can't find a way to attach a canvas inside the scene onto it. So I made the canvas a prefab.
    Currently, I've set a
    public bool isShowing;
    and checked it to true in the inspector.
    I also made the Canvas a Gameobject (before i tried making it a Canvas and using .enabled but it didn't work)
    and at the start of the scene,
    Canvas.SetActive(!isShowing)
    then, when the the key R is pressed (key press works independantly btw)
    Canvas.SetActive(isShowing)
    I've tried taking the Canvas out of the scene and putting it in the scene, and both of them don't work as intended. Is there a reason to why this may be?
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,834
    If your UI-oriented prefab has no Canvas, then instantiate the prefab with the appropriate existing Canvas as its parent (or somewhere under the Canvas family tree). This is common for smaller reusable elements that you may want to instantiate many times, like an element inside a scrolling list view, or even a scrolling list view itself.

    If your UI-oriented prefab has a Canvas, just make sure it has the correct sorting/camera settings after instantiating it with no parent. It's fine for a game to have many Canvas objects, and it's useful to have the Canvas inside the prefab for many "self-contained" things like a whole dialog box.
     
    clurpslurp likes this.
  3. Unifikation

    Unifikation

    Joined:
    Jan 4, 2023
    Posts:
    1,026
    Yes. There are horror show, show stopping bugs in the Canvas and RectTransforms at this very moment, in the last 4 "updates" to 2022.LTS and some of these are in the latest 2021.LTS "updates", too.
     
    clurpslurp likes this.