- Home /
AddComponent for RawImage not functioning as expected
I'm having a slight time with the RawImage component within Unity. I'm trying to create a function wherein each character's health bar appears directly below the character. I do this by making a GameObject earlier in the initialization, where p is type Player.
p.HealthDisplay = new GameObject ();
p.HealthDisplay.transform.SetParent (stageCanvas.transform);
p.HealthDisplay.AddComponent <RawImage> ();
p.HealthBar = p.HealthDisplay.GetComponent <RawImage> ();
p.HealthBar.transform.SetParent (stageCanvas.transform);
p.HealthBar.texture = Resources.Load <Texture2D> (@"Textures/Blank");
p.HealthBar.color = Color.yellow;
p.HealthBar.enabled = true;
Then, later in the code as I'm updating the map, I use this block of code to ensure health is displayed.
if (!p.KOd && !p.Invisible.IsActive && p.InPlay) {
RawImage pImg = getImageFromPlayer (p);
p.HealthBar.transform.position = new Vector3 (pImg.transform.position.x - 334,
pImg.transform.position.y - 381,
0);
print ("DISPLAYING " + p.FirstName + "'S HEALTH BAR AT "
+ p.HealthBar.transform.position.x + ": " + p.HealthBar.transform.position.y);
p.HealthBar.enabled = true;
p.HealthBar.transform.localScale = new Vector3 ((p.Health.MeterRatio * 100) / 40,
10, targetHealthBarImage.transform.localScale.z);
} else {
p.HealthBar.enabled = false;
}
The "print" method displays the correct location for the Player, but the health bar does not appear on the map. Do I need to change the priority of the RawImage as I'm creating them?
Your answer
Follow this Question
Related Questions
How to get a component from an object and add it to another? (Copy components at runtime) 12 Answers
GetComponent of ALL clones? 2 Answers
Weird GetComponent error 2 Answers
Adding Arbitrary Properties to GameObjects 1 Answer
GetComponent vs AddComponent 3 Answers