Create a model from code

You can create models in scripts at runtime. You can do this in several different ways, including:

  • creating a model from an asset

  • creating a procedural model using built-in geometric primitives (eg a sphere or cube)

  • instantiating a prefab that contains a model (see )

  • Create a new, empty synchronous script. For full instructions, see Create a script.

  • In the script, load the model using its asset URL. For example:
Tip

To find the model's asset URL, in the Asset View, move the mouse over the model.(Get asset URL

  • Add the script as a script component to any entity in the scene. It doesn't matter which entity you use. For instructions, see .
  • In the Asset View, right-click the model you want to create at runtime and select Include in build as root asset.

This makes sure the asset is available for the script to use at runtime. For more information, see Manage assets.

Add new script

  • Add the script as a script component to any entity in the scene. It doesn't matter which entity you use. For instructions, see .

  • In your script, instantiate an empty entity and an empty model. For example:
  1. var entity = new Entity();
  2. SceneSystem.SceneInstance.RootScene.Entities.Add(entity);
  3. // Create a model and assign it to the model component.
  4. var model = new Model();
  5. entity.GetOrCreate<ModelComponent>().Model = model;
  • In your script, create a procedural model using built-in geometric primitives (eg a sphere or cube). For example:
Note

To use the code above, make sure you add using Xenko.Extensions to the top of your script.

Alternatively, create a mesh using your own vertex and index buffers. For example:

  1. mesh = new Mesh { Draw = new MeshDraw { /* Vertex buffer and index buffer setup */ } };
  2. model.Meshes.Add(mesh);
Note

Finally, you need to give the model one or more materials. There are two ways to do this.

  • In your code, load one or more materials and add them to the model. Because models can use multiple materials (one for each mesh in the model), use Mesh.MaterialIndex to specify which materials in the list are used for which mesh.

    For example:

Include in build as root asset

This makes sure the asset is available for the script to use at runtime. For more information, see .

Option 2: Create new materials in code

For example:

  1. // Create a material (eg with red diffuse color).
  2. var materialDescription = new MaterialDescriptor
  3. {
  4. {
  5. DiffuseModel = new MaterialDiffuseLambertModelFeature(),
  6. Diffuse = new MaterialDiffuseMapFeature(new ComputeColor { Key = MaterialKeys.DiffuseValue })
  7. }
  8. };
  9. var material = Material.New(GraphicsDevice, materialDescription);
  10. material.Parameters.Set(MaterialKeys.DiffuseValue, Color.Red);