- Home /
Controlling Parent-Child Objects via Script
Ok so here's a complicated question.
So I will try to explain what I did.
I have some sprites for the m_slotIcon array and I assign them in the Inpector
And I instatiate a gameobject that has a child object with a button component as you can see in the script.
Then I add a function called OnClick() to the created button.
Here is the m_slot prefab
And here is what I want to do
In the OnClick() function I want to instatiate a specific prefab lets say ribosome
But it should be the prefab that the button is responsable for.
As you can see I am working on a build system and I don't know how to do it.
public class OrganelleMenu : MonoBehaviour {
[SerializeField] private GameObject m_slot;
[SerializeField] private Sprite[] m_slotIcon;
private Transform m_menu;
private void Awake()
{
m_menu = GameObject.FindGameObjectWithTag("OrganelleMenu").GetComponent<Transform>();
}
private void OnEnable()
{
for (int i = 0; i < m_slotIcon.Length; i++)
{
GameObject _slotInstance = Instantiate(m_slot, transform.position, Quaternion.identity); //Instantiate slot
_slotInstance.transform.SetParent(m_menu.transform); //change slot parameters
_slotInstance.transform.localScale = new Vector3(1, 1, 1);
_slotInstance.name = m_slotIcon[i].name;
_slotInstance.tag = m_slotIcon[i].name;
GameObject _button =_slotInstance.GetComponentInChildren<Button>().gameObject;
_button.GetComponent<Image>().sprite = m_slotIcon[i];
_button.GetComponent<Button>().onClick.AddListener(OnClick);
}
}
void OnClick()
{
string _organelleName = GetComponent<Transform>().name; // I do not know how to get the name of the slot
Debug.Log("Clicked " + _organelleName);
}
}
Any info missing tell me
Your answer
Follow this Question
Related Questions
SetParent help. 0 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Object Instantiate two times when i SetParent 1 Answer
How can i stop my game from laging during instantiation? C# 2 Answers