0
# Asset Export and Conversion
1
2
Comprehensive export capabilities for converting Unity assets to standard formats. Includes format conversion, compression options, and platform-specific optimizations for textures, audio, meshes, and other asset types.
3
4
## Capabilities
5
6
### Texture Export and Conversion
7
8
Convert Unity textures to standard image formats with format detection and platform-specific handling.
9
10
```python { .api }
11
class Texture2DConverter:
12
"""
13
Texture format conversion and export utilities.
14
"""
15
16
@staticmethod
17
def get_image_from_texture2d(texture_2d: Texture2D, flip: bool = True) -> Image.Image:
18
"""
19
Convert Unity texture to PIL Image.
20
21
Parameters:
22
- texture_2d: Texture2D object
23
- flip: Whether to flip image vertically
24
25
Returns:
26
PIL.Image.Image: Converted image
27
"""
28
29
@staticmethod
30
def image_to_texture2d(img: Image.Image, target_format: int, platform: int = 0, platform_blob: Optional[List[int]] = None) -> Tuple[bytes, int]:
31
"""
32
Convert PIL Image to Unity texture format.
33
34
Parameters:
35
- img: PIL Image to convert
36
- target_format: Target texture format ID
37
- platform: Target platform
38
- platform_blob: Platform-specific data
39
40
Returns:
41
Tuple[bytes, int]: Texture data bytes and actual format used
42
"""
43
44
@staticmethod
45
def parse_image_data(image_data: Union[bytes, bytearray, memoryview], width: int, height: int, texture_format: Union[TextureFormat, int], version: Tuple[int, int, int, int], platform: Union[BuildTarget, int], platform_blob: Optional[List[int]] = None, flip: bool = True) -> Image.Image:
46
"""
47
Parse raw image data bytes to PIL Image.
48
49
Parameters:
50
- image_data: Raw texture data
51
- width: Image width in pixels
52
- height: Image height in pixels
53
- texture_format: Unity texture format
54
- version: Unity version tuple
55
- platform: Build target platform
56
- platform_blob: Platform-specific data
57
- flip: Whether to flip image vertically
58
59
Returns:
60
PIL.Image.Image: Parsed image
61
"""
62
```
63
64
### Audio Export and Conversion
65
66
Convert Unity audio clips to standard audio formats with support for various compression methods.
67
68
```python { .api }
69
class AudioClipConverter:
70
"""
71
Audio format conversion and export utilities.
72
"""
73
74
@staticmethod
75
def extract_audioclip_samples(audio: AudioClip, convert_pcm_float: bool = True) -> Dict[str, bytes]:
76
"""
77
Extract audio samples from AudioClip as WAV data.
78
79
Parameters:
80
- audio: AudioClip object
81
- convert_pcm_float: Whether to convert PCM float to int16
82
83
Returns:
84
Dict[str, bytes]: Dictionary mapping sample names to WAV file bytes
85
"""
86
87
@staticmethod
88
def dump_samples(clip: AudioClip, audio_data: bytes, convert_pcm_float: bool = True) -> Dict[str, bytes]:
89
"""
90
Extract samples from raw audio data.
91
92
Parameters:
93
- clip: AudioClip object for metadata
94
- audio_data: Raw audio data bytes
95
- convert_pcm_float: Whether to convert PCM float to int16
96
97
Returns:
98
Dict[str, bytes]: Dictionary mapping sample names to WAV file bytes
99
"""
100
101
@staticmethod
102
def subsound_to_wav(subsound, convert_pcm_float: bool = True) -> bytes:
103
"""
104
Convert FMOD subsound to WAV format.
105
106
Parameters:
107
- subsound: FMOD subsound object
108
- convert_pcm_float: Whether to convert PCM float to int16
109
110
Returns:
111
bytes: WAV audio data
112
"""
113
```
114
115
### Mesh Export
116
117
Export Unity mesh data to standard 3D formats.
118
119
```python { .api }
120
class MeshExporter:
121
"""
122
Mesh export utilities for 3D formats.
123
"""
124
125
@staticmethod
126
def export_mesh(m_Mesh: Mesh, format: str = "obj") -> str:
127
"""
128
Export mesh in specified format.
129
130
Parameters:
131
- m_Mesh: Mesh object
132
- format: Output format ("obj" only currently supported)
133
134
Returns:
135
str: Mesh data in specified format
136
"""
137
138
@staticmethod
139
def export_mesh_obj(mesh: Mesh, material_names: Optional[List[str]] = None) -> str:
140
"""
141
Export mesh as Wavefront OBJ format.
142
143
Parameters:
144
- mesh: Mesh object
145
- material_names: Optional list of material names
146
147
Returns:
148
str: OBJ format text data
149
"""
150
```
151
152
### Mesh Renderer Export
153
154
Export rendered meshes with material information.
155
156
```python { .api }
157
class MeshRendererExporter:
158
"""
159
Export meshes with rendering information.
160
"""
161
162
@staticmethod
163
def export_mesh_renderer(renderer: Renderer, export_dir: str) -> None:
164
"""
165
Export mesh renderer with materials to directory.
166
167
Parameters:
168
- renderer: Renderer object (MeshRenderer, SkinnedMeshRenderer)
169
- export_dir: Directory to export files to
170
"""
171
172
@staticmethod
173
def get_mesh(meshR: Renderer) -> Optional[Mesh]:
174
"""
175
Get mesh from renderer component.
176
177
Parameters:
178
- meshR: Renderer object
179
180
Returns:
181
Optional[Mesh]: Associated mesh object if found
182
"""
183
184
@staticmethod
185
def export_material(mat: Material) -> str:
186
"""
187
Export material as text representation.
188
189
Parameters:
190
- mat: Material object
191
192
Returns:
193
str: Material data as string
194
"""
195
```
196
197
### Sprite Processing
198
199
Extract and process Unity sprite assets with texture atlas support.
200
201
```python { .api }
202
class SpriteHelper:
203
"""
204
Sprite extraction and processing utilities.
205
"""
206
207
@staticmethod
208
def get_image_from_sprite(m_Sprite: Sprite) -> Image.Image:
209
"""
210
Extract sprite as PIL Image with alpha channel merging.
211
212
Parameters:
213
- m_Sprite: Sprite object
214
215
Returns:
216
PIL.Image.Image: Extracted sprite image with proper alpha
217
"""
218
219
@staticmethod
220
def get_image(sprite: Sprite, texture: PPtr[Texture2D], alpha_texture: Optional[PPtr[Texture2D]]) -> Image.Image:
221
"""
222
Get sprite image from texture with optional alpha texture.
223
224
Parameters:
225
- sprite: Sprite object
226
- texture: Main texture reference
227
- alpha_texture: Optional alpha texture reference
228
229
Returns:
230
PIL.Image.Image: Sprite image with alpha channel
231
"""
232
233
@staticmethod
234
def mask_sprite(m_Sprite: Sprite, mesh: MeshHandler, sprite_image: Image.Image) -> Image.Image:
235
"""
236
Apply mesh mask to sprite image.
237
238
Parameters:
239
- m_Sprite: Sprite object
240
- mesh: Mesh handler for masking
241
- sprite_image: Source sprite image
242
243
Returns:
244
PIL.Image.Image: Masked sprite image
245
"""
246
```
247
248
### Shader Conversion
249
250
Convert Unity shaders to readable formats.
251
252
```python { .api }
253
class ShaderConverter:
254
"""
255
Shader code conversion and export utilities.
256
"""
257
258
@staticmethod
259
def export_shader_code(shader):
260
"""
261
Export shader source code.
262
263
Parameters:
264
- shader: Shader object
265
266
Returns:
267
str: Readable shader code
268
"""
269
270
@staticmethod
271
def export_shader_properties(shader):
272
"""
273
Export shader properties and parameters.
274
275
Parameters:
276
- shader: Shader object
277
278
Returns:
279
dict: Shader properties and metadata
280
"""
281
```
282
283
## Usage Examples
284
285
### Exporting Textures
286
287
```python
288
import UnityPy
289
from UnityPy.export import Texture2DConverter
290
291
env = UnityPy.load("texture_assets/")
292
293
for obj in env.objects:
294
if obj.type.name == "Texture2D":
295
texture = obj.read()
296
297
# Method 1: Use built-in save method
298
texture.save(f"exports/{texture.name}.png")
299
300
# Method 2: Use converter for more control
301
image = Texture2DConverter.export_PIL(texture)
302
image.save(f"exports/{texture.name}_converted.png")
303
304
# Method 3: Export as bytes
305
png_data = Texture2DConverter.export_bytes(texture, "PNG")
306
with open(f"exports/{texture.name}.png", "wb") as f:
307
f.write(png_data)
308
309
# Export in different formats
310
jpeg_data = Texture2DConverter.export_bytes(texture, "JPEG")
311
with open(f"exports/{texture.name}.jpg", "wb") as f:
312
f.write(jpeg_data)
313
```
314
315
### Processing Audio Files
316
317
```python
318
import UnityPy
319
from UnityPy.export import AudioClipConverter
320
import numpy as np
321
322
env = UnityPy.load("audio_assets/")
323
324
for obj in env.objects:
325
if obj.type.name == "AudioClip":
326
audio = obj.read()
327
328
# Method 1: Use built-in save method
329
audio.save(f"exports/{audio.name}.wav")
330
331
# Method 2: Use converter
332
wav_data = AudioClipConverter.export_wav(audio)
333
with open(f"exports/{audio.name}_converted.wav", "wb") as f:
334
f.write(wav_data)
335
336
# Get raw audio samples for processing
337
samples = AudioClipConverter.get_samples(audio)
338
print(f"Audio samples shape: {samples.shape}")
339
print(f"Sample rate: {audio.m_Frequency}")
340
341
# Process samples (example: reduce volume)
342
processed_samples = samples * 0.5
343
344
# Export OGG format
345
try:
346
ogg_data = AudioClipConverter.export_ogg(audio)
347
with open(f"exports/{audio.name}.ogg", "wb") as f:
348
f.write(ogg_data)
349
except Exception as e:
350
print(f"OGG export failed: {e}")
351
```
352
353
### Exporting Meshes
354
355
```python
356
import UnityPy
357
from UnityPy.export import MeshExporter
358
359
env = UnityPy.load("mesh_assets/")
360
361
for obj in env.objects:
362
if obj.type.name == "Mesh":
363
mesh = obj.read()
364
365
# Export as OBJ format
366
obj_data = MeshExporter.export_obj(mesh)
367
with open(f"exports/{mesh.name}.obj", "w") as f:
368
f.write(obj_data)
369
370
# Export as PLY format
371
ply_data = MeshExporter.export_ply(mesh)
372
with open(f"exports/{mesh.name}.ply", "w") as f:
373
f.write(ply_data)
374
375
# Export just vertices for analysis
376
vertices = MeshExporter.export_vertices(mesh)
377
print(f"Mesh {mesh.name}: {len(vertices)} vertices")
378
379
# Export vertex data as CSV
380
import csv
381
with open(f"exports/{mesh.name}_vertices.csv", "w", newline="") as f:
382
writer = csv.writer(f)
383
writer.writerow(["x", "y", "z"])
384
writer.writerows(vertices)
385
```
386
387
### Extracting Sprites
388
389
```python
390
import UnityPy
391
from UnityPy.export import SpriteHelper
392
393
env = UnityPy.load("sprite_assets/")
394
395
sprites = []
396
textures = {}
397
398
# First, collect all textures
399
for obj in env.objects:
400
if obj.type.name == "Texture2D":
401
texture = obj.read()
402
textures[obj.path_id] = texture
403
elif obj.type.name == "Sprite":
404
sprites.append(obj)
405
406
# Export sprites
407
for sprite_obj in sprites:
408
sprite = sprite_obj.read()
409
410
# Method 1: Direct sprite export
411
sprite_image = SpriteHelper.export_sprite(sprite)
412
sprite_image.save(f"exports/{sprite.name}.png")
413
414
# Method 2: Manual cropping from texture
415
if sprite.texture.path_id in textures:
416
source_texture = textures[sprite.texture.path_id]
417
cropped = SpriteHelper.crop_sprite_from_texture(source_texture, sprite)
418
cropped.save(f"exports/{sprite.name}_cropped.png")
419
420
# Export as bytes
421
sprite_bytes = SpriteHelper.export_sprite_bytes(sprite, "PNG")
422
with open(f"exports/{sprite.name}_bytes.png", "wb") as f:
423
f.write(sprite_bytes)
424
```
425
426
### Batch Export Operations
427
428
```python
429
import UnityPy
430
import os
431
from pathlib import Path
432
433
def export_all_assets(asset_path, output_dir):
434
"""Export all supported assets from a Unity project."""
435
436
env = UnityPy.load(asset_path)
437
output_path = Path(output_dir)
438
439
# Create output directories
440
(output_path / "textures").mkdir(parents=True, exist_ok=True)
441
(output_path / "audio").mkdir(parents=True, exist_ok=True)
442
(output_path / "meshes").mkdir(parents=True, exist_ok=True)
443
(output_path / "sprites").mkdir(parents=True, exist_ok=True)
444
445
export_counts = {"textures": 0, "audio": 0, "meshes": 0, "sprites": 0}
446
447
for obj in env.objects:
448
try:
449
if obj.type.name == "Texture2D":
450
texture = obj.read()
451
safe_name = "".join(c for c in texture.name if c.isalnum() or c in "._-")
452
texture.save(output_path / "textures" / f"{safe_name}.png")
453
export_counts["textures"] += 1
454
455
elif obj.type.name == "AudioClip":
456
audio = obj.read()
457
safe_name = "".join(c for c in audio.name if c.isalnum() or c in "._-")
458
audio.save(output_path / "audio" / f"{safe_name}.wav")
459
export_counts["audio"] += 1
460
461
elif obj.type.name == "Mesh":
462
mesh = obj.read()
463
safe_name = "".join(c for c in mesh.name if c.isalnum() or c in "._-")
464
obj_data = MeshExporter.export_obj(mesh)
465
with open(output_path / "meshes" / f"{safe_name}.obj", "w") as f:
466
f.write(obj_data)
467
export_counts["meshes"] += 1
468
469
elif obj.type.name == "Sprite":
470
sprite = obj.read()
471
safe_name = "".join(c for c in sprite.name if c.isalnum() or c in "._-")
472
sprite_image = SpriteHelper.export_sprite(sprite)
473
sprite_image.save(output_path / "sprites" / f"{safe_name}.png")
474
export_counts["sprites"] += 1
475
476
except Exception as e:
477
print(f"Failed to export {obj.type.name}: {e}")
478
479
print(f"Export complete:")
480
for asset_type, count in export_counts.items():
481
print(f" {asset_type}: {count}")
482
483
# Usage
484
export_all_assets("game_assets/", "extracted_assets/")
485
```
486
487
### Advanced Format Conversion
488
489
```python
490
import UnityPy
491
from UnityPy.export import Texture2DConverter
492
from PIL import Image
493
494
env = UnityPy.load("texture_assets/")
495
496
for obj in env.objects:
497
if obj.type.name == "Texture2D":
498
texture = obj.read()
499
500
# Get original format info
501
print(f"Original format: {texture.m_TextureFormat}")
502
print(f"Size: {texture.m_Width}x{texture.m_Height}")
503
504
# Convert to PIL for processing
505
image = Texture2DConverter.export_PIL(texture)
506
507
# Apply processing
508
if image.mode == "RGBA":
509
# Convert RGBA to RGB with white background
510
rgb_image = Image.new("RGB", image.size, (255, 255, 255))
511
rgb_image.paste(image, mask=image.split()[-1]) # Use alpha as mask
512
513
# Save processed version
514
rgb_image.save(f"exports/{texture.name}_rgb.jpg", quality=95)
515
516
# Create thumbnail
517
thumbnail = image.copy()
518
thumbnail.thumbnail((128, 128), Image.LANCZOS)
519
thumbnail.save(f"exports/{texture.name}_thumb.png")
520
521
# Export multiple formats
522
formats = [
523
("PNG", "png"),
524
("JPEG", "jpg"),
525
("WEBP", "webp")
526
]
527
528
for format_name, ext in formats:
529
try:
530
converted_bytes = Texture2DConverter.export_bytes(texture, format_name)
531
with open(f"exports/{texture.name}.{ext}", "wb") as f:
532
f.write(converted_bytes)
533
except Exception as e:
534
print(f"Failed to convert to {format_name}: {e}")
535
```