Distribute Sprites Evenly on Scene

Hey,

Firstly, a heads up, I’m pretty new to unity!

Essentialy what I am trying to do is simulate drawing cards in to a hand with no maximum size.
I want to be able to add new cards to the hand area and have them evenly distributed along X depending on the amount of cards but without going off screen. So I figure the gap would be smaller each time.

For example with a small hand the cards would be as so: X X X X
A larger hand would be: XXXXXXX

If that makes sense…

I’m not sure how to achieve this, although it’s probably really simple. Here is what I have so far.

public class Generate : MonoBehaviour {
    public Sprite sprite;
    public int cardcount = 0; //total cards drawn
    public float cardScale = 0.1f; //rendered sprite scale


    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        

        if(Input.GetKeyDown(KeyCode.N)){
            //Create GameObject
            GameObject go = new GameObject("DrawCard" + cardcount);
            SpriteRenderer renderer = go.AddComponent<SpriteRenderer>();
            //Render Sprite
            renderer.sprite = sprite;
            //Transform and Distribute
            go.transform.localScale= new Vector3(cardScale,cardScale,cardScale);
            float DistPos = cardcount + (cardcount * 0.2f) ;
            go.transform.position= new Vector3(DistPos,0f,0f);

            cardcount = cardcount + 1;

It creates the cards on screen as planned but the continue off screen.

Thank you for help in advance!

Not the most beautiful code in the world, but it should get you started.

    void distributeCards()
    {
        // Get width of screen
        Vector3 leftBottom = Camera.main.ViewportToWorldPoint(Vector3.zero);
        Vector3 rightTop = Camera.main.ViewportToWorldPoint(Vector3.one);
        Vector3 pos = Camera.main.ViewportToWorldPoint(Vector3.one * 0.5f);

        // Calculate spacing
        float space = (Mathf.Abs(rightTop.x) + Mathf.Abs(leftBottom.x)) / (cardcount);

        // Calculate position of first card
        pos.x -= space * (cardcount - 1) / 2f;

        for (int i = 0; i < cardcount; i++)
        {
            GameObject g = GameObject.Find("DrawCard" + i);

            g.transform.position = pos;

            pos.x += space;
        }
    }

Thank you so much! I can absolutely work with this.