Components

All classes inherited from Component are called Component Classes. The objects in a Component Class are called Components. Components are implement according to the Cocos Creator 3D Entity Component (EC) system.

The component class must inherit from a cc class. Example:

import { Component } from "cc";

@ccclass("MyComponent")
class MyComponent extends Component {

}

Component creation and destruction

The life cycle of a component is completely controlled by the node. Unlike ordinary class objects, components cannot be created by constructors:

const component = new MyComponent(); // Error: The component cannot be created by the constructor

Conversely, components must be created by nodes:

const myComponent = node.addComponent(MyComponent);

After this, the component is said to be attached to the node. Components are always attached to a node, except for:

  • Before the end of the constructor of the component class.
  • After the component is removed from the node.

Call the Node.removeComponent method to remove the specified component and destroy it. Example"

import { Component } from "cc";

@ccclass("MyComponent")
class MyComponent extends Component {
    constructor () {
        console.log(this.node.name); // Error: The component is not attached to the node
    }

    public printNodeName () {
        console.log(this.node.name);
    }
}

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const myComponent = node.addComponent(MyComponent);
myComponent.printNodeName(); // Correct
node.removeComponent();
myComponent.printNodeName(); // Error: The component is not attached to the node

results matching ""

    No results matching ""