I am new to Unity. I have created two theme style sheet (tss) and have added all the required theming. I am able to switch in the UI Builder and also verified the themes are working. I also verified in the panel UI settings by changing the theme.
I have added @ url(“unity-theme://default”); in both the themes.
Currently I am trying to change the theme in the run time, by clicking on a button I wanted to change the theme.
Is there a way to change the default theme on run time ?
Hi,
if I understand correctly, you have two themes t1 and t2 and you want to switch from t1 to t2 (or t2 → t1) at runtime by clicking a button somewhere in your ui?
Yes Exactly That is what I am trying to do
For what follows, I assume you already have a UI Document object in your scene.
One way to achieve what you want to do could be something similar to this
1 - Create a MonoBehaviour with two serializable ThemeStyleSheet fields
using UnityEngine;
using UnityEngine.UIElements;
public class ThemeManager : MonoBehaviour
{
public ThemeStyleSheet theme1;
public ThemeStyleSheet theme2;
// Start is called before the first frame update
void Start()
{
var uidocument = GetComponent<UIDocument>();
var root = uidocument.rootVisualElement;
var button = root.Q<Button>();
button.clicked += () =>
{
if (root.styleSheets.Contains(theme1))
{
root.styleSheets.Remove(theme1);
root.styleSheets.Add(theme2);
}
else
{
root.styleSheets.Remove(theme2);
root.styleSheets.Add(theme1);
}
};
}
}
2 - Add this MonoBehaviour to you UIDocument object (from the Inspector of the UIDocument object, click “Add Component” then pick your ThemeManager class)
3 - Set both Theme1 and Theme2 fields to your theme assets from the inspector.
4 - Play run!
Thank you so much it worked perfectly!!! I am able to change the theme runtime