J.K. Harthoorn
J.K. Harthoorn

Reputation: 218

Make gameObject child of the gameObject which is at the position of the button

It's hard to explain my question. I have 16 tiles with 9 buttons between them:

https://i.gyazo.com/7f0402427b37fdba8a267b7a9ca9dc68.png

Behind every button is a white gameObject which is in the center of 4 tiles. If you press a button, the 4 tiles should rotate around the white gameObject. I thought that the best way to do this is that when you click a button, the 4 tiles around that button should become child of the white gameObject behind that button, so they can rotate with 4. How do I make it so, that when you press a button, the tiles around that button will become child of the white gameObject behind that button?

Upvotes: 0

Views: 170

Answers (1)

ryeMoss
ryeMoss

Reputation: 4343

There are several ways to accomplish this but it can more or less be broken down into the few steps that you mentioned. This method assumes you have one script that you attach to each of the white objects.

You first need to generate a list of objects that the white object is touching. This could either be done using OnCollisionEnter/OnTriggerEnter or by performing a distance check. Below is an example of how OnTriggerEnter could be used after tagging each of the colored squares. Then you can simply loop through the 4 objects in the list and assign their parent to the white square:

void SquareClicked()
{
    foreach(GameObject square in NeighborList)
    {
        square.transform.parent = gameObject.Transform;
    }
    DoRotate(); //this is where you do the rotation of the parent object.
}

List<GameObject> NeighborList = new List<GameObject>();
void OnTriggerEnter2D(Collider2D col)
{
    if (col.tag == "coloredsquare") //tag each square with this tag.
    {
         NeighborList.Add(col.gameObject);
    }
}

Upvotes: 1

Related Questions