Home > Back-end >  Implementing Light and Dark mode?
Implementing Light and Dark mode?

Time:10-06

How to achieve light and dark mode without having different sprites for each mode?

Optimal would be some sort of prefab for colors. That way every Gameobject would be assigned a certain type of color and to change it I only have to change the color of the Color prefab.

I don't think that exists but maybe someone knows a similar way?

I am using c# and Unity

CodePudding user response:

I think you can use scriptableObjects which you can save them like assets in your game. I have written a simple code for you which work for Images. First create the class for Image UI components.

[CreateAssetMenu(fileName = "Color", menuName = "UI/Color Pallet", order = 1)]
public class ImageColorPallet : ScriptableObject
{
    public Color lightColor;
    public Color darkColor;
}

then, right click in the project tab and from UI menu create a color pallet scriptable object. (this path is created by the path defined in the scriptable Object code in the menuName attribute) then add the following code to an image component and assign the scriptable object you created to it. Turn the dark mode on and off to see the changes. (Beware that the colors transparency is not 0)

public class ImageColorMode : MonoBehaviour
{
    [SerializeField] private ImageColorPallet colorPallet;
    [SerializeField] private bool isDark;
     
    private void OnValidate()
    {
        GetComponent<Image>().color = isDark ? colorPallet.darkColor : colorPallet.lightColor;
    }
}

The problem is that you have to create these scriptable objects for each of your UI elements.

  • Related