Instantiated prefab with ui child gameobject , works differently compared to on-scene prefab
Hey everyone. My purpose is to put healthbars on top of each enemy. So , i made these two scripts;
Script one:
public class HealthBarScript : MonoBehaviour {
//script on the enemy main gameobject, to get component from the correct enemy
public GameObject newInstant;
public HealthBarFollow hpFollow;
void Awake () {
hpFollow = GetComponentInChildren<HealthBarFollow>();
hpFollow.target = transform.Find("HPbar");
newInstant = transform.Find("HealthSlider").gameObject;
}
}
Script two:
public class HealthBarFollow : MonoBehaviour {
//script on the healthbar to follow its target
public Vector3 movePos;
public Transform target;
public GameObject canvas;
private void Start()
{
canvas = GameObject.FindGameObjectWithTag("Canvas");
transform.SetParent(canvas.transform, false);
}
void Update () {
movePos = Camera.main.WorldToScreenPoint(target.position);
transform.position = movePos;
}
}
And these two scripts work great, if the enemy prefab is placed before the game starts. If the prefab is instantiated or simply dragged to the scene through the editor, the healthbar location gets skewed.
Here's what i mean:
I am truly lost on this one, i searched a lot for an answer but nothing worked. Thanks for your attention.
Your answer
Follow this Question
Related Questions
How to make another ground spawn beneath itself 1 Answer
How do I Instantiate a Prefab to align with the closest object? 0 Answers
I get an error message every time i run this script? Any ideas? 0 Answers
Unable to set position of instantiated prefab 1 Answer
Can't move instantiated object. 1 Answer