'Having a CS1579 issue [duplicate]

I am trying to create a basic Hot bar system in my unity project. And When I'm trying to use Foreach. I get an error message that reads:

Foreach statement cannot operate on variables of typ HotbarButtun because HotbarButtun does not contain a public instance or extension definition for GetEnumerator

Problem Code:

using UnityEngine
Public class toolbar: MonoBehaviour
{
 private void Awake()
 {
  foreach(var Button in GetComponentInChildren<Hotbarbuttun>())
  Button.OnbuttonClicked += ButtonOnButtonClicked;
 }
  Private void ButtonOnButtonClicked(int ButtonNumber)
 {
   
 }

Hotbarbuttun Code

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

public class HotBarButtun : MonoBehaviour
{
 
[SerializeField] private TMP_Text _text;

public event Action<int> OnbuttonClicked;

private KeyCode _keyCode;
private int _keyNumber;


private void OnValidate()
{
    _keyNumber = transform.GetSiblingIndex() + 1;
    _keyCode = KeyCode.Alpha0 + _keyNumber;

    if (_text == null)
    {
        _text = GetComponentInChildren<TMP_Text>();

    }
    _text.SetText(_keyNumber.ToString());
    gameObject.name = "Hotbar Button " + _keyNumber;
}

private void Awake()
{
    GetComponent<Button>().onClick.AddListener(HandelClick);
}

private void Update()
{
    if (Input.GetKeyDown(_keyCode))
    {
        HandelClick();
    }
}

private void HandelClick()
{
    OnbuttonClicked?.Invoke(_keyNumber);
}



}

the Code is from this tutorial: Easy Unity HotBars w/ OnValidate Unity by Jason Weimann . All help appreciated



Solution 1:[1]

You're using foreach with GetComponentInChildren<Hotbarbuttun>().

The Get Component SINGULAR will only return one item, so where you think you're iterating over a collection of Hotbarbuttun you're actually trying to iterate on a Hotbarbuttun, which itself is not a collection. It doesn't implement GetEnumerator, again because it's not a collection, so you can't do that.

What you're looking for instead is the PLURAL GetComponentsInChildren<Hotbarbutton>() which will return an array of Hotbarbutton.

Solution 2:[2]

You are calling a method that returns a single component which cannot be enumerated.

From the documentation:

public Component GetComponentInChildren(Type t);

Returns
A Component of the matching type, otherwise null if no Component is found.

What you want instead is to call a method that returns an enumeration, such as:

public Component[] GetComponents(Type type);

Returns 
all components of Type type in the GameObject.

In your code:

foreach(var Button in GetComponents<Hotbarbuttun>())
{
    Button.OnbuttonClicked += ButtonOnButtonClicked;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chuck
Solution 2