Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

foreach statement cannot operate on variables of type 'Canvas' because 'Canvas' does not contain a p

Discussion in 'Scripting' started by cabmobile, Sep 13, 2022.

  1. cabmobile

    cabmobile

    Joined:
    Mar 5, 2022
    Posts:
    1
    I'm trying to make a health bar for enemy using a world space canvas
    how can i solve this please ?

    error: foreach statement cannot operate on variables of type 'Canvas' because 'Canvas' does not contain a public instance or extension definition for 'GetEnumerator'



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

    public class HealthUiTarget : MonoBehaviour
    {

    public GameObject uiPrefab;
    public Transform target;

    Transform ui;
    Image healthSlider;
    Transform cam;

    void Start()
    {
    cam = Camera.main.transform;
    foreach (Canvas c in FindObjectOfType<Canvas>())
    {
    if(c.renderMode == RenderMode.WorldSpace)
    {
    ui = Instantiate(uiPrefab, c.transform).transform;
    healthSlider = ui.GetChild(0).GetComponent<Image>();
    break;
    }
    }
    }

    // Update is called once per frame
    void Update()
    {
    ui.position = target.position;
    ui.forward = -cam.forward;
    }
    }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    Review what the above method returns, and then consider its alternative which returns a collection.

    As always, the complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/