Grid Layout group with prefabs aren't working

Im adding a bunch of prefabs to a grid Layout Group but they arent organising and just sit on the default location.

This is the code I have, as you can see Ive tried a few different ideas that have been suggested.

Any ideas?

   var bucket = Instantiate(BucketPrefab, bucketPosition, quaternion.identity);
        
            bucket.transform.SetParent(BucketGrid.transform,false);
            bucket.transform.localScale = new Vector3( 1.0f, 1.0f, 1.0f );
            bucket.transform.localPosition = Vector3.zero;

When instantiating in a UI hierarchy controlled by a layout object:

  • Do NOT set position and rotation

  • DO set the parent.

var bucket = Instantiate(BucketPrefab, BucketGrid.transform);

Hi!

Thanks for the reply. ok the prefabs are now being added with no position or rotation using the following:

    private void CreateBuckets()
    {
        for (int i = 0; i < totalBuckets; i++)
        {
            var bucket = Instantiate(BucketPrefab, BucketGrid.transform);
        }
    }

However, they now just stack on top of each other (there are 8 prefabs stacked)

Could it be the prefabs are somehow incompatible with UI elements? Ive noticed weird things happen when you try and mix. The Prefab is made up of non-ui sprites

7889818--1004149--upload_2022-2-11_21-23-38.png


More likely there is something not right with your layout… is it too narrow? Anchored wrong? Are the individual prefab elements anchored wrong?

Either way, I’m not a huge fan of prefabs used this way. They certainly should work, but they split your “area of interest” into two things: the scene with the layout, and then the things that go inside.

I like to keep those intimately tied together for ease of my brain. What I do is stick a single “example object” in and give my script access to that, and for each object I clone that example.

After making all the items I want, I either set the example inactive, or destroy it.

And you can make each example thing as complicated or as simple as you like.

I actually keep a handy example… see attached package. Enjoy!

8494565–1130474–DynamicUIDemo.unitypackage (55.7 KB)

Hi Again,

Turns out it was the non-ui elements I was using in the prefab, I switched from sprite to image (UI version) and it worked great after that.

That said, regarding your code demo you posted Im going to have a play with that now since I think I understand what you are saying.

Its a shame there isnt a grid control for non ui as having the code split into the ui screen is really annoying in terms of editing (moving back and forth from different views)

Thanks again for your time, really appreciate it