0

I'm really new to Unity and C# and I want to take a screenshot of a canvas in my scene with the press of a button, but keep getting an NullReferenceException error. I got this code from another stack overflow question, but I'm not entirely sure If I'm even coding this right. I would love any help possible!

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

public class ScreenShot : MonoBehaviour
{
    string pathToYourFile = @"C:\Unity Projects\chem sample";
    string fileName = "screenshot";
    string fileType = ".png";

    private Button button;

 
    private int currentScreenShot
    {
        get => PlayerPrefs.GetInt("ScreenShot");
        set => PlayerPrefs.SetInt("ScreenShot", value);
    } 

    private void Update()
    {
        button.onClick.AddListener(TaskOnClick);
    }

    private void TaskOnClick()
    {
        UnityEngine.ScreenCapture.CaptureScreenshot(pathToYourFile + fileName + currentScreenShot + fileType);
        currentScreenShot++;
    }
}
RW01
  • 1
  • Is there a very special reason btw why you would add a listener to a button event **each and every frame**? Makes little sense ;) – derHugo Dec 28 '20 at 21:03
  • oh I just saw it on a Unity tutorial page, so I included it. – RW01 Dec 29 '20 at 02:48
  • Doubt that a lot ... As soon as you click the button your listener method would be called thousands of times ^^ – derHugo Dec 29 '20 at 08:00

0 Answers0