# ScriptComponent

Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Script

Source: https://github.com/playcanvas/engine/blob/f059dc005842f76e052cdf44d8370c8c7ec475ac/src/framework/components/script/component.js#L47

The ScriptComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to have custom behavior by attaching scripts
written in JavaScript (or TypeScript).

You should never need to use the ScriptComponent constructor directly. To add a
ScriptComponent to an [Entity](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent):

```javascript
const entity = new Entity();
entity.addComponent('script');
```

Once the ScriptComponent is added to the entity, you can access it via the
[Entity#script](https://api.playcanvas.com/engine/classes/Entity.md#script) property:

```javascript
// Option 1: Add a script using the name registered in the ScriptRegistry
entity.script.create('cameraControls');

// Option 2: Add a script using the script class
entity.script.create(CameraControls);
```

For more details on scripting see the [Scripting Section](https://developer.playcanvas.com/user-manual/scripting/)
of the User Manual.

## Accessors

### scripts

```ts
get scripts(): readonly Script[]
set scripts(value: readonly Script[])
```

Gets the array of all script instances attached to an entity. Use create, destroy and move to
change attached scripts or their order.

## Methods

### create

```ts
create<T extends Script>(type: Object, args?: object): T | null
```

Create a script instance of the specified class and attach it to the entity's script
component. The result is typed as an instance of that class, so no cast is needed.

**Parameters**

- `type` (`Object`): The script class.
- `args` (`object`, optional): Object with arguments for a script.
    - `args.attributes` (`any`, optional): Object with values for attributes (if any), where key is
      name of an attribute.
    - `args.enabled` (`boolean`, optional): If script instance is enabled after creation. Defaults to
      true.
    - `args.ind` (`number`, optional): The index where to insert the script instance at. Defaults to
      -1, which means append it at the end.
    - `args.preloading` (`boolean`, optional): If script instance is created during preload. If true,
      script and attributes must be initialized manually. Defaults to false.
    - `args.properties` (`any`, optional): Object with values that are **assigned** to the script
      instance.

**Returns** [`T`](https://api.playcanvas.com/engine/classes/ScriptComponent.md#createt) `| null`: Returns an instance of the class if successfully attached to the entity,
or null if it failed because a script with the same name has already been added.

**Example**

```ts
const controller = entity.script.create(PlayerController, {
    properties: {
        speed: 4
    }
}); // PlayerController | null
```

```ts
create(name: string, args?: object): Script | null
```

Create a script instance by name and attach it to the entity's script component. The name
is looked up in the application's [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md).

**Parameters**

- `name` (`string`): The name of the script.
- `args` (`object`, optional): Object with arguments for a script.
    - `args.attributes` (`any`, optional): Object with values for attributes (if any), where key is
      name of an attribute.
    - `args.enabled` (`boolean`, optional): If script instance is enabled after creation. Defaults to
      true.
    - `args.ind` (`number`, optional): The index where to insert the script instance at. Defaults to
      -1, which means append it at the end.
    - `args.preloading` (`boolean`, optional): If script instance is created during preload. If true,
      script and attributes must be initialized manually. Defaults to false.
    - `args.properties` (`any`, optional): Object with values that are **assigned** to the script
      instance.

**Returns** [`Script`](https://api.playcanvas.com/engine/classes/Script.md) `| null`: Returns the script instance if successfully attached to the entity,
or null if it failed because a script with the same name has already been added or if the
name cannot be found in the [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md).

**Example**

```ts
entity.script.create('playerController', {
    attributes: {
        speed: 4
    }
});
```

### destroy

```ts
destroy(nameOrType: string | typeof Script): boolean
```

Destroy the script instance that is attached to an entity.

**Parameters**

- `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md).

**Returns** `boolean`: If it was successfully destroyed.

**Example**

```ts
entity.script.destroy('playerController');
```

### get

```ts
get<T extends Script>(type: Object): T | null
```

Get a script instance (if attached) by its class. The result is typed as an instance of that
class, so no cast is needed.

**Parameters**

- `type` (`Object`): The script class.

**Returns** [`T`](https://api.playcanvas.com/engine/classes/ScriptComponent.md#gett) `| null`: If a script of the class is attached, the instance is returned. Otherwise
null is returned.

**Example**

```ts
const controller = entity.script.get(PlayerController); // PlayerController | null
```

```ts
get(name: string): Script | null
```

Get a script instance (if attached) by its name.

**Parameters**

- `name` (`string`): The name of the script.

**Returns** [`Script`](https://api.playcanvas.com/engine/classes/Script.md) `| null`: If a script with the name is attached, the instance is returned.
Otherwise null is returned, including while a script declared by name is still awaiting its
class to be added to the [ScriptRegistry](https://api.playcanvas.com/engine/classes/ScriptRegistry.md).

**Example**

```ts
const controller = entity.script.get('playerController');
```

### has

```ts
has(nameOrType: string | typeof Script): boolean
```

Detect if script is attached to an entity.

**Parameters**

- `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md).

**Returns** `boolean`: If script is attached to an entity.

**Example**

```ts
if (entity.script.has('playerController')) {
    // entity has script
}
```

### move

```ts
move(nameOrType: string | typeof Script, ind: number): boolean
```

Move script instance to different position to alter update order of scripts within entity.

**Parameters**

- `nameOrType` (`string | typeof` [`Script`](https://api.playcanvas.com/engine/classes/Script.md)): The name or class of the [Script](https://api.playcanvas.com/engine/classes/Script.md).
- `ind` (`number`): New position index.

**Returns** `boolean`: If it was successfully moved.

**Example**

```ts
entity.script.move('playerController', 0);
```

## Events

### EVENT_CREATE

```ts
static EVENT_CREATE: string = 'create'
```

Fired when a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance is created and attached to the script component.
This event is available in two forms. They are as follows:

1. `create` - Fired when a script instance is created. The name of the script type and the
script type instance are passed as arguments.
2. `create:[name]` - Fired when a script instance is created that has the specified script
type name. The script instance is passed as an argument to the handler.

**Example**

```ts
entity.script.on('create', (name, scriptInstance) => {
    console.log(`Instance of script '${name}' created`);
});
```

**Example**

```ts
entity.script.on('create:player', (scriptInstance) => {
    console.log(`Instance of script 'player' created`);
});
```

### EVENT_DESTROY

```ts
static EVENT_DESTROY: string = 'destroy'
```

Fired when a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance is destroyed and removed from the script component.
This event is available in two forms. They are as follows:

1. `destroy` - Fired when a script instance is destroyed. The name of the script type and
the script type instance are passed as arguments.
2. `destroy:[name]` - Fired when a script instance is destroyed that has the specified
script type name. The script instance is passed as an argument.

**Example**

```ts
entity.script.on('destroy', (name, scriptInstance) => {
    console.log(`Instance of script '${name}' destroyed`);
});
```

**Example**

```ts
entity.script.on('destroy:player', (scriptInstance) => {
    console.log(`Instance of script 'player' destroyed`);
});
```

### EVENT_DISABLE

```ts
static EVENT_DISABLE: string = 'disable'
```

Fired when the script component becomes disabled. This event does not take into account the
enabled state of the entity or any of its ancestors.

**Example**

```ts
entity.script.on('disable', () => {
    console.log(`Script component of entity '${entity.name}' has been disabled`);
});
```

### EVENT_ENABLE

```ts
static EVENT_ENABLE: string = 'enable'
```

Fired when the script component becomes enabled. This event does not take into account the
enabled state of the entity or any of its ancestors.

**Example**

```ts
entity.script.on('enable', () => {
    console.log(`Script component of entity '${entity.name}' has been enabled`);
});
```

### EVENT_ERROR

```ts
static EVENT_ERROR: string = 'error'
```

Fired when a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance had an exception. The handler is passed the script
instance, the exception and the method name that the exception originated from.

**Example**

```ts
entity.script.on('error', (scriptInstance, exception, methodName) => {
    console.log(`Script error: ${exception} in method '${methodName}'`);
});
```

### EVENT_MOVE

```ts
static EVENT_MOVE: string = 'move'
```

Fired when the index of a [Script](https://api.playcanvas.com/engine/classes/Script.md) instance is changed in the script component.
This event is available in two forms. They are as follows:

1. `move` - Fired when a script instance is moved. The name of the script type, the script
type instance, the new index and the old index are passed as arguments.
2. `move:[name]` - Fired when a specifically named script instance is moved. The script
instance, the new index and the old index are passed as arguments.

**Example**

```ts
entity.script.on('move', (name, scriptInstance, newIndex, oldIndex) => {
    console.log(`Script '${name}' moved from index '${oldIndex}' to '${newIndex}'`);
});
```

**Example**

```ts
entity.script.on('move:player', (scriptInstance, newIndex, oldIndex) => {
    console.log(`Script 'player' moved from index '${oldIndex}' to '${newIndex}'`);
});
```

### EVENT_REMOVE

```ts
static EVENT_REMOVE: string = 'remove'
```

Fired when the script component has been removed from its entity.

**Example**

```ts
entity.script.on('remove', () => {
    console.log(`Script component removed from entity '${entity.name}'`);
});
```

### EVENT_STATE

```ts
static EVENT_STATE: string = 'state'
```

Fired when the script component changes state to enabled or disabled. The handler is passed
the new boolean enabled state of the script component. This event does not take into account
the enabled state of the entity or any of its ancestors.

**Example**

```ts
entity.script.on('state', (enabled) => {
    console.log(`Script component of entity '${entity.name}' changed state to '${enabled}'`);
});
```

## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md)

- `entity: Entity`
- `system: ComponentSystem`
- `get enabled(): boolean` · `set enabled(value: boolean)`
- `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler`
- `hasEvent(name: string): boolean`
- `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler`
- `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
- `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
