Skip to content

Instantiating zcomps

zcomponents can be added to your Hierarchy using the interface; however, there are times when you might want to instantiate them programmatically.

For example, if you are creating an environment with flowers, you might want to create multiple instances of a flower zcomponent and place them randomly in your scene. Doing this manually would be time-consuming, so we recommend instantiating them through code using the following method.

  1. Import the zcomponent into your script:

    // Replace 'zcompExample' with your zcomponent name
    import zcompExample from "./zcompExample.zcomp";
  2. Create a new instance of the zcomponent:

    // Creating a new instance of the zcomponent using the context manager
    const zcompExampleInstance = new zcompExample(this.contextManager, {});
  3. Add the zcomponent instance to your scene - in this example, it is being added to a Group node:

    // Add the zcomponent instance to the 'myGroup' node
    this.zcomponent.nodes.myGroup.appendChild(zcompExampleInstance);

To showcase how to use instantiated zcomponents, in the video and snippet below we show how 1000 individual flower zcomponents can be added to a scene and (or) group within a behavior.

Instantiating a zcomponent

Example code

import { Behavior, zBehavior, zOnStart } from '@zcomponent/core';
import { Group } from '@zcomponent/three/lib/components/Group';
import Scene from './Scene.zcomp';
import Stem from './Stem.zcomp';
@zBehavior()
export class InstantiateStem extends Behavior<Group> {
protected zcomponent = this.getZComponentInstance(Scene);
@zOnStart()
private _init() {
this.instantiateStem();
}
private instantiateStem() {
const numStems = 1000;
const minRadius = 1;
const maxRadius = 15;
const minY = -0.5;
const maxY = 1;
for (let i = 0; i < numStems; i++) {
const angle = Math.random() * Math.PI * 2;
const radius = Math.random() * (maxRadius - minRadius) + minRadius;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const currentY = Math.random() * (maxY - minY) + minY;
const target = new Stem(this.contextManager, {});
target.position.value = [x, currentY, z];
this.zcomponent.nodes.StemGroup.appendChild(target);
}
}
}

To run this behavior in the editor as well as at runtime, check the Run at Design Time box when creating the behavior.