Can I get component ID from constant or property, not just hardcoding it?

Suppose I have a game object and a factory in it, called “parts_factory”. To create an object with this factory I have to call something like:

factory.create("#parts_factory",  vmath.vector3(), nil, {}, nil)

If I want then to rename factory in the editor to any other name (like "spare_parts_factory) I also need to refactor the script because otherwise, it contains the wrong url. Is there any other way to get a component id except just hard-coding string, so I wouldn’t need to rename it in all the places I use it during refactoring? Otherwise, it becomes very tedious and difficult to refactor if a component is referenced from many places.

No, all references are automatically updated, except in scripts.

You can, in the script, declare a property “factory” which is an url. Then you can set that from the editor:

go.property("factory", msg.url())

and then you use it as usual:

factory.create(self.factory,  vmath.vector3(), nil, {}, nil)
2 Likes

Thanks for the answer, but as I understand it still won’t be refactored automatically if I rename a component.

Not yet, no. Perhaps we can do that in the future.
But it at least saves you from having multiple scripts.

2 Likes

You can also declare constants in a Lua module and use them.

If you are using it multiple places in the same script, then you should save the url string to a variable so you only have to change it in one place at the top of your script. Really you should do this for any constant value that you might ever possibly want to adjust.

If you are using the factory from other scripts, you can do the same for them.

Otherwise, just use search and replace (Ctrl+E in the Defold editor) and click “Replace All”. It should only take a couple of seconds.