привет у меня есть вот такой скрипт на unity который из pdf делает картинки но делает…
- User
привет у меня есть вот такой скрипт на unity который из pdf делает картинки но делает это очень долго, как мне сделать так чтобы это было быстрее ? public class PdfFilesUI : MonoBehaviour { private const string PathName = "/StreamingAssets/PDF/Training"; private const string FileExtension = "*.pdf"; private const string PathConverter = "/../Converter/pdf2img.exe"; private const string PathImage = " pageRight.png "; private const string PathImageFull = "/../pageRight.png";
[SerializeField] private Transform _contentButton; [SerializeField] private Transform _contentImage; [SerializeField] private PDFbutton _buttonPrefab; [SerializeField] private Image _imagePrefab; [SerializeField] private ScrollRect _scrollRect; private string pdfConverterPath; private Dictionary<Button, Image[]> buttonToImagesMapping = new Dictionary<Button, Image[]>(); private List<Image[]> allImageGroups = new List<Image[]>(); public void Initialize() { pdfConverterPath = Application.dataPath + PathConverter; FindPdfFiles(); } private void FindPdfFiles() { var folderPath = Application.dataPath + PathName; var pdfFiles = Directory.GetFiles(folderPath, FileExtension, SearchOption.AllDirectories); foreach (string file in pdfFiles) { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); var button = Instantiate(_buttonPrefab, _contentButton); button.Initialized(fileNameWithoutExtension, file); var pageCount = 0; using (PdfReader reader = new PdfReader(file)) { pageCount = reader.NumberOfPages; } var imageGroup = new Image[pageCount]; for (int pageNumber = 0; pageNumber < pageCount; pageNumber++) { CallExternalProcess(pdfConverterPath, file + PathImage + (pageNumber).ToString()); var image = ApplyTextureToUI(Application.dataPath + PathImageFull); imageGroup[pageNumber] = image; } allImageGroups.Add(imageGroup); button.Button.onClick.AddListener(() => AllImagesOn(imageGroup)); buttonToImagesMapping[button.Button] = imageGroup; } AllImagesOff(); } public void AllImagesOff() { foreach (Image[] images in allImageGroups) { foreach (var image in images) { image.gameObject.Deactive(); } } } public void AllImagesOn(Image[] imageGroup) { AllImagesOff(); foreach (Image image in imageGroup) { image.gameObject.Active(); } _scrollRect.verticalNormalizedPosition = 1; } public Texture2D LoadPNG(string filePath) { Texture2D texture = null; if (File.Exists(filePath)) { var fileData = File.ReadAllBytes(filePath); texture = new Texture2D(2, 2); texture.LoadImage(fileData); } return texture; } public Image ApplyTextureToUI(string filePath) { var texture = LoadPNG(filePath); if (texture != null) { var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); var image = Instantiate(_imagePrefab, _contentImage); image.sprite = sprite; return image; } return null; } public void CallExternalProcess(string processPath, string arguments) { var myProcess = new Process(); myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; myProcess.StartInfo.CreateNoWindow = true; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.FileName = processPath; myProcess.StartInfo.Arguments = arguments; myProcess.EnableRaisingEvents = true; try { myProcess.Start(); } catch (InvalidOperationException ex) { UnityEngine.Debug.LogError(ex); } myProcess.WaitForExit(); var ExitCode = myProcess.ExitCode; } } - Assistant
Для ускорения работы вашего скрипта на Unity, который преобразует PDF в картинки, существует несколько способов. Основное замедление, вероятно, связано с вызовом внешнего процесса
pdf2img.exeдля каждой страницы PDF индивидуально, что может быть довольно ресурсоемкой операцией. Вот несколько предложений, как можно оптимизировать процесс: - User
можешь ли изменить код чтобы работало все параллельно с использованием System.Threading.Tasks для обработки каждого файла
- Assistant
- User
вышла такая ошибка UnityException: get_dataPath can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UI.PdfFilesUI+<>c__DisplayClass15_1.b__1 () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:80) System.Threading.Tasks.Task`1[TResult].InnerInvoke () (at :0) System.Threading.Tasks.Task.Execute () (at :0) --- End of stack trace from previous location where exception was thrown --- UI.PdfFilesUI.ProcessPdfFileAsync (System.String file) (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:84) UI.PdfFilesUI.FindPdfFilesAsync () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:57) UI.PdfFilesUI.Initialize () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:42) System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) (at :0) UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UnitySynchronizationContext.Exec () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <685c48cf8f0b48abb797275c046dda6a>:0)
- Assistant
Ошибка, которую вы видите, указывает на то, что вы пытаетесь использовать
Application.dataPathвне основного потока Unity. Конкретно, это происходит из-за использования этого вызова в асинхронной задаче. В Unity доступ к определенным функциям и свойствам, включаяApplication.dataPath, ограничен основным потоком из-за потокобезопасности.Чтобы решить эту проблему, вам нужно заранее сохранить значение в переменную в основном потоке, а затем использовать эту переменную в асинхронной задаче. Вот исправленная часть кода:
- User
теперь такая ошибка Exception: UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene. PimDeWitte.UnityMainThreadDispatcher.UnityMainThreadDispatcher.Instance () (at Assets/Scripts/UnityMainThreadDispatcher.cs:114) UI.PdfFilesUI.ProcessPdfFileAsync (System.String file) (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:95) UI.PdfFilesUI.FindPdfFilesAsync () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:59) UI.PdfFilesUI.Initialize () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:44) System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) (at :0) UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UnitySynchronizationContext.Exec () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <685c48cf8f0b48abb797275c046dda6a>:0)
- Assistant
Ошибка указывает, что в вашей сцене отсутствует объект
UnityMainThreadDispatcher, необходимый для работы с основным потоком Unity из асинхронных задач.UnityMainThreadDispatcher— это компонент или класс, который позволяет асинхронным задачам безопасно вызывать методы в основном потоке Unity, что важно для операций, которые должны выполняться в нём (например, работа с элементами пользовательского интерфейса). - User
теперь такая проблема NullReferenceException: Object reference not set to an instance of an object UI.PdfFilesUI.AllImagesOff () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:143) UI.PdfFilesUI.AllImagesOn (UnityEngine.UI.Image[] imageGroup) (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:150) UI.PdfFilesUI+<>c__DisplayClass16_0.b__2 () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:98) UnityEngine.Events.InvokableCall.Invoke () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.Events.UnityEvent.Invoke () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70) UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114) UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57) UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272) UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:501)
- Assistant
- User
теперь такая проблема UnityException: SupportsTextureFormatNative can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEngine.SystemInfo.SupportsTextureFormat (UnityEngine.TextureFormat format) (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.Texture.ValidateFormat (UnityEngine.TextureFormat format) (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.Texture2D.ValidateFormat (UnityEngine.TextureFormat format, System.Int32 width, System.Int32 height) (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.Texture2D..ctor (System.Int32 width, System.Int32 height, UnityEngine.TextureFormat textureFormat, System.Int32 mipCount, System.Boolean linear, System.IntPtr nativeTex) (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.Texture2D..ctor (System.Int32 width, System.Int32 height) (at <685c48cf8f0b48abb797275c046dda6a>:0) UI.PdfFilesUI.LoadPNG (System.String filePath) (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:178) UI.PdfFilesUI.ApplyTextureToUI (System.String filePath) (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:187) UI.PdfFilesUI+<>c__DisplayClass17_2.b__1 () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:86) System.Threading.Tasks.Task`1[TResult].InnerInvoke () (at :0) System.Threading.Tasks.Task.Execute () (at :0) --- End of stack trace from previous location where exception was thrown --- UI.PdfFilesUI.ProcessPdfFileAsync (System.String file) (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:90) UI.PdfFilesUI.FindPdfFilesAsync () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:61) UI.PdfFilesUI.Initialize () (at Assets/Scripts/UI/PDF/PdfFilesUI.cs:46) System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) (at :0) UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UnitySynchronizationContext.Exec () (at <685c48cf8f0b48abb797275c046dda6a>:0) UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <685c48cf8f0b48abb797275c046dda6a>:0)
- Assistant
Ошибка
UnityException: SupportsTextureFormatNative can only be called from the main thread.указывает на то, что вы пытаетесь создать текстуру в неосновном потоке. В Unity, создание и модификация объектов , включая текстуры, должны производиться в основном потоке. Это ограничение существует, потому что движок Unity не является потокобезопасным. - User
можешь написать код чтобы не было проблем с логикой обработки файлов
- Assistant