Unity中工作代码的突然错误/bug



正如标题所示,我在代码中遇到了一个意想不到的错误,在我试图编辑或更改一行代码之前,它一直工作正常。不断出现的错误消息是"NullReferenceException:对象引用未设置为对象的实例,";这是许多人的共同问题。

导致错误的代码行是第23行。

1  using System;
2  using System.IO;
3  using UnityEngine;
4  using UnityEngine.Rendering;
5 
6  public class SaveImage : MonoBehaviour {
7 
8     public static SaveImage Instance { get; private set; }
9 
10    [SerializeField] private Camera screenshotCamera;
11 
12     private Action<Texture2D> onScreenshotTaken;
13 
14     private void Awake() {
15         Instance = this;
16         RenderPipelineManager.endFrameRendering += RenderPipelineManager_endFrameRendering;
17     }
18 
19     private void RenderPipelineManager_endFrameRendering(ScriptableRenderContext arg1, Camera[] arg2) {
20         if (onScreenshotTaken != null) {
21             RenderTexture renderTexture = screenshotCamera.targetTexture;
22 
23             Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
24             Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
25             renderResult.ReadPixels(rect, 0, 0);
26             renderResult.Apply();
27 
28             RenderTexture.ReleaseTemporary(renderTexture);
29             screenshotCamera.targetTexture = null;
30 
31             onScreenshotTaken(renderResult);
32             onScreenshotTaken = null;
33 
34             Destroy(renderResult);
35         }
36     }
37 
38     public void Save() {
39 
40        TakeScreenshot(Screen.width, Screen.height, (Texture2D screenshotTexture) => {
41             string pathfile = Application.persistentDataPath + "/NGallery/ImageData.png";
42             string imagestorage = pathfile;
43             byte[] screenshotByteArray = screenshotTexture.EncodeToPNG();
44             File.WriteAllBytes(imagestorage, screenshotByteArray);
45         });
46     }
47 
48     private void TakeScreenshot(int width, int height, Action<Texture2D> onScreenshotTaken) {
49         screenshotCamera.targetTexture = RenderTexture.GetTemporary(width, height, 16);
50         this.onScreenshotTaken = onScreenshotTaken;
51     }
52 }

我尝试了什么,它的结果:

  • 尝试加载我的旧Unity项目。-工作正常
  • 试图从头开始创建一切。-错误发生
  • 尝试复制和粘贴我的旧Unity项目。-错误发生
  • 尝试在新的Unity项目中调试renderTextureDebug.Log(renderTexture)说它是空的
  • 尝试调试旧Unity项目中的renderTextureDebug.Log(renderTexture)说它不是空的并且工作。

所以,不知何故,我已经解决了这个问题,它必须与文件目录中保存的图像(我不知道它是如何相关的,但我确信这是导致问题,我甚至试图仔细检查,如果它真的是文件目录)。所以,我所做的是,我在Line 41 Directory.CreateDirectory(Application.persistentDataPath + "/NGallery");中添加了一行,向下移动string pathfile = Application.persistentDataPath + "/NGallery/ImageData.png";到第42行。然后不再出现错误。

相关内容

  • 没有找到相关文章

最新更新