how to start IEnumerator again after SetActive(false);

44 views Asked by At

I am trying to create a picture function in my game, and I want the picture frame to vanish after a couple seconds. After I did that, when I tried to take the picture again, it wont work. I am very new to C#, and would love some help ^^;

After pressing space, a picture will show up, and after a few seconds it will disappear. If you press space again, the action repeats. The action does not repeat.

Here is the code :

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Animations;


public class PhotoCapture : MonoBehaviour
{
    
    [Header("Photo Taker")]
    [SerializeField] private Image photoDisplayArea;
    [SerializeField] private GameObject photoFrame;

    [Header("Flash Effect")]
    [SerializeField] private GameObject cameraFlash;
    [SerializeField] private float flashTime;

    [Header("Photo Fader Effect")]
    [SerializeField] private Animator fadingAnimation;

    private Texture2D screenCapture;
    private bool viewingPhoto;

    private void Start()
    {
        screenCapture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (!viewingPhoto)
            {
                StartCoroutine(CapturePhoto());


            }

        }
    }

    IEnumerator CapturePhoto()
    {
       
            //Camera UI set false
            viewingPhoto = true;

            yield return new WaitForEndOfFrame();

            Rect regionToRead = new Rect(0, 0, Screen.width, Screen.height);

            screenCapture.ReadPixels(regionToRead, 0, 0, false);
            screenCapture.Apply();
            ShowPhoto();
            


    }

    private void ShowPhoto()
    {
        //doflash
        Sprite photoSprite = Sprite.Create(screenCapture, new Rect(0.0f, 0.0f, screenCapture.width, screenCapture.height), new Vector2(0.5f, 0.5f), 100.0f);
        photoDisplayArea.sprite = photoSprite;

        photoFrame.SetActive(true);
        fadingAnimation.Play("photoFade");
        StartCoroutine(CameraFlashEffect());
        yield return new WaitForSeconds(2);
        photoFrame.SetActive(false);

        
    }

    

    IEnumerator CameraFlashEffect()
    {
        //play some audio
        cameraFlash.SetActive(true);
        yield return new WaitForSeconds(flashTime);
        cameraFlash.SetActive(false);
    }

    void RemovePhoto()
    {

        viewingPhoto = false;
        photoFrame.SetActive(false);
        //cameraUI true 
    }
}

1

There are 1 answers

0
Michael Urvan On

You never set viewingPhoto to false so that you can do it again, because I don't see RemovePhoto being called from anywhere.