- Home /
Is there any way to link an image object to another game object's component?
I'm not sure if I worded it right, but what I want to ask is for example
I have an Image object in the heirarchy that I want to link to my instantiated object (or player), how do I link it to the player's script?
I wanted to link the damage image I have in the heirarchy to the Damage Image I have on this script but I don't know how to do it in script. I know that I could just drag it there if the object is also in the scene, but when I try to instantiate the same object from the assets (as a prefab) all those sliders and images are empty. I tried linking it by using these set of codes:
healthSlider = (Slider)FindObjectOfType (typeof(Slider));
//damageImage =
m_FillImage = (Image)FindObjectOfType (typeof(Image));
but when I write the same for the damageImage, it also automatically takes the Image that is set to the FillImage. This is how the UI objects look like in the heirarchy:
I'm guessing my code in the script is getting the last image object in the canvas, but I have no idea how to call the specific image object.
I'm sorry for the long question I just wanted to be as specific and accurate as possible with my question, because I haven't seen any answers for this on any other questions. Or I just don't know the right terms to search for. And I'm new to asking questions so it's really long. Thanks in advance
I'm not sure if i get this right It depends which object your script is attached to. If it is attached to DamageImage then simply use GetComponent<Image>().sprite;
if attached to a child of HUDCanvas then use transform.Find
m_FillImage = transform.parent.Find("DamageImage").GetComponent<Image>().sprite;
transform.Find will find a child by name so use parent which will be HUDCanvas
The PlayerHealth script is attached to a player object that I'm instantiating at the start of the scene. The DamageImage is attached to an object that can damage the player object.
I'll try that and see if it would work. Thanks
I actually did it by manipulating that line of code a bit with
damageImage = (Image)GameObject.Find("DamageImage").GetComponent<Image>();
Though I'm not sure if that's really optimized. I do want to know more ways to do it