npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

unity-asset-reader

v2.0.0

Published

Browser-first Unity AssetBundle parser: isomorphic, synchronous, zero platform dependencies.

Readme

unity-asset-reader

Read Unity AssetBundles and SerializedFiles in JavaScript. A SerializedFile is the file that holds Unity's objects: a node inside a bundle, or a player build's .assets file. Give this package the bytes, and it unpacks the container, lists every object inside and reads each one into plain JavaScript data.

It is browser-first and runs the same way in browsers, Web Workers and Node.js. It opens these containers: UnityFS, UnityWeb, UnityRaw, UnityWebData and gzip.

  • Isomorphic: runs anywhere. It has no node:* import and no DOM. Input is a Uint8Array, or anything open() can fetch or read (a URL, a Response, a Blob).
  • Synchronous parsing. load() returns the unpacked files straight away. Only open() is async, because it fetches or reads the bytes first and unwraps gzip, which the platform's DecompressionStream inflates asynchronously. Nothing in the parse path is async (see Run it in a Worker).
  • No WASM. Its only dependency is a small, pure-JS LZMA decompressor, lzma1. gzip and zlib use the platform's DecompressionStream.
  • 64-bit values are always bigint, whatever their size (see 64-bit values and JSON).

It is a TypeScript port of AssetStudio, and it is tested against UnityPy on bundles built with our own Unity projects.

| You want to | Install | |---|---| | Unpack bundles and read objects: text, scripts' data, raw audio, video and font bytes | unity-asset-reader (this package) | | Get textures and sprites as RGBA pixels, too | add unity-asset-reader-texture | | Load files and folders from disk in Node.js | add unity-asset-reader-node | | Export meshes as OBJ or glTF | add unity-asset-reader-mesh | | Convert audio clips to WAV (or Vorbis clips to Ogg) | add unity-asset-reader-audio | | Export Spine skeletons (data, atlas, page textures) | add unity-asset-reader-spine | | Write shaders as AssetStudio's inspection text (GLSL, Metal, SPIR-V) | add unity-asset-reader-shader | | Decode animation clips into curves, or export an animated scene to glTF (.glb) | add unity-asset-reader-animation |

Install

npm install unity-asset-reader

Types are included. For Node.js versions, CommonJS and bundlers, see Requirements and the Bundler Guide.

Quick start

Load a bundle, list what is in it, and read the assets you care about:

import { load, open } from "unity-asset-reader";

const env = load(bundleBytes);                          // a Uint8Array or an ArrayBuffer
const web = await open("https://cdn.example.com/ui.bundle"); // or a URL, Request, Response, Blob / File

for (const asset of env.assets()) {
  console.log(asset.type, asset.name, asset.path); // "TextAsset" "hello" "assets/text/hello.txt"

  switch (asset.type) {
    case "TextAsset":
      console.log(asset.data.text, asset.data.bytes.length); // `data` is a TextAssetFields here
      break;
    case "Texture2D":
      console.log(asset.data.format, asset.data.width, asset.data.mipCount); // a Texture2DFields
      break;
    case "MonoBehaviour":
      console.log(asset.data.script, asset.data.fields); // the MonoScript pointer, the script's fields
      break;
    case "Other":
      console.log(asset.typeName, asset.data); // "Camera" { m_GameObject: {...}, ... } from the type tree
  }
}

const icon = env.get("Assets/UI/Icon.png"); // by the path the asset had in the project
for (const sprite of env.assets("Sprite")) sprite.data.rect; // filtered and typed

What the example uses:

  • load() takes bytes and returns an Env at once. open() fetches or reads the bytes first, and unwraps a gzip-wrapped file.
  • env.assets() yields every object as an Asset. A switch (asset.type) narrows asset.data to that class's shape.
  • "Other" is every class without a hand-written reader. Its data comes from the object's type tree: the description of each class's fields that Unity stores in the file, by default.
  • env.get(path) finds an asset by the path it had in the Unity project.

The sections below cover each step in more detail.

Common tasks

Load bytes, files or URLs

load(input, options?) takes one file or an array of files. Each file is bytes or { name, data }.

  • A file without a name is called input 0, input 1, ... after its place.
  • That is fine for a bundle, whose contents carry their own names.
  • Give loose files (a .resS, a sharedassets0.assets) their real names: resources and pointers between files are found by name.

await open(source) gets the bytes first, then calls load():

  • A string or URL is fetched. A Request is fetched as it is.
  • A Response or Blob / File is read.
  • Bytes or { name, data } pass through.
  • An array mixes them.
  • A gzip-wrapped file (a web server's .gz) is unwrapped, as often as it is wrapped, and keeps its name: a wrapped bundle's files carry their own names, a wrapped .resS the .gz one. load() refuses gzip with an UnsupportedError naming open() and gunzip(), because inflating is async and load() is not. await gunzip(bytes) unwraps one yourself.
  • A file is named after the last segment of its URL's path (decoded, without the query) or its File.name.
  • A response that is not OK throws an Error naming the URL and the status.

To fetch with your own headers or credentials, pass { fetch }:

const env = await open(url, { fetch: (input) => fetch(input, { headers }) });

Both load() and open() accept { unityVersion } for version-stripped files, and { typeTrees } for the scripts of files built without type trees.

List and filter assets

env.assets(...types) yields every object as an Asset. An Asset is plain data with type, typeName, classId, name, path, pathId, file, byteSize, data, the low-level reader and the env that loaded it.

  • type is the class name for the classes with a class reader (see Classes), and "Other" for the rest. Their name is in typeName.
  • A switch (asset.type) narrows data.
  • env.assets("Texture2D", "Sprite") keeps only those types, and narrows too.
  • Assets have no methods. What you can turn one into is a function that takes it.

Read an asset's name, path and data

name, path and data are read when you first use them, then kept.

  • name is m_Name, read only as far as that field ("" for a class without one).
    • Without type trees, a GameObject is named from its header, and is "" where the GameObject reader refuses it.
    • A Shader's name is its parsed form's name ("UAR/ShaderFixture"), by AssetStudio's formula, since Unity leaves its m_Name empty. That reads the whole shader.
    • A shader the Shader reader refuses or cannot fit keeps its m_Name, usually "".
  • path is the first m_Container path of any loaded AssetBundle that points at the asset, or undefined.
  • data is what obj.read() returns (see Read objects at the low level). For a class with a class reader, it has the TypeScript-style shape of Classes. For "Other", it is what the type tree reads, under Unity's names.
  • A read that fails throws when you access it, with the file, class and path id in the message. It is tried again on the next access.

asset.data field names are camelCase, without Unity's m_ prefix: width for m_Width, format for m_TextureFormat. Each field's JSDoc names the Unity field it comes from, so the Unity documentation still applies.

  • Pointers stay PPtrs ({ m_FileID, m_PathID }). Follow them with env.resolve.
  • 64-bit values stay bigint.
  • A field that only some Unity versions have is optional.
  • The low-level obj.read() keeps Unity's names. The toXFields functions (toTexture2DFields(obj.read()), ...) turn its result into the same shape as asset.data.

Find an asset by its project path

env.get(path) finds the asset a container path names. Unity stores those paths in lower case, and the lookup ignores case. A path that lists several assets (a texture and its sprites) gives the first one; filter env.assets() by path for the rest.

Follow a pointer to another object

Objects point at each other with a PPtr ({ m_FileID, m_PathID }), for example a material's shader. env.resolve(pptr, obj) follows one:

import { classIdName } from "unity-asset-reader";

for (const material of env.assets("Material")) {
  const result = env.resolve(material.data.shader, material.reader);
  if (result.status === "found") console.log(material.name, classIdName(result.object.type));
  else if (result.status === "fileNotLoaded") console.log("load", result.fileName, "too");
}

It returns { status: "found", object }, or a reason why not ("null", "fileNotLoaded" with the file name to load, ...). A dangling pointer is a result, never an exception. resolveOrThrow() is the variant for a pointer that must lead somewhere (see Loading).

Read objects at the low level

Below env.assets() sit the unpacked files and the raw objects themselves:

import { load, ClassID, classIdName, textAssetString, type TextAsset } from "unity-asset-reader";

// Pass the bundle, plus any .resS / .resource files that sit next to it.
const env = load([{ name: "characters.bundle", data: bundleBytes }]);

// 1. Unpack: every file inside, byte for byte.
for (const { path, data } of env.files) {
  console.log(path, data.length); // "CAB-1a2b…" 4580, "CAB-1a2b….resS" 64
}

// 2. Read objects.
for (const obj of env.objects) {
  console.log(classIdName(obj.type), obj.pathId); // "TextAsset" -2966962111441417370n

  if (obj.type === ClassID.TextAsset) {
    console.log(textAssetString(obj.read<TextAsset>()));
  }
}
  • env.files lists every file after unpacking. That covers the "just unpack it" use case.
    • Nested containers are opened too: a bundle inside a UnityWebData file.
    • A SerializedFile or a .resS is kept under its own path.
  • env.objects lists every object of every SerializedFile in env.files.
    • The files are parsed the first time you read env.objects (or call env.resolve / env.readResource), not by load().
    • So a file this library cannot parse does not stop you from unpacking.
  • obj.read() reads an object with the class reader for its class, if there is one (see Classes). Otherwise it reads the object's type tree.
    • The result type is the union ObjectData.
    • Narrow it yourself after checking obj.type, for example obj.read<TextAsset>(). Nothing checks it at run time.
  • obj.readTypeTree() reads any object into a plain JS object by walking its type tree. That works for every class, including your own MonoBehaviour/ScriptableObject fields, as long as the bundle was built with type trees (the Unity default), or you supply your scripts' type trees.
  • env.resolve(pptr, obj) follows a pointer (see Follow a pointer to another object).
  • env.readResource(ref, obj) reads bulk data that an object keeps in a .resS / .resource file. obj.read() already does that for Texture2D, Cubemap, Texture2DArray, Texture3D, AudioClip and VideoClip (imageData, audioData, videoData).

Returned bytes are views into your input or into the decompressed blocks, never copies. A small view keeps its whole buffer alive. To keep a small piece and let the rest be garbage-collected, copy it (data.slice()).

Load several files together

Pass every file in one load() call: a bundle and its dependency bundles, or a player build's sharedassets0.assets with its .resS. Then pointers between them resolve, and each object finds its resource files.

  • File names are matched by their last path component, ignoring case, as Unity does.
  • To keep two builds apart, load each one with its own load().

In Node.js, unity-asset-reader-node's loadPath() reads a file with its sidecars, or a whole folder, and calls load() for you.

Compare two builds

diff(oldEnv, newEnv) lists the assets one build added, removed or modified against another, for a CI check on an asset pipeline or a patch-size estimate. Assets that did not change are left out.

import { diff, load } from "unity-asset-reader";

for (const e of diff(load(oldFiles), load(newFiles))) {
  console.log(e.change, e.type, e.path ?? `${e.file} ${e.pathId}`, e.sizeDelta, e.fields);
}
// modified Texture2D assets/ui/star.png 2048 [ "m_Width", "m_CompleteImageSize", "m_TextureFormat", "m_StreamData" ]
// added Texture2D assets/ui/moon.png 1216 undefined
  • Matching: by container path (with the class and name) first. The rest match by class, path id and bundle name (the AssetBundle object's m_AssetBundleName), so a bundle whose CAB name changed still matches. Where there is no bundle name, the file name is used.
  • Content: the object's bytes, and the bytes of its streamed data in the .resS or .resource file. Different object bytes make an asset modified. The one exception is an object with streamed data: its fields are compared instead, the streamed data by its bytes, so a texture whose data only moved within its .resS is not modified. In a build without type trees, the streamed data of CubemapArray is not compared yet.
  • fields: for a modified asset with a type tree on both sides, the top-level fields that differ. m_StreamData (or m_Resource, m_ExternalResources) is listed when the streamed bytes differ. The list is empty when only bytes no field shows differ, such as padding.
  • sizeDelta: the object plus its streamed data, new less old.
  • before and after are the two Assets. Load each build with its own load(), with its .resS files.

Run it in a Worker

Parsing is synchronous, so a big bundle blocks the thread it runs on until it is done. In a browser, run the reader in a Web Worker and post plain data back to the page:

// reader.worker.js (a module Worker)
import { load, classIdName } from "unity-asset-reader";

self.onmessage = ({ data: { name, bytes } }) => {
  const env = load([{ name, data: new Uint8Array(bytes) }]);
  self.postMessage(
    env.objects.map((obj) => ({
      className: classIdName(obj.type),
      pathId: String(obj.pathId), // bigint -> string for the page
      size: obj.byteSize,
    })),
  );
};
// page
const worker = new Worker(new URL("./reader.worker.js", import.meta.url), { type: "module" });
const bytes = await file.arrayBuffer();
worker.postMessage({ name: file.name, bytes }, [bytes]); // transfer, do not copy

64-bit values and JSON

Every 64-bit integer is a bigint: path ids (obj.pathId, m_PathID), and every SInt64 / UInt64 field a type tree holds.

  • That holds even when the value is small, so a field's type never depends on its value.
  • File offsets and sizes are plain numbers. Anything at or above 2^53 is refused with an error rather than rounded.

JSON.stringify throws on a bigint. Pass a replacer that writes it as a decimal string:

/** JSON.stringify replacer: bigint -> decimal string, bytes -> hex. */
function unityJsonReplacer(_key, value) {
  if (typeof value === "bigint") return value.toString();
  if (value instanceof Uint8Array) {
    return Array.from(value, (b) => b.toString(16).padStart(2, "0")).join("");
  }
  return value;
}

JSON.stringify(obj.readTypeTree(), unityJsonReplacer, 2);
  • The Uint8Array branch is optional. Without it, a byte array (TypelessData, byte[], a TextAsset's m_Script) becomes {"0":…,"1":…}.
  • JSON has no NaN, Infinity or -0. JSON.stringify writes null, null and 0 for float fields that hold them.

Errors

Every error says where the problem is:

  • An error from load() or env.objects names the path down to the bad bytes (a.bundle: CAB-1a2b…: ...).
  • An asset's name or data adds the class and path id (a.bundle: CAB-1a2b…: Texture2D -2966962111441417370: ...).

Three error classes let you tell the cases apart:

| Class | Meaning | Useful fields | |---|---|---| | UnsupportedError | The input is well-formed, but it uses something this library does not read: a compression type, a container, a format or Unity version. | kind ("compression type", "container", "Unity version", ...), found | | CorruptError | The input claims to be something this library reads, but it does not hold together: it is truncated, a size disagrees with its header, the magic number is wrong. | | | ResourceNotFoundError | An object's data is in a .resS / .resource file that was not passed to load(), or a pointer followed by resolveOrThrow leads into a SerializedFile (CAB-<hash>) of a bundle that was not. Load it too. For a bundle, the message ends with the dependencies the pointing bundle's AssetBundle object declares, when it declares any: asset.data.dependencies (m_Dependencies, Unity 5.0+). They are bundle names, not file names, so they narrow down which file to pass rather than name it. | path, fileName |

Nothing returns partial or garbage data without an error.

Supported

What this package reads: containers and compression, classes, Unity versions and version-stripped files. Each row is checked against the code.

In the "Tested on" column:

  • "fixture" means a bundle built by the Unity editor (fixtures/);
  • "generated" means a container written by UnityPy's bundle writer around made-up bytes;
  • "unit test" means a hand-written byte layout in this package's tests.

Containers and compression

| Input | Support | Tested on | |---|---|---| | UnityFS | Formats 6, 7 and 8. Blocks info at the end (flag 0x80), 2019.4+ block padding (flag 0x200), the 16-byte header padding of format 7 and of 2019.4.15+ format 6 | Fixtures (formats 7 and 8), generated (format 6) | | UnityWeb, UnityRaw (legacy web player bundles) | The old level layout and the format 6 archive layout, LZMA-compressed (UnityWeb) or not (UnityRaw) | Generated (formats 2 and 3), unit tests (formats 4 and 6) | | UnityWebData1.0 (WebGL .data) | Yes, and a bundle inside it is opened too | Generated | | A gzip-wrapped file | Unwrapped by open(), then opened as whatever is inside; load() refuses it | Generated | | A loose SerializedFile (.assets, level0, globalgamemanagers) | Yes | Fixtures' SerializedFile nodes, read on their own | | .resS / .resource resource files, loose or bundle nodes | Yes: Texture2D, Cubemap, Texture2DArray, Texture3D, AudioClip and VideoClip read their data from them | Fixtures | | Split files (.split0, .split1, ...) | Pass the joined file to load(); unity-asset-reader-node's loadPath() joins them | Unit tests of -node | | Bundle block compression | None, LZMA, LZ4, LZ4HC (LZ4HC blocks decode as LZ4) | Fixtures (none, LZMA, LZ4), generated | | SerializedFile format versions | 2 to 23, little- and big-endian. See Unity versions | Fixtures (21, 22, 23), unit tests (6, 8, 15; format-23 blob validation) |

Classes

obj.readTypeTree() reads any class from a file with type trees. obj.read() uses a hand-written reader, a class reader, for the classes below. Those readers also work on bundles built without type trees (BuildAssetBundleOptions.DisableWriteTypeTree).

How to read the table:

  • Main fields of asset.data lists the main fields, with the type in brackets. The JSDoc of each type has every field, with its Unity name.
  • From is the first Unity version whose layout the reader knows. The other readers refuse an older version. Texture2D has no floor: it reads any older version with its oldest layout.
  • Fixture "Yes" is all three fixture editors.

Unity 2019.1 is the supported floor. A reader added since that decision (Mesh, Avatar, AnimatorController, Animator, AnimatorOverrideController, AnimationClip, Animation, GameObject, Transform, RectTransform, MeshFilter, MeshRenderer, SkinnedMeshRenderer) starts there. The older readers keep the older layouts they already had.

| Class | Main fields of asset.data | From | Fixture | |---|---|---|---| | AssetBundle (AssetBundleFields) | container: asset path to object, the bundle's table of contents; preloadTable, dependencies | 3.4 | Yes | | TextAsset (TextAssetFields) | bytes: the file as stored; text: those bytes decoded as UTF-8 (on first use) | 3.4 | Yes | | MonoBehaviour (MonoBehaviourFields) | script (the MonoScript pointer), gameObject, enabled, name, and fields: every field of the script, with a type tree only, the file's own or a supplied one | Any | Yes | | MonoScript (MonoScriptFields) | className, namespace, assemblyName | 3.4 | Yes | | Material (MaterialFields) | shader pointer, keywords, and savedProperties: texEnvs (texture slots), floats, ints, colors | 3.4 | Yes | | Shader (ShaderFields) | parsedForm: the parsed ShaderLab (name, properties, sub-shaders, passes, render state, keywords, each variant's parameters); platforms and compressedBlob: every platform's compiled programs, LZ4-compressed, not decoded | 2019.1 | 2019.4, 2020.3, 6000.3.26f1, 6000.6 | | Texture2D (Texture2DFields) | width, height, format (a TextureFormat), mipCount, textureSettings, platform and imageData, still encoded (inline or from the .resS). Decode it with unity-asset-reader-texture | Any (gates from 2.6; tested from 3.4) | Yes | | Cubemap (CubemapFields) | The Texture2D fields of its six faces (imageData holds each face with its own mip levels, one after the other) and sourceTextures. Decode it with unity-asset-reader-texture | 2019.1 | 2019.4, 2020.3, 6000.3, 6000.6 | | Texture2DArray (Texture2DArrayFields) | width, height, depth (the slice count), format (a GraphicsFormat; textureFormatOfGraphicsFormat maps it), mipCount, colorSpace, textureSettings, platform and imageData: each slice with its own mip levels, still encoded | 2019.1 | 2019.4, 2020.3, 6000.3, 6000.6 | | Texture3D (Texture3DFields) | The same fields as Texture2DArray; depth is the depth of level 0, and imageData holds the levels one after the other, level n max(1, depth >> n) slices deep | 2019.1 | 2019.4, 2020.3, 6000.3, 6000.6 | | Sprite (SpriteFields) | rect, pivot, border, pixelsToUnits, renderData (texture area and mesh). Cut it out with unity-asset-reader-texture | 4.3 | 2019.4, 6000.3, 6000.6 | | SpriteAtlas (SpriteAtlasFields) | renderDataMap; before 6000.6 also packedSprites, from 6000.6 each entry holds its sprite instead (spriteInstanceData: name, rect, pivot, border, mesh) | 2017.1 | 2019.4, 6000.3, 6000.6 | | AudioClip (AudioClipFields) | channels, frequency, length, compressionFormat and audioData: the sound bank as stored (usually FSB5), not decoded | 3.4 | Yes | | VideoClip (VideoClipFields) | width, height, frameRate, frameCount and videoData: the video file as imported (e.g. WebM, MP4), not decoded | 5.6 | Yes | | Font (FontFields) | fontData: the TrueType/OpenType file; fontNames, fontSize, characterRects | 3.4 | Yes | | MovieTexture (MovieTextureFields) | movieData (the Ogg Theora file), loop, audioClip | 3.4 | No, unit tests only | | Mesh (MeshFields) | subMeshes, vertexData, compressedMesh, indexBuffer, streamData, and decoded as AssetStudio does: vertexCount, vertices, normals, tangents, colors, uv (UV0 to UV7), skin (bone weights), indices (each submesh's triangles, offset by its baseVertex, which AssetStudio leaves out), the vertex data read from the .resS when streamed | 2019.1 | Yes | | Avatar (AvatarFields) | avatar: the runtime avatar (skeletons, poses, the humanoid part with its bones, hands and muscle setup); tos (path hash to transform path); humanDescription: the bones and settings it was built from | 2019.1 | Yes, and 6000.6 | | AnimatorController (AnimatorControllerFields) | controller: layers (with their masks), state machines (states, transitions with their conditions, blend trees, entry and exit selectors) and parameters with their defaults; tos (name hash to name), animationClips, stateMachineBehaviours | 2019.1 | Yes, and 6000.6 | | Animator (AnimatorFields) | avatar, controller (pointers), gameObject, enabled, cullingMode, updateMode, applyRootMotion and the other flags | 2019.1 | Yes, and 6000.6 | | AnimatorOverrideController (AnimatorOverrideControllerFields) | controller, and clips: each original clip with the clip that overrides it | 2019.1 | Yes, and 6000.6 | | AnimationClip (AnimationClipFields) | legacy; a legacy clip's curves (positionCurves, rotationCurves, eulerCurves, scaleCurves, floatCurves, pptrCurves); a Mecanim clip's muscleClip (its streamed, dense and constant parts, raw, and its loop settings) and clipBindingConstant (what each curve animates); sampleRate, wrapMode, events | 2019.1 | Yes, and 6000.6 | | Animation (AnimationFields) | A legacy Animation component: clip (the default one) and clips (pointers), gameObject, enabled, wrapMode, playAutomatically, animatePhysics, cullingType, updateMode (2023.1+) | 2019.1 | Yes, and 6000.6 | | GameObject (GameObjectFields) | component (each { component } pointer, the Transform first), layer, name, tag, isActive | 2019.1 | Yes, and 6000.6 | | Transform (TransformFields) | gameObject, localRotation, localPosition, localScale, children, father (pointers to the parent and child Transforms) | 2019.1 | Yes, and 6000.6 | | RectTransform (RectTransformFields) | A UI element's Transform: the Transform fields, then anchorMin, anchorMax, anchoredPosition, sizeDelta, pivot | 2019.1 | Yes, and 6000.6 | | MeshFilter (MeshFilterFields) | gameObject, mesh | 2019.1 | Yes, and 6000.6 | | MeshRenderer (MeshRendererFields) | materials, gameObject, enabled, the shadow, probe, lightmap and sorting settings, additionalVertexStreams | 2019.1 | Yes, and 6000.6 | | SkinnedMeshRenderer (SkinnedMeshRendererFields) | mesh, bones, rootBone, blendShapeWeights, aabb, quality, and the renderer fields as MeshRenderer | 2019.1 | Yes, and 6000.6 |

  • The animation classes' nested runtime structs keep their raw arrays: curves and muscle values are not decoded here. unity-asset-reader-animation's clipCurves() decodes them.
  • Every other class (Camera, Light, Canvas, ...) comes from its type tree. In a bundle without type trees, obj.read() throws UnsupportedError for them.
  • The class readers are for player builds. See Not supported for the editor files they refuse.

Unity versions

  • A class reader reads a version newer than its newest gate (6000.6) with the newest layout it knows.
  • readTypeTree() does not depend on the Unity version, so it reads every format from 2 to 23.
  • Format 23's type-tree content hashes and blob headers follow UnityPy 1.25.4. AssetStudio does not yet handle that layout.
  • A zero-length blob has no embedded tree. So a generic dump of an object using it throws UnsupportedError, as it does when type trees are disabled.
  • A SerializedFile of format 6 or older records no Unity version. In a bundle, it takes the bundle's unityRevision. A loose one has version [0, 0, 0, 0], and the class readers treat it as a version-stripped file (below).

The editors and formats each part is tested on are listed in How it is tested.

Version-stripped files

A bundle built with AssetBundleStripUnityVersion records "0.0.0" as its Unity version, in the bundle header and in each SerializedFile. If you know the editor that built it, pass its version:

const env = load(bytes, { unityVersion: "2019.4.41f2" });
const web = await open(url, { unityVersion: "2019.4.41f2" });
  • This fallback fills a missing or stripped version after trying the enclosing bundle's revision.
  • It preserves recorded versions and usable bundle revisions.
  • It also applies to loose files below SerializedFile format 7.
  • The option must name an editor: major.minor.patch with an optional build suffix and custom postfix, such as 2021.3.15f1c1.
  • Invalid strings, including "0.0.0", throw RangeError. Non-strings throw TypeError.

Without a usable version, readTypeTree() reads the file as usual. Each class reader reads such an object only when its bytes or the SerializedFile format leave one layout. Otherwise it throws UnsupportedError (kind "Unity version"):

| Class | Version-stripped | |---|---| | AssetBundle | Read, format 16 and later | | TextAsset | Read, format 7 and later | | MonoBehaviour | Read | | MonoScript | Refused | | Material | Read in formats 18 to 21 (Unity 2019), refused otherwise | | Shader | Read in format 21 (Unity 2019.3 and 2019.4), refused otherwise | | Texture2D | Refused | | Cubemap | Refused | | Texture2DArray | Refused | | Texture3D | Refused | | Sprite | Read in formats 18 to 21 (Unity 2019), refused otherwise | | SpriteAtlas | Read in formats 18 to 21 (Unity 2019), refused otherwise | | AudioClip | Read, format 18 and later | | VideoClip | Read, format 21 and later | | Font | Read, format 16 and later | | MovieTexture | Refused | | Mesh | Read in formats 18 to 21 (Unity 2019), refused otherwise | | Avatar | Read in formats 18 to 21 (Unity 2019), refused otherwise | | AnimatorController | Read in formats 18 to 21 (Unity 2019), refused otherwise | | Animator | Read in formats 18 to 21 (Unity 2019), refused otherwise | | AnimatorOverrideController | Read in formats 18 to 21 (Unity 2019), refused otherwise | | AnimationClip | Read in formats 18 to 21 (Unity 2019), refused otherwise | | Animation | Read in formats 18 to 21 (Unity 2019), refused otherwise | | GameObject | Read in formats 18 to 21 (Unity 2019), refused otherwise | | Transform | Read in formats 18 to 21 (Unity 2019), refused otherwise | | RectTransform | Read in formats 18 to 21 (Unity 2019), refused otherwise | | MeshFilter | Read in formats 18 to 21 (Unity 2019), refused otherwise | | MeshRenderer | Read in formats 18 to 21 (Unity 2019), refused otherwise | | SkinnedMeshRenderer | Read in formats 18 to 21 (Unity 2019), refused otherwise |

The version-stripped fixtures, in formats 21 and 22, hold a TextAsset, a Material, AudioClips, a VideoClip, a Font, the font's Texture2D and the bundle's AssetBundle. The other rows are unit tests.

Scripts in files built without type trees

Most player builds strip type trees (DisableWriteTypeTree), so a MonoBehaviour or ScriptableObject gives up only its header: the script's own fields need the script's type tree. If you have it, pass it to load() or open(), keyed by script:

const env = load(bytes, {
  typeTrees: {
    // The MonoScript's "<m_AssemblyName>:<m_Namespace>.<m_ClassName>"
    "Assembly-CSharp.dll:Game.ItemDatabase": itemDatabaseNodes,
    // or the script id of the object's type entry, as 32 hex digits
    "15f441d01838cd812fdb2c200c404b22": otherNodes,
  },
});
for (const asset of env.assets("MonoBehaviour")) console.log(asset.data.fields);
  • Making the trees is up to you: this library does not read assemblies. Generators such as UnityPy's TypeTreeGenerator build them from the game's DLLs (or, for IL2CPP, from Il2CppDumper's dummy DLLs).
  • The format is a TypeTreeNodeData[]: the nodes in pre-order, the root (level 0) first, each { type, name, level, byteSize, metaFlag }, optionally typeFlags and version. It is plain JSON. A TypeTreeNode[] of another file is accepted as it is. From a UnityPy TypeTreeNode node: [{"type": d["m_Type"], "name": d["m_Name"], "level": d["m_Level"], "byteSize": d["m_ByteSize"], "metaFlag": d["m_MetaFlag"]} for d in node.to_dict_list()].
  • Keys: the script name uses the MonoScript the object's m_Script points at ("<m_AssemblyName>:<m_ClassName>" in the global namespace; the assembly is "Assembly-CSharp", without .dll, from Unity 6). The script id (SerializedType.scriptId) is for when that MonoScript is not loaded or cannot be read.
  • Lookup order: the file's own type tree, then the tree of the script's name, then the tree of its script id, then the header only.
  • A tree that does not fit (it does not consume exactly the object's bytes) throws CorruptError naming the script, rather than reading garbage.
  • [SerializeReference] data cannot be read this way: the file has no type trees for the referenced types either, so a supplied tree reaching a referenced object throws UnsupportedError. An empty [SerializeReference] registry reads.

API reference

Every export, grouped. Each one has full JSDoc (parameters, return values, what it throws) in the bundled index.d.ts, so your editor shows it on hover.

Loading

| Export | What | |---|---| | load(inputs, options?) | Unpack one file or several and index their objects. Returns an Env | | open(sources, options?) | Fetch or read files (URL, Request, Response, Blob / File, bytes), unwrap gzip, then load() them. Returns a promise of the Env | | OpenSource, OpenOptions | What open() takes; options include LoadOptions and a fetch replacing the global one | | ResponseLike, RequestLike, BlobLike, URLLike | The parts of the WHATWG types open() uses, which Response, Request, Blob, File and URL fit | | Env | files, objects, assets(...types), get(path), resolve(pptr, from), readResource(ref, from) | | LoadSource | One input of load(): bytes, a LoadInput, or { data } without a name (called input <index>) | | LoadInput | { name, data }: one named file for load(); data is a Uint8Array or ArrayBuffer | | LoadOptions | unityVersion: fallback editor version for files that record none or have a stripped version; typeTrees: type trees for the MonoBehaviours of files built without them, by script (details) | | LoadedFile | { path, data }: one unpacked file | | ResourceRef | { path, offset, size }: a byte range of a resource file (a StreamingInfo) | | PPtr | { m_FileID, m_PathID }: a pointer as a type tree holds it | | PPtrResolution | What env.resolve returns: found with the object, or why not | | resolveOrThrow(env, pptr, from, what, classId?) | env.resolve for a pointer that must lead somewhere: the object, optionally checked to be of class classId, or an error naming the field (what): ResourceNotFoundError for a file not loaded, its message ending with the dependencies the AssetBundle of from's bundle declares ((this bundle declares dependencies: a, b)) when there are any, CorruptError otherwise |

Objects

| Export | What | |---|---| | Asset, AssetType, KnownAssetType | One object as env.assets() yields it; Asset<"Texture2D"> is one of that type. AssetType is KnownAssetType (the classes with a class reader) or "Other" | | AssetDataMap | Class name to the type of asset.data (Texture2DFields, ...), for the classes with a class reader | | ObjectDataMap | Class name to what obj.read() returns (Texture2DData, ...), under Unity's names | | ObjectReader | One object: pathId, type (class id), byteSize, version, platform, read(), readTypeTree(), and the binary read methods of BinaryReader | | ObjectData | The union obj.read() returns | | readTypeTree(reader) | Read an object into a plain JS object by walking its type tree | | TypeTreeObject, TypeTreeValue | What readTypeTree returns; the JSDoc lists each Unity type's JS shape | | diff(oldEnv, newEnv) | The assets added, removed or modified between two loaded builds (details) | | DiffEntry | One diff result: change, type, path, name, file, pathId, before, after, sizeDelta, and fields (top-level fields that differ) | | ClassID, classIdName(id) | Unity class ids by name (ClassID.Texture2D === 28), and back | | Vector3, Quaternion, XForm | Shapes read by ObjectReader.readVector3 / readXForm (and by the animation readers' float3, float4 and xform fields) |

Class readers

Each readX(reader) reads one class from the object's first byte. obj.read() calls them for you. Call one yourself only to read an object as a specific class.

| Export | Result types | |---|---| | readObject, readEditorExtension, readNamedObject | UnityObject, EditorExtension, NamedObject: the fields every class starts with | | readAssetBundle | AssetBundle, AssetInfo, AssetBundleScriptInfo | | readTextAsset, textAssetString | TextAsset | | readMonoScript | MonoScript, Hash128 | | readMonoBehaviour | MonoBehaviour (the header); MonoBehaviourData is what obj.read() returns | | readMaterial | Material, UnityPropertySheet, UnityTexEnv, BuildTextureStackReference, Color, Vector2 | | readShader | Shader, SerializedShader, SerializedProperty, SerializedTextureProperty, SerializedSubShader, SerializedPass, SerializedTagMap, SerializedShaderState, SerializedShaderRTBlendState, SerializedStencilOp, SerializedShaderFloatValue, SerializedShaderVectorValue, SerializedProgram, SerializedSubProgram, SerializedPlayerSubProgram, ParserBindChannels, ShaderBindChannel, ProgramParameters, VectorParameter, MatrixParameter, StructParameter, TextureParameter, BufferBinding, ConstantBuffer, UAVParameter, SamplerParameter, Binding | | readTexture, readTexture2D, TextureFormat | Texture, Texture2D, StreamingInfo, GLTextureSettings; Texture2DData is what obj.read() returns | | readCubemap, readTexture2DArray, readTexture3D | Cubemap, Texture2DArray, Texture3D; CubemapData, Texture2DArrayData, Texture3DData are what obj.read() returns | | GraphicsFormat, textureFormatOfGraphicsFormat(format) | The GraphicsFormat values a fixture checks, and the TextureFormat a Texture2DArray or Texture3D m_Format decodes as (UnsupportedError of kind "graphics format" for any other value) | | readSprite, SpritePackingRotation | Sprite, SpriteRenderData, SpriteVertex, SpriteBone, SecondarySpriteTexture, VertexData, ChannelInfo, SubMesh, BlendShapeData, BlendShapeVertex, MeshBlendShape, MeshBlendShapeChannel, BoneWeights4, AABB, Matrix4x4, Vector4, GUID | | readSpriteAtlas | SpriteAtlas, SpriteAtlasData, SpriteInstanceData | | readAudioClip | AudioClip; AudioClipData is what obj.read() returns | | readVideoClip | VideoClip, StreamedResource; VideoClipData is what obj.read() returns | | readFont | Font, CharacterInfo, Rectf | | readMovieTexture | MovieTexture | | readMesh, GfxPrimitiveType | Mesh, CompressedMesh, PackedFloatVector, PackedIntVector, MinMaxAABB, VariableBoneCountWeights, MeshLodInfo, MeshLodRange, LodSelectionCurve; MeshData (with VertexBoneWeights) is what obj.read() returns | | readHumanPose, readValueArrayConstant | HumanPose, HumanGoal, HandPose, ValueArrayConstant, ValueConstant, OffsetPtr: structs the animation classes share | | readAvatar | Avatar, AvatarConstant, Skeleton, SkeletonNode, SkeletonPose, Axes, Limit, Human, Hand, HumanDescription, HumanBone, SkeletonBone, SkeletonBoneLimit | | readAnimatorController | AnimatorController, ControllerConstant, LayerConstant, HumanPoseMask, SkeletonMask, SkeletonMaskElement, StateMachineConstant, StateConstant, TransitionConstant, ConditionConstant, BlendTreeConstant, BlendTreeNodeConstant, Blend1dDataConstant, Blend2dDataConstant, BlendDirectDataConstant, MotionNeighborList, SelectorStateConstant, SelectorTransitionConstant, ValueArray, StateMachineBehaviourVectorDescription, StateKey, StateRange | | readAnimator | Animator | | readAnimation | Animation | | readAnimatorOverrideController | AnimatorOverrideController, AnimationClipOverride | | readAnimationClip | AnimationClip, AnimationCurve, Keyframe, QuaternionCurve, Vector3Curve, CompressedAnimationCurve, PackedQuatVector, FloatCurve, PPtrCurve, PPtrKeyframe, ClipMuscleConstant, Clip, StreamedClip, DenseClip, ConstantClip, ValueDelta, AnimationClipBindingConstant, GenericBinding, AnimationEvent | | readGameObject | GameObject, ComponentPair | | readTransform | Transform | | readRectTransform | RectTransform | | readMeshFilter | MeshFilter | | readMeshRenderer, readSkinnedMeshRenderer | MeshRenderer, SkinnedMeshRenderer, Renderer (the fields both start with), StaticBatchInfo |

asset.data shapes

Each toXFields(data) turns what obj.read() returns for class X into what asset.data is for it. env.assets() calls them for you.

| Export | Result types | |---|---| | toAssetBundleFields, toTextAssetFields, toMonoScriptFields, toMaterialFields, toShaderFields, toTexture2DFields, toCubemapFields, toTexture2DArrayFields, toTexture3DFields, toSpriteFields, toSpriteAtlasFields, toAudioClipFields, toVideoClipFields, toFontFields, toMovieTextureFields, toMeshFields | AssetBundleFields, TextAssetFields, MonoScriptFields, MaterialFields (UnityPropertySheetFields, UnityTexEnvFields), ShaderFields (SerializedShaderFields, SerializedPropertyFields, SerializedSubShaderFields, SerializedPassFields, SerializedShaderStateFields, SerializedProgramFields, SerializedSubProgramFields, SerializedPlayerSubProgramFields, ProgramParametersFields, VectorParameterFields, MatrixParameterFields, StructParameterFields, TextureParameterFields, BufferBindingFields, ConstantBufferFields, UAVParameterFields, SamplerParameterFields, BindingFields), Texture2DFields (GLTextureSettingsFields), CubemapFields, Texture2DArrayFields, Texture3DFields, SpriteFields (SpriteRenderDataFields, VertexDataFields, SubMeshFields, AABBFields), SpriteAtlasFields (SpriteAtlasDataFields, SpriteInstanceDataFields), AudioClipFields and VideoClipFields (StreamedResourceFields), FontFields, MovieTextureFields, MeshFields (CompressedMeshFields, PackedFloatVectorFields, PackedIntVectorFields, MinMaxAABBFields, MeshLodInfoFields) | | toAnimationFields | AnimationFields | | toRectTransformFields | RectTransformFields | | toAvatarFields, toAnimatorControllerFields, toAnimatorFields, toAnimatorOverrideControllerFields | AvatarFields, AnimatorControllerFields, AnimatorFields, AnimatorOverrideControllerFields (AnimationClipOverrideFields, ValueConstantFields, ValueArrayConstantFields, SkeletonMaskElementFields, SkeletonMaskFields, LayerConstantFields, ConditionConstantFields, TransitionConstantFields, MotionNeighborListFields, Blend2dDataConstantFields, Blend1dDataConstantFields, BlendDirectDataConstantFields, BlendTreeNodeConstantFields, BlendTreeConstantFields, StateConstantFields, SelectorTransitionConstantFields, SelectorStateConstantFields, StateMachineConstantFields, ValueArrayFields, ControllerConstantFields, StateKeyFields, StateRangeFields, StateMachineBehaviourVectorDescriptionFields, SkeletonNodeFields, LimitFields, AxesFields, SkeletonFields, SkeletonPoseFields, HandFields, HumanFields, AvatarConstantFields, SkeletonBoneLimitFields, HumanBoneFields, SkeletonBoneFields, HumanDescriptionFields) | | toAnimationClipFields | AnimationClipFields (AnimationCurveFields, QuaternionCurveFields, Vector3CurveFields, PackedQuatVectorFields, CompressedAnimationCurveFields, FloatCurveFields, DenseClipFields, ClipFields, HumanGoalFields, HandPoseFields, HumanPoseFields, ValueDeltaFields, ClipMuscleConstantFields) | | toGameObjectFields, toTransformFields, toMeshFilterFields, toMeshRendererFields, toSkinnedMeshRendererFields | GameObjectFields, TransformFields, MeshFilterFields, MeshRendererFields, SkinnedMeshRendererFields (RendererFields: the fields both renderers start with) | | toMonoBehaviourFields(data, obj) | MonoBehaviourFields; it takes the object too, whose type tree tells whether data holds the script's fields | | EditorExtensionFields, NamedObjectFields, TextureFields | The fields every class, every named class and every texture starts with |

Lower layers

For tools that work below load():

| Export | What | |---|---| | detectFileType(data), FileType | Sniff what a file is from its first bytes; never throws | | detectContainer(data), SupportedFileType | The same, but throws UnsupportedError for what cannot be opened | | readBundle(data), BundleFile, BundleHeader, StorageBlock, StreamFile, NodeFlags | Unpack one UnityFS / UnityWeb / UnityRaw bundle: its header, its data blocks (blocks, each with its codec in flags & 0x3f) and its files | | readWebFile(data), WebFile | Unpack one UnityWebData1.0 file | | readSerializedFile(data), SerializedFile, SerializedFileHeader, ObjectInfo, FileIdentifier, LocalSerializedObjectIdentifier, UnityVersion | Parse a SerializedFile's header, type trees and object table | | SerializedType, TypeTreeNode | A type entry and its type tree | | TypeTreeNodeData | One node of a type tree supplied through LoadOptions.typeTrees: { type, name, level, byteSize, metaFlag }, plain JSON | | SerializedFileFormatVersion, BuildTarget | Format version and target platform constants | | decompressLz4, lzmaDecompress | The block decompressors, each checking its output size | | crc32(bytes, start?, end?) | CRC-32 (reflected polynomial 0xEDB88320, as PNG, gzip and zip use it) of bytes[start..end), unsigned | | gunzip, unzlib | gzip and zlib through the platform's DecompressionStream: async, each returning a promise, rejected with a CorruptError on a damaged or truncated stream | | formatSingle(value), formatSingleInvariant(value) | Write a float32 as .NET 8's float.ToString() does, under en-US and invariant culture | | GltfWriter | Build a binary glTF 2.0 file (.glb); see glTF writer | | BinaryReader, Endian | Bounds-checked reader over a Uint8Array, little- or big-endian | | UnsupportedError, CorruptError, ResourceNotFoundError | See Errors |

glTF writer

The building blocks of a binary glTF 2.0 file (.glb), for the feature packages that export models. Two exporters are built on it:

About the writer itself:

  • It follows the glTF 2.0 specification and knows nothing about Unity.
  • What goes in, and how Unity's left-handed space is converted, is the caller's choice.
  • Sync, no dependency.

| Export | What | |---|---| | GltfWriter | new GltfWriter(generator), then addAccessor(), addMesh(), addSkin(), addNode(), addAnimation() and addScene(), each returning the index the others refer to it by; toGlb() checks the references and the spec's counting rules (UnsupportedError) and returns the file's bytes | | GltfAccessor, GltfComponentArray, GltfAccessorType | One accessor: a typed array (its class picks the component type), SCALAR to MAT4, the buffer view's target, normalized, and bounds for the min and max glTF requires of POSITION and animation inputs | | GltfMesh, GltfPrimitive | A mesh of triangle primitives: attributes, indices, morph targets (POSITION, NORMAL, TANGENT deltas) and default weights | | GltfNode | A node: mesh, skin, children, translation, rotation, scale, weights | | GltfSkin | joints and their inverseBindMatrices, for meshes with JOINTS_0 and WEIGHTS_0 | | GltfAnimation, GltfAnimationChannel, GltfAnimationSampler | Channels targeting a node's translation, rotation, scale or weights, sampled LINEAR, STEP or CUBICSPLINE |

Not supported

Each of these throws UnsupportedError naming what it found:

  • Compression: LZHAM, brotli (a WebGL build's .br files: decompress them first), zstd.

  • Containers: UnityArchive, zip archives (extract the zip first).

  • Encrypted bundles (UnityCN and other game-specific encryption), and the containers of games that modified the format.

  • One bundle that unpacks to more than 0x7fffffff bytes (2 GiB).

  • A class reader for a version it has no layout for:

    • before its "From" version in Classes (Texture2D has none);
    • a version-stripped file where the bytes do not decide the layout (Version-stripped files).

    readTypeTree() still works on such files.

  • An editor file (BuildTarget.NoTarget), read by a class reader that reads player data only:

    • the readers of Texture2D, MovieTexture, MonoScript, MonoBehaviour, Shader, Sprite, SpriteAtlas, AudioClip, Mesh, Avatar, AnimatorController, Animator, AnimatorOverrideController, AnimationClip, Animation, GameObject, Transform, RectTransform, MeshFilter, MeshRenderer and SkinnedMeshRenderer;
    • Material's reader, from Unity 2022.1 on.

    readTypeTree() reads editor files.

  • A Mesh whose vertices or triangles cannot be decoded: a submesh of lines or points, a vertex format Unity does not define, bone weights in an integer format or more than four per vertex (AssetStudio throws for each). readMesh() still reads its fields. A submesh whose baseVertex takes an index past the vertices throws CorruptError.

Out of scope for this package:

  • decoding audio or video;
  • converting meshes to OBJ or glTF (the glTF writer here only writes what it is given);
  • writing or repacking bundles;
  • image encoding.

Texture and sprite pixels, and PNG encoding, are in unity-asset-reader-texture.

How it is tested

Bundles built by the Unity editor from our own projects (the fixtures) are read and compared with what UnityPy reads from the same files. The class readers are also checked against readTypeTree() and, where noted, against AssetStudio and Unity's own type trees.

| | Unity versions | |---|---| | Tested on editor-built fixtures | 2019.4.41f2, 2020.3.30f1 and 6000.3.25f1: SerializedFile formats 21 and 22, UnityFS formats 7 and 8, LZ4, LZMA and uncompressed blocks, with and without type trees, and version-stripped | | Tested format-23 metadata, generic type-tree dumps, Sprite and SpriteAtlas | 6000.6.4f1: five fixtures, compared with UnityPy 1.25.4. unity-asset-reader-texture cuts the sprites such an atlas holds (packedSprites()) | | Tested Shader | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: DX11, GLES3 and Vulkan builds, and Metal from 2020.3 and 6000.3, against readTypeTree(); every Shader layout from 2019.1 to 6000.6 against UnityPy's reading of a synthetic object | | Tested Mesh skin and blend shapes | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: a mesh with up to four bone influences per vertex and two blend shapes, plain and compressed (not 2020.3), against UnityPy's decoded skin and AssetStudio's (not 6000.6), and readTypeTree() | | Tested Avatar, AnimatorController, Animator, AnimatorOverrideController | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: a humanoid and a generic avatar, a controller with two layers, a mask, a sub-state machine, 1D, 2D and direct blend trees and behaviours, an override controller, typed and without type trees, against readTypeTree(); every layout from 2019.1 to 6000.6 (the Animator's patch-release gates included) against Unity's own type trees | | Tested AnimationClip | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: a legacy clip with every curve kind and Mecanim clips whose curves land in the streamed, dense and constant parts, with bindings, a sprite swap and events, typed and without type trees, against readTypeTree(); every layout from 2019.1 to 6000.6 (the split curve count's patch-release gates included) against Unity's own type trees | | Tested GameObject, Transform, MeshFilter, MeshRenderer, SkinnedMeshRenderer | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: two prefabs (a skinned hierarchy with a mesh renderer and a humanoid one), typed and without type trees, and the animator fixtures' GameObjects and Transforms, against readTypeTree(); every layout from 2019.1 to 6000.6 against Unity's own type trees | | Tested Animation | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: a legacy Animation component listing a Mecanim clip, every field away from its default, typed and without type trees, against readTypeTree(); every layout from 2019.1 to 6000.6 against Unity's own type trees | | Tested RectTransform | 2019.4.41f2, 2020.3.30f1, 6000.3.26f1 and 6000.6.4f1: a Canvas with three children, their anchors set, typed and without type trees, against readTypeTree(); every layout from 2019.1 to 6000.6 against Unity's own type trees | | Tested on unit tests only | The class readers' version gates from 3.4 to 6000.6 and their refusals (see Version-stripped files and Not supported); SerializedFile formats 6, 8 and 15 | | Handled in code, no test | The rest of SerializedFile formats 2 to 22; Texture2D's layouts before 3.4 (gates at 2.6 and 3.0) |

Requirements

  • Browsers: any browser with ES2020 (bigint) and TextDecoder, and for gzip and zlib DecompressionStream. Every current browser has all three.
  • Node.js: 20.19+ or 22.12+ (engines: ^20.19.0 || >=22.12.0), for both import and require.
    • lzma1 is published as ES modules only, so require("unity-asset-reader") needs a Node.js that can require() an ES module (#172).
    • CI tests on 20.19.0 and 22.12.0.

Acknowledgements

  • AssetStudio (MIT, © Perfare, RazTools, Razviar): the bundle, SerializedFile, type tree and class readers are hand-ported from it; each ported file names its source.
  • UnityPy (MIT, © K0lb3): generates the test goldens, and is the source of the UnityFS header version gates, the [SerializeReference] registry reading and the common-string table.
  • AssetRipper TypeTreeDumps and Tpk (Tpk: MIT): indirectly, the type tree data in UnityPy's TPK table, which the common strings and several version gates come from.
  • lzma1 (MIT) for LZMA: the one runtime dependency.

The full list is in the repository README, and a comparison with similar npm packages in COMPARISON.md.

License

MIT. This package is a derivative port of AssetStudio (MIT) and uses UnityPy (MIT) as a secondary reference. Their copyright notices are in NOTICE.