Unity中SetActive(false)后如何重启IEnumerator?拍照功能失效求助
问题解决:拍照功能无法重复触发
核心问题是viewingPhoto标记在拍照后始终为true,导致后续按空格键时,!viewingPhoto的条件不成立,无法再次触发拍照流程。另外ShowPhoto方法里使用了yield return但方法类型是void,这是语法错误,会导致延迟逻辑完全不执行。
具体修改步骤:
- 将
ShowPhoto方法改为IEnumerator类型,适配内部的延迟等待逻辑 - 在拍照展示流程结束后,手动重置
viewingPhoto为false - 调用
ShowPhoto时必须通过StartCoroutine启动协程,确保延迟逻辑生效
修正后的完整代码:
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() { 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协程并等待其完成 yield return StartCoroutine(ShowPhoto()); } // 修改为IEnumerator类型,支持yield延迟 private IEnumerator ShowPhoto() { 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()); // 等待2秒后隐藏相框并重置标记 yield return new WaitForSeconds(2); photoFrame.SetActive(false); viewingPhoto = false; } IEnumerator CameraFlashEffect() { cameraFlash.SetActive(true); yield return new WaitForSeconds(flashTime); cameraFlash.SetActive(false); } }
关键修改说明:
ShowPhoto方法改为IEnumerator,让内部的yield return new WaitForSeconds(2)能正常执行延迟- 在
CapturePhoto中通过yield return StartCoroutine(ShowPhoto())等待整个展示流程完成 - 在延迟结束后直接设置
viewingPhoto = false,重置标记以允许下一次触发拍照
内容的提问来源于stack exchange,提问作者Moonixe
相关产品推荐
相关产品推荐

