Home > OS >  how can i get an empty gameobject and replace its sprite with a random card sprite?
how can i get an empty gameobject and replace its sprite with a random card sprite?

Time:01-26

I am trying to make blackjack in unity and the first thing im going to start out with is trying to have an assortment of empty gameobjects on the screen and when i click a button they will take a random card sprite from the folder of 52 prefabs i made, and make that gameobjects sprite be the card. it would be really inefficient to load each sprite into each gameobject individually, so is there a way i can pull it from the folder by itself?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cardstuff : MonoBehaviour
{
    void Start()
    {
        spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
    }
    public SpriteRenderer spriteRenderer;
    public Sprite currentCards;
    
    public void ChangeSprite()
    {
        spriteRenderer.sprite = currentCards;
        Debug.Log("changeSprite Initiated");
    }



    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ChangeSprite();
        }
    }










}

CodePudding user response:

You could follow the docs here and do something like this:

public class cardstuff : MonoBehaviour
{
    private Object[] deckOfCards;
    public SpriteRenderer spriteRenderer;
    public Sprite currentCard;

    void Awake() {
        // load all sprites from "Resources/Sprites/"
        deckOfCards = Resources.LoadAll("Sprites", typeof(Sprite));
        spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
    }
    
    public void ChangeSprite() {
        spriteRenderer.sprite = deckOfCards[Random.Range(0, deckOfCards.Length)];
        Debug.Log("card sprite changed");
    }

    void Update() {
        if (Input.GetMouseButtonDown(0))
            ChangeSprite();
    }
}
  • Related