Adding a mesh through code

Well, I’m stumped. I’ve imported an FBX: “SpritePlane”, with a mesh “Plane01”, to a folder “_Meshes” in my Assets folder. Now I want to add it to my MeshFilter component in script. How do I do this?

I’ve gotten this far:

Plane.AddComponent<MeshFilter>();
Plane.AddComponent<MeshRenderer>();
Plane.GetComponent<MeshFilter>().mesh = ...

What do I do now? Any help at this point would be seriously appreciated.
Thanks-
O

You need to build a Mesh object, fill the triangles and vertices at least and rebuild its normals.

mesh.RecalculateNormals();

Plane.GetComponent().mesh = mesh;

I assumed this was only necessary if you wanted to build the mesh completely from scratch, like if you wanted to generate a custom mesh based on some runtime variables, like dynamic terrain, or custom volume shapes, etc (things you couldn’t have imported).

Is this process still necessary if I have the mesh imported somewhere as an FBX? Can I just grab it from the Resources folder?

Thanks a lot for the help-

drop your mesh in the resources folder and load it at runtime and assign it to the mesh filter. ( Resources.Load())

Thanks a lot, I’ll give this a try tonight.

If I recall correctly, there isn’t any importers at runtime for meshes. I think there is support for this in Unity Pro with Asset bundles. You would need to write a script that that pulls the binary data and parses it into a mesh to get runtime importing to work.

In order to do this correctly, you would need to cover a few things…

Unity - Scripting API: WWW // would load the file
Unity - Scripting API: WWW.bytes // use the www.bytes variable to get the bytes into a data set.

BitConverter Class (System) | Microsoft Learn // use the System.BitConverter methods to convert the bytes to usable data.

That would be the begining of it. You would then have to write everything to convert the document from whatever file format you are using to mesh data.

Next, you would need to use the WWW object to import JPG or PNG files, (or extract them from the 3d file) and assign them to Texture2D objects or directly to the material.

As part of all that you need to import and parse the materials and generate your materials based on what you find in the 3d file.

It is not a fun nor easy process.

I’m sure I’m just misunderstanding it, but I’m having trouble getting that to work. I’ve got an FBX: “SpritePlane” in the root of my Resources folder, with a mesh “Plane01”. (the object that I want to receive the mesh is called “Plane”):

Neither:

Plane.GetComponent().mesh = Resources.Load(“SpritePlane”) as Mesh;

nor

Plane.GetComponent().mesh = Resources.Load(“Plane01”) as Mesh;

…are working. they don’t produce errors, but they don’t assign the mesh (which stays Null). Originally I left the casting bit off, but I got an error telling me I should. What am I doing wrong?

Thanks!

I get the same problem