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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to set a RenderTexture as a background image at runtime?

Discussion in 'UI Toolkit' started by WongKit, Jan 22, 2023.

  1. WongKit

    WongKit

    Joined:
    Apr 27, 2017
    Posts:
    23
    Hi,

    how can I set a dynamically created RenderTexture as a background image of a visual element through C#?

    upload_2023-1-22_14-57-50.png

    The Dragon Crashers example project simply uses a predefined RenderTexture asset with a fixed resolution. However, I want to render a camera to a texture with the exact dimensions of the visual element.

    This is what I tried:
    Code (CSharp):
    1. //StyleBackground does not have a constructor with "Texture"
    2. style.backgroundImage = new StyleBackground(renderTexture);
    3.  
    4. //Overwriting the renderTexture does nothing
    5. Background background = resolvedStyle.backgroundImage;
    6. background.renderTexture = renderTexture;
    7.  
    8. //Use the somewhat hidden Image instead of VisualElement. It shows the render texture,
    9. //but the element increases its width and height on the next GeometryChangedEvent?!
    10. image = renderTexture;
    11.  
    12. //Preassigning a RenderTexture to the element in UIBuilder and working with it
    13. //works, but it prevents me from having multiple instances of the element. It
    14. //also always overwrites the asset in play mode.
    15. resolvedStyle.backgroundImage.renderTexture.Release();
    16. resolvedStyle.backgroundImage.renderTexture.width = newWidth;
    17. resolvedStyle.backgroundImage.renderTexture.height = newWidth;
     
  2. WongKit

    WongKit

    Joined:
    Apr 27, 2017
    Posts:
    23
    Sorry for double-posting. If someone has the similar problem, the following (imho not that intuitive) code can be used:

    Code (CSharp):
    1. visualElement.style.backgroundImage = new StyleBackground(Background.FromRenderTexture(renderTexture));
     
  3. Yury_K

    Yury_K

    Joined:
    Jan 18, 2017
    Posts:
    3
    Don't be sorry, answer is very useful.