0
\$\begingroup\$

I want to make a slide of images that change automatically by a timer without pressing any button for example every 5 seconds the image changes to another one. I have a script but it only changes them when pressing a button I looked everywhere but I found no info about how to do it with time instead of sliding buttons.

this is the script I'm using now:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Slidescript : MonoBehaviour
{
    //All _slides in the project, minus the _fadeSlide
    [SerializeField]
    private List<Transform> _slides = default;

    //The panel that overlays all _slides and changes from clear to black
    [SerializeField]
    private Image _fadeSlide = default;

    [Header("Config Values")]
    [SerializeField, Tooltip("The duration (in seconds) over which the fade slide will fade in / out")]
    private float _fadeDuration = 0.75f;

    [SerializeField, Tooltip("All key codes that will move to the next slide if pressed")]
    private KeyCode[] _nextSlideKeyCodes = {
        KeyCode.D,
        KeyCode.RightArrow,
        KeyCode.Space
    };

    [SerializeField, Tooltip("All key codes that will move to the previous slide if pressed")]
    private KeyCode[] _previousSlideKeyCodes = {
        KeyCode.A,
        KeyCode.LeftArrow,
    };

    //The slide we're currently viewing
    private int _currentSlide = -1;

    // Whether the fade slide is currently fading
    private bool _isTransitioning = false;

    private void Start()
    {
        // Set our fade to black slide to black so that the audience can not see the first slide
        _fadeSlide.color = Color.black;
    }

    public void Update()
    {
        //Check for arrow keys/space bar down so we can fade the fadePanel accordingly
        ListenForInput();
    }

    private void ListenForInput()
    {
        // Ignore input if we're in the middle of a transition
        if (_isTransitioning)
        {
            return;
        }

        //If we strike the space bar or right arrow key, proceed to the next slide
        if (_nextSlideKeyCodes.Any(Input.GetKeyDown))
        {
            NextSlide();
        }

        //If we strike the left arrow key, return to the previous slide
        if (_previousSlideKeyCodes.Any(Input.GetKeyDown))
        {
            PreviousSlide();
        }

        //If we strike the Esc key, quit the application
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
    }

    private void NextSlide()
    {
        //If we're on the very last slide already..
        if (_currentSlide == _slides.Count - 1)
        {
            // Exit early
            return;
        }

        //Increment the slide count
        _currentSlide++;

        // Transition to the next slide
        StartCoroutine(SlideTransition());
    }


    private IEnumerator SlideTransition()
    {
        // Mark our fading slide as currently fading
        _isTransitioning = true;

        // Fade to black
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.black));

        // Set only our current slide active - and all others inactive
        _slides.ForEach(slide => slide.gameObject.SetActive(_slides.IndexOf(slide) == _currentSlide));

        // Fade to clear
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.clear));

        // Mark our fading slide as no longer fading
        _isTransitioning = false;
    }

    private void PreviousSlide()
    {
        //If the current slide is the very first slide, ignore the rest of this method
        if (_currentSlide == 0)
        {
            return;
        }

        //Decrement the current slide
        _currentSlide--;

        // Transition to the previous slide
        StartCoroutine(SlideTransition());
    }

    private IEnumerator FadeToTargetColor(Color targetColor)
    {
        // The total amount of seconds that has elapsed since the start of our lerp sequence
        float elapsedTime = 0.0f;

        // The color of our fade panel at the start of the lerp sequence
        Color startColor = _fadeSlide.color;

        // While we haven't reached the end of the lerp sequence..
        while (elapsedTime < _fadeDuration)
        {
            // Increase our elapsed time
            elapsedTime += Time.deltaTime;

            // Perform a lerp to our target color
            _fadeSlide.color = Color.Lerp(startColor, targetColor, elapsedTime / _fadeDuration);

            // Wait for the next frame
            yield return null;
        }
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ You already kind of have a timer in there, you know? \$\endgroup\$
    – Vaillancourt
    Aug 2 at 18:45
  • \$\begingroup\$ Presumably you considered copying your existing elapsed time code for fading and using it to drive the slide show advancement, or using a coroutine with WaitForSeconds? It's not clear to me what is novel about this task that you need help doing, when all the ingredients you need are present in the code you've shown. \$\endgroup\$
    – DMGregory
    Aug 2 at 19:04
  • \$\begingroup\$ @Vaillancourt I know I have that but it doesn't work because there are buttons I have to press or something do you have any idea how I can shorten this code and remove all the lines that has button press functions. i only need timer slideshow. \$\endgroup\$ Aug 2 at 20:16
  • \$\begingroup\$ Selecting the lines you don't want and pressing delete works. But if you can't figure out which lines relate to the buttons and which ones don't, then you have a bit more learning to do before you're ready to make the most of this site. I'd recommend working your way through a few beginner Unity tutorials, until you can read code like this and understand what each line is doing. Once you have that core fluency in the language you're using, you'll be able to ask questions and understand answers much more effectively, as well as solve more problems for yourself. \$\endgroup\$
    – DMGregory
    Aug 3 at 9:44

1 Answer 1

0
\$\begingroup\$

You can use a Coroutine with WaitForSeconds to create a timer:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;

public class Slidescript : MonoBehaviour
{
    //All _slides in the project, minus the _fadeSlide
    [SerializeField]
    private List<Transform> _slides = default;

    //The panel that overlays all _slides and changes from clear to black
    [SerializeField]
    private Image _fadeSlide = default;

    [Header("Config Values")]
    [SerializeField, Tooltip("The duration (in seconds) over which the fade slide will fade in / out")]
    private float _fadeDuration = 0.75f;
    [Header("Config Values")]
    [SerializeField, Tooltip("The duration (in seconds) over switch silde")]
    private float _switchDuration = 1.6f;
    //The slide we're currently viewing
    private int _currentSlide = -1;

    // Whether the fade slide is currently fading
    private IEnumerator Start()
    {
        // Set our fade to black slide to black so that the audience can not see the first slide
        _fadeSlide.color = Color.black;
        while (true)
        {
            _currentSlide++;
            _currentSlide = _currentSlide % _slides.Count;

            // Transition to the next slide
            StartCoroutine(SlideTransition());
            yield return new WaitForSeconds(_switchDuration);
        }
    }

    private IEnumerator SlideTransition()
    {
        // Fade to black
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.black));

        // Set only our current slide active - and all others inactive
        _slides.ForEach(slide => slide.gameObject.SetActive(_slides.IndexOf(slide) == _currentSlide));

        // Fade to clear
        yield return StartCoroutine(FadeToTargetColor(targetColor: Color.clear));
    }

    private IEnumerator FadeToTargetColor(Color targetColor)
    {
        // The total amount of seconds that has elapsed since the start of our lerp sequence
        float elapsedTime = 0.0f;

        // The color of our fade panel at the start of the lerp sequence
        Color startColor = _fadeSlide.color;

        // While we haven't reached the end of the lerp sequence..
        while (elapsedTime < _fadeDuration)
        {
            // Increase our elapsed time
            elapsedTime += Time.deltaTime;

            // Perform a lerp to our target color
            _fadeSlide.color = Color.Lerp(startColor, targetColor, elapsedTime / _fadeDuration);

            // Wait for the next frame
            yield return null;
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ works perfectly thank you. the other code was kinda complicated \$\endgroup\$ Aug 3 at 12:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .