(Solved) Creating an object by name, from a structure variable

Hello!

I am trying to spawn random objects in my game, from an Object Group. I using the Create Object by Name action, but the objects in the group do not have a naming convention of a string ending with a number. So, I am using the approach of creating a structure variable, which keeps a number as the ‘key’, and the object name in the group as the ‘value.’ My approach is similar to the answer in this post: https://forum.gdevelop.io/t/create-random-enemies-from-a-group/12348/5

However, I’m noticing that when I try to create the object like this:

VariableString( Enemies[ ToString(Random(2)) ] )

the object does not show up on the screen. For example, here is my screenshot of the code for that action:

The structure variable is called SpawnableArray (I initially was going to make it an array rather than a structure), and the highest index is 2. I also noticed that if I display the value of VariableString(SpawnableArray.2) as text on the screen, a proper name shows up in quotation mark, but it seems like the it chokes when trying to use that name to create an object.

Here is my structure variable and the object group, so you can see the object names (I don’t have all of them in the structure variable, I just wanted to start by adding a few to make sure I could spawn them):
https://ibb.co/4TZfPVk
Any ideas about where I might be going wrong?

Thanks so much!

Isn’t the index a numerical value (ToString is extra)?
And how does you Random expression work? Shouldn’t it be a range?

Don’t put quotation marks around your strings in the variable editor… I believe that will add literal quotation marks to the string… which would not match the names of your objects.

1 Like

This post was flagged by the community and is temporarily hidden.

@ElementerTheDragon, it’s “VariableString”. Check in GDevelop first if you’re not sure and before you post please…


Yes. It should be VariableString(SpawnableArray[Random(2)])


Random(n) randomly selects a number from 0 and n. It’s the same as RandomInRange(0,n)


image

As @krunkster wrote, you don’t have the quotation marks in your variable declaration.


If you’re going to select a random group, make it an array. A structure is better for key-value pairs, where the key is a string. It also means you won’t have to worry about the indexes - with a structure, if you remove one of the children, you’ll need to remember to renumber the other children.

2 Likes

@MrMen Ahh, ok. That’s a really good point about using an array instead. For this project, I don’t think the children will be removed, so I hadn’t thought about that consideration. Thanks so much!

@krunkster This solved it for me…thanks!

Thanks everyone for responding! @Zune @ElementerTheDragon I really appreciate your time and help, and sorry about not responding all in one post at first…still learning my way around :slight_smile: