Search code examples
arraysunity-game-enginepositioninggameobject

Positioning Array Content (Sprites)


I have Pictures with Numbers on it (I mean Sprites). I got them on an Empty GameObject, I mean [SerializeField] and added through the script (C# Ofcourse), So the Objects are not really there they are being Generated when the Game begins. So as you can see in the Code that I can set Row and Columns Amount and with Offset also distances in X and Y Axis. But I cannot re-position it. It seems that the first one being generated is locked to the middle of the project (the first one up-Left)So I tried to move the gizmo of the empty gameobject but the sprites are still on the spot even if I use the Inspector Instead. It seems that it would need to be positioned it in the script, But How?

Please give me enough Examples witch will work with Unity?

What I tried is to position it in Unity as I already mentioned with moving the Gizmo of the Gameobject and also in the Inspector It really seems that it can only be done on the script (I might be wrong but I tried everything).

public class Controll : MonoBehaviour 
{
    public const int gridRows = 6;
    public const int gridCols = 6;
    public const float offsetX = 0.65f;
    public const float offsetY = 0.97f;

    [SerializeField] private GameObject[] cardBack;

    // Use this for initialization
    void Start ()
    {
        for (int i = 0; i < gridRows; i++)
        {
            for (int j = 0; j < gridCols; j++)
            {
                Instantiate(cardBack[i], new Vector3(offsetY*j, offsetX* i *-1 , -0.1f), Quaternion.identity);
            }
        }
    }

Solution

  • You are instantiating all objects into the Scene root level. They are in no way related to the GameObject which was originally responsible for the instantiation.

    If you rather want them to be positioned relative to the spawning GameObject then use

    var position = transform.position + new Vector3(offsetY * j, offsetX * i * -1, -0.1f);
    Instantiate(cardBack[i], position, Quaternion.Identity, transform);

    in order to instantiate them as child objects of the GameObject this Controll script is attched to.

    Now if you translate, rotate or scale that parent object all instantiated objects are transformed along with it.