I’m using a Grid Layout Group to give me flexibility on how multiple objects are displayed.
When the player taps/selects one of the objects, I need to draw a sprite on top of that object. (I don’t want to replace the existing sprite in that object.)
I’ve read that to draw a second sprite on top of an existing object, I need to create a second game object and instantiate it at the location of the first object (I guess this will display the two sprites on top of each other).
When I try the following code, the new game object is displayed at the next available slot in the grid, instead of displaying the new object at the same location as the tapped/selected object.
Vector3 thisPosition = this.transform.position; // get location of tapped object (this)
Transform newSelection = Instantiate(this.transform, thisPosition, Quaternion.identity, parentTransform);
newSelection.transform.SetParent (parentTransform, false); // in case it helped, it didn't
Does the Grid Layout Group take complete position control of all objects added to it, so that I can’t draw two objects in one location?
Or am I doing something wrong?
If you have a grid layout and you add another child to the object that has the grid layout, the grid will format it. If you create a new object and make it a child of one of the objects in your grid layout, the grid doesn’t do anything to it.
-Parent <= has your grid
–child1
–child2
—child2Newsprite
–child3
So, to try to explain better, the child2Newsprite is a child of child2, so the grid doesn’t do anything to it. But if I added a child to the parent, it would become child4 and stick it under child3.
1 Like
Thanks, Brathnann!
Making the second object a child makes good sense and did allow me to add a game object without having the Grid Layout control it.
However, when I instantiate the second object as a child, the sprite is not visible.
(If I instantiate the same object as a child of the real parent (controlled by the GridLayoutGroup), the sprite does appear, albeit in a new grid location.)
Vector3 thisPosition = this.transform.position; // get location of tapped object (this)
thisPosition.z = 100; // move the new child object away from parent object (same sprite in this test)
Transform newSelection = Instantiate(this.transform, thisPosition, Quaternion.identity, parentTransform);
In the Scene window, I can see the child object “frame” but no sprite is visible. Even when I instantiate the child with the same object as the parent (as a test), the child sprite isn’t visible.
Why does sprite visibility change due to the parent?
If you want an overlay image within a layout group without it being affected by the layout group, you need to add a layout element to the object and check the box to exclude it from the layout group.