4
\$\begingroup\$

I need to add one assest multiple times in my scene similar to the blender array tool and I was wondering what is the best way to do this because adding each asset individually and setting there locations doesn't seem like the best way to do it. I need to:

  • Create multiple sprites quickly
  • Be able to set the distance between the sprites
  • Set the number of sprites

How can I do this in the editor preferably without any plugins?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

If you want to create an array of this gameobject, you can do this as follows:

int Size = 10;     //Number of objects
GameObject[] Tiles = new GameObject[Size];

Let's assume you have created a prefab, called "Tile". If we want to initialize the array's gameobjects, we could do it like this:

//Loop for the entire size of the array, 10 in this case
for (int i = 0; i < Size; i++)
{
    //Create the game object
    Tiles[i] = GameObject.Instantiate (Resources.Load ("Tile")) as GameObject;  

    //Position it in the scene
    Tiles[i].transform.position = new Vector3(i * 0.32f, 0, 0);
}

If you assign the following script to the Start() function of a gameobject in your scene, you will see 10 Tile prefab objects appear when you Run your game.

\$\endgroup\$
1
\$\begingroup\$

Have a look into the Builder Pattern. It wraps up all that complex construction for you.

Builders are best driven by some kind of external textual or binary map data file, from which are read in various shorthand specs for each entity.

So in other words with this...

class SoldierBuilder //singleton
{
     function build()
     {
       //encapsulates a bunch of object creations, some of which create their own subobjects, etc. in order to build this whole soldier
     }
}

you would do something like

for each (record in soldierToBeBuiltRecords) //comes from a data file
   builder.build(record)

Bear in mind that for instance you might have two different builders, a SoldierBuilder and a WeaponBuilder. Then the SoldierBuilder might utilise the WeaponBuilder within it's own construction code, in order to build weapons for the soldiers as spec'ed in the soldier data, aside from using other parameters therein to construct the soldier itself.

You can use the same builder both at level setup and during runtime. And you can use it for predefined (data-specified) entities, or dynamic entities whose specs your game logic may decide at runtime.

As for setting the distance between sprites, I guess that should be a distinct bit of logic coded in the way you want it. It doesn't really have anything to do with construction, but rather positioning in relation to existing entities. Your builder's focus should only be within the context of the entity itself.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .