我正在尝试在游戏中创建图片功能,并且我希望图片框在几秒钟后消失。完成此操作后,当我尝试再次拍照时,它不起作用。我对 C# 很陌生,希望得到一些帮助 ^^;
按空格键后,会出现一张图片,几秒钟后就会消失。如果再次按空格键,则会重复该操作。该动作不会重复。
这是代码:
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
}
}
您永远不会将viewingPhoto设置为false,以便您可以再次执行此操作,因为我没有看到从任何地方调用RemovePhoto。