Search Unity

how to align my cards like this ?

Discussion in 'Scripting' started by blesstc, Oct 23, 2017.

  1. blesstc

    blesstc

    Joined:
    Sep 25, 2017
    Posts:
    10
    hi all

    I have following code for my card game and I need to align the cards like below and not getting an idea how to show. I am very new to Unity and C#
    The image can be seen here
    https://imgur.com/a/7H6nZ



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class test : MonoBehaviour {
    5. public Sprite[] card;
    6. void Awake()
    7. {
    8. // load all frames in cards array
    9. card = Resources.LoadAll<Sprite>("CardDeck_");
    10. }
    11. void Start ()
    12. {
    13. // create the object
    14. GameObject cards = new GameObject();
    15. // add a "SpriteRenderer" component to the newly created object
    16. cards.AddComponent<SpriteRenderer>();
    17. cards.GetComponent<SpriteRenderer>().sprite = card[8];
    18. cards.GetComponent<SpriteRenderer>().sprite = card[15];
    19. }
    20. }
     

    Attached Files:

  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    You would use a for loop to arrange those sprites. But you're not to that point yet. Right now, you're just creating one card, whose image looks like sprite 8 no actually sprite 15.

    So the next step is probably to change this to a List<GameObject> cards, or better yet, List<Transform> cards. Then create an object for card[0], and add it to this list. Then also create an object for card[1], and add that to the list as well. Then, because you're already starting to get tired of copying & pasting by this point, change it to use a for-loop to create objects for all the cards you have.

    Once you've done all that, then you should be asking how to position these cards so they're not all at 0,0,0. And it'll be pretty easy by that point — just a bit of math based on cards.Count, and use that to assign the position of each new card.

    If you haven't done it already, I highly recommend working through both some Unity tutorials (follow the Learn link at the top of this page), and some C# tutorials. Trying to learn this stuff as you go is going to be much, much harder than getting some instruction up front.

    Good luck with your game, and enjoy the journey!