1
\$\begingroup\$

The situation is I work in my free time on one study project. I have resources of one game packed in it's own format. My intent was to use those with Unity without converting them into Unity's inner format.

But with brief analysis of Unity Api Reference I did not find anything that would help my in my efforts. Like I have custom binary files I would need to parse with Unity and upon that data create geometry, lights and so on using Unity's classes.

So I wonder if it's even possible? I would really appreciate if anyone would show make a hint on this subject

\$\endgroup\$
1
\$\begingroup\$

Almost any Unity component can be created completely code-based at runtime.

The documentation of the class Mesh has an example how to create a new 3d model just from binary data:

public class ExampleClass : MonoBehaviour {
    public Vector3[] newVertices;
    public Vector2[] newUV;
    public int[] newTriangles;
    void Start() {
        Mesh mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
        mesh.vertices = newVertices;
        mesh.uv = newUV;
        mesh.triangles = newTriangles;
    }
}

This code snippet does of course assume that the arrays newVertices, newUV and newTriangles are filled with the data read from your custom file formats. Any C# classes for file IO are also available from Unity, but when you want to work with the Unity asset management system and not against it, you might do well loading them as TextAssests which (despite the name) also work very well for binary data.

It also assumes that you already have a game object which already has a MeshFilter component. You can also create that at runtime:

GameObject my3dObject = new GameObject("My 3d object");
my3dObject.AddComponent<MeshFilter>();

Other Unity components like Light have similar ways to create them completely code-based.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Thanks, that really helped to wrap my head around. When I looked at unity api, I saw Resources.Load method, so I assumed it's the only way to load data from files. I didn't know the general IO is also available from Unity runtime. \$\endgroup\$ – Dmitry Tolmachov Nov 30 '15 at 14:34
  • 1
    \$\begingroup\$ I've deserialized custom binary assets using a TextAsset as Philipp suggests, and would definitely recommend this route over using basic IO to open files directly when possible. ".bytes" TextAssets are handy because you still get the convenience of working with Unity's inspectors and resource management - I don't need to write separate loading code that knows where the file gets placed when making a build versus running in editor, for example. \$\endgroup\$ – DMGregory Dec 1 '15 at 5:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.