Home > Mobile >  Set active true only on current element of the array
Set active true only on current element of the array

Time:12-01

I am learning Unity by building a simple card game.

I trying to display one card at the time using random function on the game object array.

I am using UI image component with sprite assets assigned to it while calling DealMyNewCard function on the button component.

I am expecting to see one card displayed at the time while still being able to repeat the process of randomly dealing the card.

using UnityEngine;

public class DealCard : MonoBehaviour
{

public GameObject[] dealtCard;
public int cardGenerate;

public void DealMyNewCard(){

   cardGenerate = Random.Range(2, 6);
   dealtCard[cardGenerate].SetActive(!dealtCard[cardGenerate].activeSelf);
  
}
}

The issue arises when I reach the top or higher card of the array because it overrides the other hierarchy components of the object and prevents the display of previous cards.

CodePudding user response:

My test script :

using UnityEngine;

public class DealCard : MonoBehaviour
{
    public GameObject[] dealtCard;
    public int cardGenerate;

[ContextMenu("Test DealMyNewCard()")] //for inspector test use
public void DealMyNewCard()
{
    cardGenerate = Random.Range(1, dealtCard.Length);
    HideAllCards();
    dealtCard[cardGenerate].SetActive(true);
}

private void HideAllCards()
{
    foreach (var card in dealtCard)
    {
        card.SetActive(false);
    }
}
}

enter image description here enter image description here Works fine for me:

enter image description here

CodePudding user response:

How about hide all cards before showing the dealt card? like:

public void DealMyNewCard()
{

   cardGenerate = Random.Range(2, 6);
   HideAllCards();
   dealtCard[cardGenerate].SetActive(true);
}

private void HideAllCards()
{
      foreach (var card in dealtCard)
      {
           card.SetActive(false);
      }
}

A more elegant way to show only one card at a time is using only one card game object in the hierarchy, and set it look each time you pick up a random card. Doing this way, you don't need to call SetActive() multiple times when dealting new card.

  • Related