How to instantiate objects through custom script attached to a empty object?

I am trying to instantiate objects based on button click and for that created a custom script that handles the UI adn instantiating of objects, nothing happens when I click the buttons, nothing, have given too much time on this till now, if its something silly, please forgive me.
Have attached the script too

Hi shitman027tm! To instantiate objects through a custom script attached to an empty object using Needle Engine, you need to ensure a few things are correctly set up.

  1. Script Binding: Ensure that your script is correctly linked to a button click event in the UI. This usually involves adding an event listener.
  2. Instantiation Logic: Use the instantiate method provided by Needle Engine along with appropriate parameters for the objects you want to create.
  3. Lifecycle Methods: Ensure your script has an appropriate lifecycle method such as start() or awake() to initiate the instantiation process.

Here’s an example of how your script might look:

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

export class MyInstantiateScript extends Behaviour {
    private prefab: GameObject; // Assign your prefab in the inspector or load dynamically

    start() {
        const button = document.getElementById("yourButtonId");
        if (button) {
            button.addEventListener("click", this.onButtonClick.bind(this));
        }
    }

    private async onButtonClick() {
        const instance = await GameObject.instantiate(this.prefab, {
            position: this.gameObject.position.clone(), // spawn at the position of this object
            parent: this.gameObject.parent, // or any other parent object
        });
        if (instance) {
            console.log("Object instantiated successfully!", instance);
        } else {
            console.error("Failed to instantiate object");
        }
    }
}

Troubleshooting Steps:

  • Ensure the button’s ID matches what you reference in your script.
  • Check the console for any error messages that may provide insights.
  • Verify that your prefab object is correctly assigned and available at runtime.

For further reference on instantiation specifics, you can check the API documentation (see the documentation).

If you continue to face issues, please share your button setup details or any console errors, and I’ll help you further!

1 replies left - Get a PRO license for more AI replies.
thread_EZuYQGGBsR48FIdEp7LZbQ4k
Reply to this message to continue the conversation

Hello @shitman027tm

You shared a C# script - however you need to write Typescript for Needle Engine. I would recommend you to take a look at the following page: Scripting Introduction for Unity Developers | Needle Engine Documentation

I was mad confused seeing all this, you are one gem of a human being, thanks

This topic was automatically closed 13 days after the last reply. New replies are no longer allowed.