In my Unity 2021.2.6f1 project, I have a ScrollRect
object (carNameList
) with several Image
items that are added dynamically via prefab instancing. They are switched between each other by KeyPress
events.
The unselected item has its alpha
value 0, and the selected one must have alpha
1.
When I clear my list and fill it up again with new items (that action is also performed by key press), the first item must be selected automatically (without pressing the 'switch' key). Actually the method works and prints the message. But I don't see any changes ingame until I change the alpha value manually via editor.
When called inside Start() it works. It also changes when I press the "switch" key after pressing "refill list" key, but it's wrong (the second element selects then). None of solutions that i found on the internet worked.
Code for selecting menu item:
void SelectMenuItem(int index)
{
if(carNameList.content.childCount > 0)
{
// deselect all items first
foreach(Image item in carNameList.content.GetComponentsInChildren<Image>())
{
Color color = item.color;
color.a = 0f;
item.color = color;
}
// select the desired one
if(index >= 0 && index < carNameList.content.childCount)
{
Image selectedItem = carNameList.content.GetComponentsInChildren<Image>()[index];
Color color = selectedItem.color;
color.a = 1f;
selectedItem.color = color;
Debug.Log(string.Format("Item {0} selected", index));
}
}
}
Clearing the list:
void ClearCarNameList()
{
if(carNameList)
{
var grid = carNameList.content.GetComponent<VerticalLayoutGroup>();
for(int i = 0; i < grid.transform.childCount; i++)
{
Destroy(grid.transform.GetChild(i).gameObject);
}
}
}
Adding items to list:
void AddItemToCarNameList(string text)
{
if(carNameList)
{
Image prefab = Resources.Load<Image>("FrontEnd/Prefabs/ListItem");
Image instance = Instantiate<Image>(prefab);
instance.rectTransform.SetParent(carNameList.content.transform, false);
instance.GetComponentInChildren<Text>().text = text;
}
}
Start method:
void Start()
{
...
prevVehicleBtnPressed.AddListener(PreviousVehicleInCategory);
nextVehicleBtnPressed.AddListener(NextVehicleInCategory);
prevCatBtnPressed.AddListener(PreviousCategory);
nextCatBtnPressed.AddListener(NextCategory);
...
LoadAllVehicles(); // this calls the LoadAllVehiclesInCategory(string catName)
}
Load all vehicles in category (clear list and add new items):
private void LoadAllVehiclesInCategory(string catName)
{
...
FillCarNameList(namesList);
SelectMenuItem(0);
...
}
Update method:
void Update()
{
#region Events firing when pressing on keyboard keys
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
prevCatBtnPressed.Invoke(); // refill list call
}
if(Input.GetKeyDown(KeyCode.RightArrow))
{
nextCatBtnPressed.Invoke(); // refill list call
}
if(Input.GetKeyDown(KeyCode.UpArrow)) // previous vehicle in category list
{
prevVehicleBtnPressed.Invoke();
}
if(Input.GetKeyDown(KeyCode.DownArrow)) // next vehicle in category list
{
nextVehicleBtnPressed.Invoke();
}
...
#endregion
}