Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Why can I not do a foreach in my List of gameobjects?

Discussion in 'Scripting' started by OffThHeezay91, Oct 31, 2019.

  1. OffThHeezay91

    OffThHeezay91

    Joined:
    Feb 23, 2013
    Posts:
    45
    I have a list of gameobjects and I want to cycle through the list and disable each object.

    public List<GameObject> panel;
    foreach (GameObject i in panel) { i.SetActive(false); }


    I am getting the error that I cannot convert char to gameobject. How do I refer to the gameobject?
    thank you
     
  2. APSchmidtOfOld

    APSchmidtOfOld

    Joined:
    Aug 8, 2016
    Posts:
    4,473
    Your script works for me:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Test : MonoBehaviour
    6. {
    7.     public List<GameObject> panel;
    8.  
    9.     private void Start()
    10.     {
    11.         foreach(GameObject i in panel) { i.SetActive(false); }
    12.     }
    13. }
     
  3. Boz0r

    Boz0r

    Joined:
    Feb 27, 2014
    Posts:
    419
    What does the rest of your script look like? Are you sure the error is on that line?
     
  4. OffThHeezay91

    OffThHeezay91

    Joined:
    Feb 23, 2013
    Posts:
    45
    I see my mistake now, I used "panel" 2 times which caused the error :confused:

    public List<GameObject> panel;
    public void ChangePanel(string panel)
    {
    foreach (GameObject i in panel) {
    i.SetActive(false);
    }
    }


    Thanks for testing the code all
     
    Joe-Censored likes this.