0
\$\begingroup\$

Sorry if this question has already an answer somewhere, but I've just started to play with Unity and now I'm stuck. :(

I've tried a few things ( from here , here and here and others ) but none of them work, I'm sure that I do something wrong but I don't know what.

I have this code:

public class SceneManager : MonoBehaviour {

    public Image myButtonImage; 
    private Button switchBtn;

    // Use this for initialization
    void Start () {

        switchBtn = GameObject.Find("switchBtn").GetComponent<Button>();
        myButtonImage = Resources.Load<Image>("switchCameraImg");

        switchBtn.image = myButtonImage;
    }
}

and this are my objects:

enter image description here

where cameraSwitchObj is a GameObject and switchBtn is the button itself.

SceneManager is the script attached to MainCamera

I receive this error :

NullReferenceException: Object reference not set to an instance of an object SceneManager.Start ()

for this line : switchBtn.image = myButtonImage; but according to what i read from different posts this is all i must do. What I am missing?

\$\endgroup\$
1
\$\begingroup\$

You didn't show what is switchCameraImg in your assets folder. Also is this asset in your "Resources" directory?

Afaik, you cannot load Image via Resources.Load method. But you can load a Sprite, and next set a sprite of Image as loaded component.

Try this:

myButtonImage.sprite = Resources.Load<Sprite>("someGraphics");

Where the sprite is an graphics, for example in ".png" extension, with Texture Type option set as "Sprite (2D and UI)":

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Hmm, indeed, switchCameraImg is png, under Resources folder. So I must make a sprite with that image and then attach to object.. \$\endgroup\$ – Mara Black Dec 8 '17 at 17:05
0
\$\begingroup\$

In Unity 2017.2, Button already supports an images through the Target Graphic field.

Typically this is a 9-Patch image, but it's easy to turn an image into a 9-patch.

See the documentation for Button.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.