Take screenshot from android build

Hello,

I want to add to my app a button to take a screenshot of the game with only some UI. I’m trying with this script, but when I try to take the screenshot, it doesn’t take for real; obviously, it doesn’t show me the UI deactivated.

Do you have any solutions? It could be great if they work for iOS and Android.

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class TakePhoto : MonoBehaviour
{
    public string title;
    public GameObject uiToDeactive;
    public GameObject backButtonDeactive;

    private void Start()
    {
        title = ButtonScene.ogg.GetComponent<ItemAccess>().text;
    }

    public void Capture()
    {
        StartCoroutine(Screenshot());
    }

    private IEnumerator Screenshot()
    {
        yield return new WaitForEndOfFrame();
        int width = Screen.width;
        int height = Screen.height;
        Texture2D screenshotTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);
        Rect rect = new Rect(0, 0, width, height);
        screenshotTexture.ReadPixels(rect, 0, 0);
        screenshotTexture.Apply();
        byte[] byteArray = screenshotTexture.EncodeToJPG();
        string filename = "/AppName_" + title + ".png ";
        System.IO.File.WriteAllBytes(GetAndroidExternalStoragePath() + filename, byteArray);
        uiToDeactive.SetActive(true);
        backButtonDeactive.SetActive(true);
    }

    private string GetAndroidExternalStoragePath()
    {
        if (Application.platform != RuntimePlatform.Android)
            return Application.persistentDataPath;

        var jc = new AndroidJavaClass("android.os.Environment");
        var path = jc.CallStatic<AndroidJavaObject>("getExternalStoragePublicDirectory",
            jc.GetStatic<string>("DIRECTORY_DCIM"))
            .Call<string>("getAbsolutePath");
        return path;
    }
}

Take a look at this: How can I take screenshot in an unity application and save it to device's gallery (for android and ios both)? - Questions & Answers - Unity Discussions