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

Code works only for one of multiple existing instances

Discussion in 'Scripting' started by AnonimiAngels, Jun 6, 2022.

  1. AnonimiAngels

    AnonimiAngels

    Joined:
    Jan 10, 2020
    Posts:
    4
    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
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyHpBarLookAt : MonoBehaviour
    6. {
    7.     void Update()
    8.     {
    9.         foreach(Transform enem in transform)
    10.             foreach(Transform child in enem)
    11.             {
    12.                 if(child != null)
    13.                 {
    14.                     EnemyHpBar cameraPosFun = (EnemyHpBar) child.transform.GetComponent(typeof(EnemyHpBar)) as EnemyHpBar;
    15.                     var pos = cameraPosFun.getPos();
    16.                     child.transform.LookAt(pos);
    17.                     Debug.Log(child.GetInstanceID());
    18.                 }
    19.             }
    20.     }
    21. }
    22.  
     
  2. AnonimiAngels

    AnonimiAngels

    Joined:
    Jan 10, 2020
    Posts:
    4
    It seems to cycle betwen instances IDs
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    Can you explain what each of these lines is intended to do?
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,003
    Also this line is just... what:
    Code (CSharp):
    1. EnemyHpBar cameraPosFun = (EnemyHpBar) child.transform.GetComponent(typeof(EnemyHpBar)) as EnemyHpBar;
    It could easily be converted down into:
    Code (CSharp):
    1. EnemyHpBar enemyHpBar = child.GetComponent<EnemyHPBar>();
     
    Bunny83 likes this.