Hello. I have a script that clones the prefab Cell. And after that, I need a prefab of Gold to be randomly placed in these cells. The problem is that I cannot make the cell become the Parent and the Gold becomes the child. When I start a unit, I only have a prefab of Cells without Gold.
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System;
public class Gold : MonoBehaviour
{
private Cell cell;
private Transform canvas;
public static Cell[] content;
void Start()
{
cell = GetComponentInParent();
canvas = GameObject.Find("Canvas").transform;
CreateGold();
}
void CreateGold()
{
transform.SetParent(cell.transform);
transform.position = cell.transform.position;
transform.localScale = Vector2.one;
}
}
Cell creation in GameController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
[SerializeField] private int capacity; // количество ячеек
[SerializeField] private Transform Field; // родительский объект
public static Cell[] content; // ссылка на массив ячеек
void Awake()
{
content = new Cell[capacity];
CreateCell();
}
void CreateCell()
{
for (int i = 0; i < capacity; i++)
{
GameObject cell = Instantiate(Resources.Load("Cell"));
cell.transform.SetParent(Field);
cell.transform.localScale = Vector2.one;
cell.name = string.Format("Cell [{0}]", i);
content[i] = cell.GetComponent();
}
}
} | |
↧