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 Use prefabs)
- Create a new, empty synchronous script. For full instructions, see .
- 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.
- 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 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:
var entity = new Entity();
SceneSystem.SceneInstance.RootScene.Entities.Add(entity);
// Create a model and assign it to the model component.
var model = new Model();
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:
mesh = new Mesh { Draw = new MeshDraw { /* Vertex buffer and index buffer setup */ } };
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:
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:
// Create a material (eg with red diffuse color).
var materialDescription = new MaterialDescriptor
{
{
DiffuseModel = new MaterialDiffuseLambertModelFeature(),
Diffuse = new MaterialDiffuseMapFeature(new ComputeColor { Key = MaterialKeys.DiffuseValue })
}
};
var material = Material.New(GraphicsDevice, materialDescription);
material.Parameters.Set(MaterialKeys.DiffuseValue, Color.Red);