βš™οΈ getComponent

What is it?

getComponent is an API function that allows you to retrieve the first component of a specific type from an object. There is also getComponents, which returns all components of that type on the object.

πŸ“– Syntax

const comp = getComponent(obj, "Type");
const comps = getComponents(obj, "Type");

βœ… Basic Example

Suppose you have an enemy with an AudioSource component:

{
  "type": "enemy",
  "name": "Enemy1",
  "x": 100,
  "y": 200,
  "components": [
    {
      "type": "AudioSource",
      "clip": "explosion.wav",
      "volume": 0.8,
      "loop": false
    }
  ]
}

From a script you can access the component like this:

const audio = getComponent(obj, "AudioSource");
if (audio) {
  audio.playing = true;   // play sound
  audio.volume = 0.5;     // change volume
}

βœ… Example With Multiple Components

const movers = getComponents(platform, "PlatformMover");
movers.forEach(m => {
  m.speed = 200;
});

πŸ“Œ Notes

- If the object has no components, the function returns null (in getComponent) or an empty array (in getComponents).
- Use it whenever you need to directly modify component properties.
- You can also use getComponentFromObject("name", "Type") to access a component from an object by name.