Canvas has no Image when I call GetComponent()
I added an Image to the Canvas but my Debug.Log() displays 0 Length when I call canvas.GetComponent().
GameObject canvas = GameObject.Find("Canvas");
crosshair = canvas.GetComponents<Image>();
Debug.Log("Canvas null? " + (canvas == null).ToString());
Debug.Log("CrossHair " + crosshair.Length);
Canvas is not null, but it does not have any Image in it.
In the design view of Unity, I can clearly see the Image which is a child of the Canvas.
Did I do something wrong here? Any help will be appreciated, thanks.
Answer by incorrect · Jan 05, 2016 at 03:38 AM
Yes, you are doing wrong. Your Image component is on Image object, not on Canvas. Do it this way:
GameObject canvas = GameObject.Find("Image");
Thanks for your answer. But I encounter the error saying 'canvas is null'.
I tried the code below ins$$anonymous$$d, it worked.
GameObject canvas = GameObject.Find("Canvas");
Image crosshair2 = canvas.GetComponentInChildren<Image>();
Debug.Log("Cams " + Camera.allCamerasCount);
Debug.Log("Canvas null? " + (canvas == null).ToString());
Debug.Log("CrossHair " + crosshair2.name);
I am not sure the difference between GetComponent() and GetComponentInChildren().
Ok... Once again.
You have game object named Canvas that has Canvas component on it. Canvas component provides drawing of user interface.
You also have game object named Image with Image component attached to it.
So when you try to call GetComponent() on game object 'Canvas' you get nothing. You should use it on object named Image.
GetComponentInChildren() is a different method: it looks for a component on the object itself and on it's children, so in your case it finds component Image on one of children: on game object called 'Image'.
Please, take a look in Learn section and try develop your skills in Unity and general program$$anonymous$$g. Good luck!
Thanks a lot for describing the difference.
I will try to learn more at the given link.
Now I am finding my Image and other GameObject in Start() function like this: GameObject img = GameObject.Find("$$anonymous$$yImage");
Thanks.