Adding Existing Script to Entity Via Code


I was trying to add a script programmatically to dynamically generated entities, but was unable to do so. Essentially, this is for a multiplayer game where I need the receiver script to be attached to every enemy object that appears in the scene, and I can’t use the editor since said enemy objects are generated through code. I looked around on the forums a bit, but wasn’t able to find topics that add scripts that already exist, and instead these use the create command. How would I go about adding a script programmatically if it already exists in the assets directory?

Hi @DevilZ,

Here is the script component API call to add a script programmatically, together with an example:

Create I am aware how to do. I need to add a script that is already there in my assets dir.

Yes, create is for scripts that are already there in your assets.

And in the name field @Leonidas, we have to enter the name of the script without .js correct, such as “receiver” for receiver.js?

You need to pass the script type name, which you can easily grab by opening your script file and finding the following line (usually it’s the first line):

var BtnStates = pc.createScript('btnStates');

In this case the script type name is btnStates.

Perfect thank you. Will test and revert.

1 Like