1
\$\begingroup\$

I am creating a match card game in unity and I want to place cards in straight direction that is one below another and so on... But with my formula It's showing cards one after another.Please tell me whats wrong with my code. Following is my code -

    void SpawnCards(){
    int cardsinrow = 4;
    int cardsincolumn = cardslist.Count/cardsinrow;
    if(cardslist.Count % cardsinrow > 0)
        cardsincolumn += 1;
    float spacebetweencards = .2f;

    for(int i=0; i<cardslist.Count; i++){
        GameObject mc = Instantiate(memorycard, new Vector3((i%cardsinrow+(i%cardsinrow*spacebetweencards))-(cardsinrow/2f)+spacebetweencards, 0, (i/cardsinrow+(i/cardsinrow*spacebetweencards))-(cardsincolumn/2f)+spacebetweencards), memorycard.transform.rotation) as GameObject;
        mc.GetComponentInChildren<MemoryCard>().SetMemorycard(cardslist[i].texture, cardslist[i].number);
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Are you attempting to place them all in line with each other in a vertical direction? You can't just use a nested for loop? \$\endgroup\$
    – Savlon
    Dec 5, 2014 at 7:36
  • \$\begingroup\$ @Savlon Yes,I want to place them in vertical direction.But how can I achieve that.I am newbie in unity programming. \$\endgroup\$ Dec 5, 2014 at 7:39

1 Answer 1

1
\$\begingroup\$

I don't know if this helps you but this is a nested for loop that places a prefab object at an x and y location. The cardAmountX can be changed to whatever amount you want and it basically sets the number of columns you will have. The cardAmountY can also be change to whatever amount you want and it sets the number of rows you want.

Just be aware that these objects will be placed every unity unit and will not accommodate the size of your card prefab object. That will require a little tweaking but should not be too hard for you to figure out... if you can't figure it out then post a comment and I will add it.

Is this what you are looking for or have I misinterpreted everything you have said?

//The card prefab you have created goes into this Transform variable named prefab.
public Transform prefab;
//The amount of columns of cards you want it your game
public int cardAmountX = 1;
//The amount of rows of cards you want in your game
public int cardAmountY = 5;

void Start () 
{
    //Call the spawn cards method
    SpawnCards ();
}

void SpawnCards ()
{
    //Use a nested for loop to achieve your goal of columns x rows of cards
    for (int x = 0; x < cardAmountX; x++)
    {
        for (int y = 0; y < cardAmountY; y++)
        {
            //Instantiate your card prefab variable and set its position to the x and y
            Instantiate (prefab, new Vector3 (x, y, 0), Quaternion.identity);
        }
    }
}
\$\endgroup\$

You must log in to answer this question.

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