UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

ui

[UI Toolkit] Animate Tiled Background Scrolling

Solution

uguianimatorbuild optimizationruntimestyling

Unity 2021.3.x - Unity 6.3.x

Published Sat, Mar 7

Issue

 When attempting to implement a scrolling tiled background effect in UI Toolkit using USS, direct manipulation of backgroundPositionX or backgroundPositionY on a VisualElement does not visually update the background image at runtime. Although the style property updates correctly in the UI Toolkit debugger, the image itself remains static. The backgroundPositionX API expects a BackgroundPositionKeyword instead of a direct Length or float value, complicating attempts to achieve a dynamically scrolling background. This prevents the creation of parallax or infinitely moving tiled backgrounds.

Explanation

To achieve a dynamically scrolling tiled background in UI Toolkit, the backgroundPositionX or backgroundPositionY property must be updated through the IVisualElementScheduler. Directly assigning a StyleBackgroundPosition to your visual element style will not render the visual change effectively unless the assignment is processed by the internal scheduler loop to force a repaint of the background geometry.

  1. Ensure the source Texture2D wrap mode is set to Repeat in the asset importer settings.
  2. Define a backgroundOffset variable to store the persistent horizontal or vertical displacement.
  3. Access the IVisualElementScheduler via your visual element schedule.
  4. Within the Execute callback, increment the backgroundOffset using Time.deltaTime and your speed multiplier.
  5. Create a new BackgroundPosition instance using the backgroundOffset and a BackgroundPositionKeyword (e.g., BackgroundPositionKeyword.Left).
  6. Wrap this value in a StyleBackgroundPosition and assign it to your visual element style backgroundPositionX or backgroundPositionY.
  7. Invoke the .Every(16) method on the schedule call to ensure the animation updates at approximately 60 frames per second.

Additional Tips

  • Use UsageHints.DynamicTransform on your visual element to optimize performance when the background is modified every frame.
  • If the backgroundOffset value increases indefinitely, reset it using a modulo operator based on the texture size to prevent floating point precision issues over long sessions.

TL;DR

Achieve infinite scrolling tiled backgrounds in UI Toolkit by updating BackgroundPosition through your visual element scheduler to ensure visual changes render correctly at runtime.


Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.