Scroll view list instantiation issues

Hi all,

Trying to create a scroll view which is a list of smaller canvases.

The basic structure is as follows:

  • Panel area (scroll rect, mask, image)
    –Content panel (vertical layout group, content size fitter with vertical fit set to min size)
    —Instantiated panel (layout element with preferred height set to 100)
    ----Panel components (text, image etc etc)

When manually adding them it works fine. However, I want to instantiate them at runtime as the list will be randomly populated with x from y possible panels.

I’ve got a class for the panel (Person) and a list of those attached to a GameObject in which I’ll build up the possible entries.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;

[System.Serializable]
public class Person {
    public string name;
    public Sprite icon;
}

public class CreateScrollList : MonoBehaviour {

    public GameObject namePrefab;
    public List<Person> personList;

    public Transform contentPanel;

    // Use this for initialization
    void Start () {
 
        PopulateList ();
    }
 
    void PopulateList()
    {
        foreach (var person in personList) {
            GameObject newPerson = Instantiate (namePrefab) as GameObject;
            NamePrefab generatedName = newPerson.GetComponent <NamePrefab> ();
            generatedName.nameLabel.text = person.name;
            generatedName.icon = person.icon;
            newPerson.transform.SetParent (contentPanel);

        }
    }
}

This adds them to the contentPanel (the ‘Content Panel’ listed above) and updates the UI elements as requested, but for some reason changes the scale to 2.918919.

I can’t figure out exactly why it’s doing that, nor how to manually force the scale back.

Been following the video below but the scale seems to be an issue.

I’ve tried changing the layout element and the content fitter but to no avail.

Feel free to talk to me like I’m stupid because I am when it comes to UI!

Fixed

Someone else informed me to set worldPositionStays to false when setting the parents as described here: Unity - Scripting API: Transform.SetParent

(i.e. newPerson.transform.SetParent (contentPanel, false))

Leaving in case anyone else could use this in the future (and I can’t seem to delete)

1 Like

I have the feeling, your question is asked every day two times -.-
the last time i gave an answer to that question: Scroll view is setting scale factor on items when added in code? - Unity Engine - Unity Discussions

In my opinion unity should check for a RectTransform and set the WorldPositionStays automatically to false if there is a RectTransform component.