- Home /
Automatically add list element as child transform
I try to create chess game in Unity. I want to each of list element be automatically set as child of other transform. Program looks like this:
[ExecuteInEditMode]
public class Chessboard : MonoBehaviour
{
public List<Piece> Pieces = new List<Piece>();
public static Chessboard instance = null;
void Awake()
{
if (instance == null) instance = this;
else if (instance != this) Destroy(gameObject);
foreach (Piece piece in Pieces)
{
Instantiate(piece).transform.SetParent(instance.transform);
}
}
}
Code above works, but not properly. I want to pieces be set as child of chessboard automatically when added (dragged in editor) to list (named Pieces), and destroyed when chessboard is destroyed (pieces remain as clones in the editor after running game).
void OnDestroy()
{
foreach (Transform pieceTransform in transform.GetComponentInChildren<Transform>())
{
Destroy(pieceTransform);
}
}
That has no effect. ^
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
A node in a childnode? 1 Answer
IDictionary 1 Answer
Populating a list with different items in different clones of the same prefab. 0 Answers