Code works only for one of multiple existing instances

I want to turn the canvas to look at player camera but it only works for the first in hierarchy instance here is one of codes i tried to fix it

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

public class EnemyHpBarLookAt : MonoBehaviour
{
    void Update()
    {
        foreach(Transform enem in transform)
            foreach(Transform child in enem)
            {
                if(child != null)
                {
                    EnemyHpBar cameraPosFun = (EnemyHpBar) child.transform.GetComponent(typeof(EnemyHpBar)) as EnemyHpBar;
                    var pos = cameraPosFun.getPos();
                    child.transform.LookAt(pos);
                    Debug.Log(child.GetInstanceID());
                }
            }
    }
}

It seems to cycle betwen instances IDs

Can you explain what each of these lines is intended to do?

Also this line is just… what:

EnemyHpBar cameraPosFun = (EnemyHpBar) child.transform.GetComponent(typeof(EnemyHpBar)) as EnemyHpBar;

It could easily be converted down into:

EnemyHpBar enemyHpBar = child.GetComponent<EnemyHPBar>();
1 Like