Skip to content
🤔prompts chat🧠
🔍
question:Unsupported texture format - Texture2D::EncodeTo functions do not support compressed texture formats. UnityEngine.ImageConversion:EncodeToEXR (UnityEngine.Texture2D) NewBehaviourScript2:Start () (at Assets/Scripts/NewBehaviourScript2.cs:36) ArgumentNullException: Value cannot be null. Parameter name: bytes System.IO.File.WriteAllBytes (System.String path, System.Byte[] bytes) (at <787acc3c9a4c471ba7d971300105af24>:0) NewBehaviourScript2.Start () (at Assets/Scripts/NewBehaviourScript2.cs:37) .

answer:Если функции `EncodeToPNG()`, `EncodeToJPG()`, `EncodeToEXR()` или `EncodeToTGA()` не поддерживаются для сжатых текстурных форматов, тогда вам может потребоваться использовать другие методы для сохранения текстур. В этом случае вы можете попробовать использовать функцию `Graphics.CopyTexture()` для создания некомпрессированной копии текстуры и сохранить ее как PNG или JPEG. Вот обновленный код с использованием `Graphics.CopyTexture()`: ```csharp void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); } GameObject lastPrefab = bundle.LoadAsset<GameObject>(assetNames[assetNames.Length - 1]); GameObject instantiatedPrefab = Instantiate(lastPrefab, imageHolder.transform); Image[] images = instantiatedPrefab.GetComponentsInChildren<Image>(); foreach (Image image in images) { Sprite sprite = image.sprite; if (sprite != null) { Texture2D sourceTexture = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, TextureFormat.RGBA32, false); Graphics.CopyTexture(sprite.texture, 0, 0, sourceTexture, 0, 0); byte[] bytes = sourceTexture.EncodeToPNG(); File.WriteAllBytes(savePath + image.name + ".png", bytes); } } } else { Debug.Log("None of bundle"); } } ``` В этом коде мы используем `Graphics.CopyTexture()` для создания нового экземпляра `Texture2D`, некомпрессированной копии текстуры спрайта. Затем мы используем `EncodeToPNG()` для кодирования текстуры в формат PNG и сохраняем полученные байты в файл. При использовании этого подхода учтите, что сохраняемые текстуры могут не иметь прозрачности. Если вам нужна прозрачность, то вам может потребоваться использовать другие форматы файлов или другие методы сохранения, которые поддерживают сжатые текстурные форматы.

question:Graphics.CopyTexture called with mismatching data size (src (996x600 with format 96 -> 298800 bytes) dst (996x600 with format 4 -> 2390400 bytes)) UnityEngine.Graphics:CopyTexture (UnityEngine.Texture,int,int,UnityEngine.Texture,int,int) NewBehaviourScript2:Start () (at Assets/Scripts/NewBehaviourScript2.cs:32)

answer:Ошибка "Graphics.CopyTexture called with mismatching data size" возникает потому, что размеры и формат исходной текстуры и целевой текстуры, которую вы пытаетесь создать с помощью `Graphics.CopyTexture()`, не совпадают. В этом случае вам нужно создать новую текстуру с соответствующими размерами и форматом, а затем скопировать данные с исходной текстуры в новую текстуру. Вот обновленный код с исправленной ошибкой: ```csharp void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); } GameObject lastPrefab = bundle.LoadAsset<GameObject>(assetNames[assetNames.Length - 1]); GameObject instantiatedPrefab = Instantiate(lastPrefab, imageHolder.transform); Image[] images = instantiatedPrefab.GetComponentsInChildren<Image>(); foreach (Image image in images) { Sprite sprite = image.sprite; if (sprite != null) { Texture2D sourceTexture = sprite.texture; Texture2D targetTexture = new Texture2D(sourceTexture.width, sourceTexture.height, TextureFormat.RGBA32, false); Color[] pixels = sourceTexture.GetPixels(); targetTexture.SetPixels(pixels); targetTexture.Apply(); byte[] bytes = targetTexture.EncodeToPNG(); File.WriteAllBytes(savePath + image.name + ".png", bytes); } } } else { Debug.Log("None of bundle"); } } ``` В этом коде мы создаем новую текстуру `targetTexture` с размерами исходной текстуры `sourceTexture`, а затем копируем пиксели из `sourceTexture` в `targetTexture` с помощью `GetPixels()` и `SetPixels()`. Затем мы применяем изменения с `Apply()` и сохраняем новую текстуру в файл. Надеюсь, это поможет вам исправить ошибку и успешно скопировать текстуры.

question:ArgumentException: Texture2D.GetPixels: texture data is either not readable, corrupted or does not exist. (Texture 'intro_bg') UnityEngine.Texture2D.GetPixels (System.Int32 miplevel) (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0) UnityEngine.Texture2D.GetPixels () (at <3b24cc7fa9794ed8ab04312c53e6dedd>:0) NewBehaviourScript2.Start () (at Assets/Scripts/NewBehaviourScript2.cs:34)

answer:Ошибка "Texture2D.GetPixels: texture data is either not readable, corrupted or does not exist." возникает из-за того, что данные текстуры, на которую вы пытаетесь обратиться с помощью `GetPixels()`, не доступны для чтения. Если у вас нет доступа к исходным текстурам и не можете изменить их настройки импорта, вам может потребоваться использовать другой метод для получения пикселей из текстуры. Вместо использования `GetPixels()`, вы можете попробовать использовать функцию `RenderTexture.active` и метод `ReadPixels()` для создания временного RenderTexture и чтения пикселей из него. Затем вы можете используйте `Texture2D.SetPixels()` для установки пикселей в новую текстуру. Вот обновленный код, который решит задачу: ```csharp void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); } GameObject lastPrefab = bundle.LoadAsset<GameObject>(assetNames[assetNames.Length - 1]); GameObject instantiatedPrefab = Instantiate(lastPrefab, imageHolder.transform); Image[] images = instantiatedPrefab.GetComponentsInChildren<Image>(); foreach (Image image in images) { Sprite sprite = image.sprite; if (sprite != null) { RenderTexture renderTexture = new RenderTexture(sprite.texture.width, sprite.texture.height, 32); Graphics.Blit(sprite.texture, renderTexture); Texture2D texture = new Texture2D(sprite.texture.width, sprite.texture.height, TextureFormat.RGBA32, false); RenderTexture.active = renderTexture; texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); RenderTexture.active = null; Destroy(renderTexture); byte[] bytes = texture.EncodeToPNG(); File.WriteAllBytes(savePath + image.name + ".png", bytes); } } } else { Debug.Log("None of bundle"); } } ``` В этом коде мы создаем временный `RenderTexture` с теми же размерами, что и исходная текстура спрайта. Затем мы используем `Graphics.Blit()` для копирования данных из исходной текстуры спрайта в `RenderTexture`. Затем мы создаем новую текстуру `texture` с теми же размерами и форматом, что и исходная текстура, и используем `ReadPixels()` для чтения пикселей из `RenderTexture`. После получения пикселей мы удаляем `RenderTexture` и сохраняем пиксели в файл, как и раньше. Надеюсь, это поможет вам исправить ошибку и успешно получить пиксели из текстуры.

question:как сделать, чтобы эта строка: Image[] images = instantiatedPrefab.GetComponentsInChildren<Image>(); выбирала абсолютно все объекты в префабе, то есть все дочерние дочерних дочерних и так далее

answer:Чтобы `Get

Released under the stanford License.

has loaded