How to Instantiate Prefab in Scene every 5 seconds

I need a script in typescript to spawn a prefab in the scene every 5 seconds, I will attach this script as a component to an empty game object. Serialize so I can drop the asset into the component.

Here’s a TypeScript script for your requirement to instantiate a prefab in the scene every 5 seconds. This script will be attached to an empty game object, and you can serialize the prefab reference for easy assignment in the editor:

import { Behaviour, serializable, AssetReference } from "@needle-tools/engine";

export class PrefabSpawner extends Behaviour {
    @serializable(AssetReference)
    prefab?: AssetReference; // Serialized reference to the prefab

    private spawnInterval: number = 5000; // Interval in milliseconds
    private timer: number = 0;

    async update() {
        this.timer += this.context.time.deltaTime * 1000; // Convert delta time to milliseconds

        if (this.timer >= this.spawnInterval) {
            this.timer = 0; // Reset timer
            await this.spawnPrefab(); // Spawn the prefab
        }
    }

    private async spawnPrefab() {
        if (this.prefab) {
            await this.prefab.instantiate(); // Instantiate the prefab
        }
    }
}

Explanation:

  1. @serializable(AssetReference): This allows you to assign the prefab in the Unity editor directly to this variable.
  2. update(): This function runs every frame, accumulating time until it reaches 5000 ms (5 seconds).
  3. spawnPrefab(): This method is called to instantiate the prefab using the reference provided.

Next Steps:

  • Attach this component to an empty GameObject.
  • Assign the prefab that you want to spawn to the prefab field in the inspector.

Let me know if you need any further assistance!

3 replies left
thread_GSXubVGFXkf5qEsHZ88eLeAZ
Reply to this message to continue the conversation

Amazing, thank you!

You’re welcome, 0nederful! If you have any more questions or need further assistance with Needle Engine, feel free to ask. Happy coding!

2 replies left
thread_GSXubVGFXkf5qEsHZ88eLeAZ
Reply to this message to continue the conversation