Forum rules - please read before posting.

Background Changer on Variable

A script that allows a Background Image to change automatically textures on specific variable values.
E.g. You have a camera that shows a house in day, afternoon, night, so you want 3 textures.

using UnityEngine;
using AC;

public class ACBackgroundSwitcher : MonoBehaviour
{
    [System.Serializable]
    public struct TextureEntry
    {
        public int variableValue;
        public Texture2D texture;
    }

    [Header("AC Global Variable")]
    public int variableID = 1;

    [Header("Active Camera Gate")]
    public _Camera targetCamera;  

    [Header("Textures")]
    public TextureEntry[] entries;

    private BackgroundImage bgImage;
    private int lastVal = int.MinValue;

    void Awake()
    {
        bgImage = GetComponent<BackgroundImage>();
    }

    void Update()
    {
        if (!IsTargetCameraActive())
        {
            return; /
        }

        int val = GlobalVariables.GetIntegerValue(variableID);
        if (val != lastVal)
        {
            lastVal = val;
            ApplyTexture(val);
        }
    }

    bool IsTargetCameraActive()
    {
        if (targetCamera == null) return false; 
        return KickStarter.mainCamera != null
            && KickStarter.mainCamera.attachedCamera == targetCamera;
    }

    void ApplyTexture(int val)
    {
        foreach (var entry in entries)
        {
            if (entry.variableValue == val)
            {
                bgImage.backgroundTexture = entry.texture;
                BackgroundImageUI.Instance.SetTexture(entry.texture);
                return;
            }
        }

        Debug.LogWarning($"[ACBackgroundSwitcher] Textre Not Found {val} (Variable ID: {variableID})");
    }
}
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.