How should I save the Meshes generated inside a ScriptableObject
Asked Answered
C

1

0

I have a ScriptableObject, saved as a .asset, and I want it to contains an array of generated meshes.

public class myObject : ScriptableObject
{
	[SerializeField] Mesh[] myMeshes;
	void Construct ( int count )
	{
		myMeshes = new Mesh[count];
		for( int i=0 ; i<count ; i++ )
		{
			myMeshes = new Mesh();
			// Filling the mesh with vertices and triangles
		}
	}
}

I want my meshes to be saved, but I will have hundreds of .asset, and if I save them externally, I will have tens thousand meshes and as much files.

→ Is there a way to save the meshes inside my ScriptableObject’s .asset file, so they are saved/loaded properly when opening/closing Unity?

Crevice answered 22/11, 2023 at 16:27 Comment(2)

Shouldn't this work right out of the box? Did you tried to make the array public? Though [SerializeField] should have the same effect...

Hammerfest

Well this don't seems to work. When trying to reach the meshes, all I got is an array of null references.

Crevice
N
0

Meshes are assets like Textures or GameObjects. They need to be saved seperately as asset to the project or they will be lost once you change the gamemode.

Keep in mind that a ScriptableObject also has the OnEnable callback, so you could reconstruct your meshes at runtime. If you want to create them at edit time, you have to save them as assets with AssetDatabase.

edit

Just read your concern about having hundreds of asset files. You can add assets to a single asset file with AssetDatabase.AddObjectToAsset. Pretty much the same way Unity handles the importing of an fbx file. It adds the imported mesh as subasset to the actual fbx asset. The fbx asset isn’t even included in the build, only the subassets that are referenced somewhere.

Nonrepresentational answered 6/2 at 12:41 Comment(2)

Keep in mind that Mesh also has a name property which you should set to a meaningful name before adding it to your asset.

Nonrepresentational

It works, well I saved them in separate files than myObject's one, because the assets become all shuffles in the same file and I have to search myObject amongs maaany meshes. But it works. Thanks. :)

Crevice

© 2022 - 2024 — McMap. All rights reserved.