Get all Children of an Object with a certain component
I am making a card game and when the cards are dealt they are attached to my Player1 Gameobject (This GO also has other things than cards attached to it). What I want to do is to find all the cards on the player and add them to an Array/List (The Card Gameobject have a "Card" class attached to them. This is what I have tried to do:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerGetCards : MonoBehaviour {
int x;
List<GameObject> Children;
TableMaster tMaster;
PlayerMaster pMaster;
string[] cards;
public List<GameObject> slots;
public void GetCards(bool durchgang)
{
pMaster = GetComponent<PlayerMaster>();
tMaster = pMaster.table.GetComponent<TableMaster>();
StartCoroutine(GetChildren(durchgang));
}
IEnumerator GetChildren(bool durchgang)
{
yield return new WaitForSeconds(1);
if(!durchgang)
{
x = 0;
foreach(Transform child in this.transform)
{
if(child.GetComponent<Card>())
{
AddChildCard(child.name);
x++;
}
}
}
else
{
x = 5;
foreach(Transform child in this.transform)
{
if (child.GetComponent<Card>())
{
AddChildCard(child.name);
x++;
}
}
}
}
void AddChildCard(string name)
{
cards.SetValue(name, x);
}
}
But for some Reason I get the following error two times:
NullReferenceException: Object reference not set to an instance of an object PlayerGetCards.AddChildCard (System.String name) (at Assets/Scripts/PlayerScripts/PlayerGetCards.cs:56) PlayerGetCards+c__Iterator0.MoveNext () (at Assets/Scripts/PlayerScripts/PlayerGetCards.cs:47) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
Can someone tell me why this is happening and how I can fix it? Thanks in advance!
Your answer
Follow this Question
Related Questions
How to get all children of a Gameobject with a certain component 2 Answers
Assign role randomly from array for my online game 2 Answers
All GameObjects list to a GameObject? 0 Answers
List out of range on parameter index; Editor in debug shows it isn't 1 Answer
IndexOutOfRangeException: Array index is out of range problem 2 Answers