[UI Toolkit] Animate Tiled Background Scrolling
Solution
Unity 2021.3.x - Unity 6.3.x
Published Sat, Mar 7
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.
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.
- Ensure the source
Texture2Dwrap mode is set to Repeat in the asset importer settings. - Define a backgroundOffset variable to store the persistent horizontal or vertical displacement.
- Access the
IVisualElementSchedulervia your visual element schedule. - Within the
Executecallback, increment the backgroundOffset usingTime.deltaTimeand your speed multiplier. - Create a new
BackgroundPositioninstance using the backgroundOffset and aBackgroundPositionKeyword(e.g.,BackgroundPositionKeyword.Left). - Wrap this value in a
StyleBackgroundPositionand assign it to your visual element stylebackgroundPositionXorbackgroundPositionY. - Invoke the
.Every(16)method on the schedule call to ensure the animation updates at approximately 60 frames per second.
Additional Tips
- Use
UsageHints.DynamicTransformon 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.