image in the button

hi, I'm following the book unity beginners guide by examples, and I'm having problems showing an image in a button, this is the code:

if(GUILayout.Button(Resources.Load(card.img), GUILayout.Width(cardDIM))) {
        Debug.Log(card.img);
        }

there's no error in the game, the card.img is a string that tell me the name "empty", the same name in the project panel of an image 100 x 100.

I don't know why this don't work, i've followed the book carefully

I’m going to give a fresh example. Create a folder called Resources in your Assets folder (project pane). For this example, just use a .png file and name it “Image”, place it directly into your Resources folder. Now we’ll create GUIContent and use it for the GUI Button. I’ve attached an example project .zip in case you have some issues with the following script:

[18858-guibutton+image+example.zip|18858]

#pragma strict

var image : Texture2D;
var content : GUIContent;

function Start()
{
	image = Resources.Load("Image");
	content.image = image;
}

function OnGUI()
{
	GUI.Button(Rect(0, 0, 128, 128), content);
}

This works to some extent. If you simply want to use your texture as the button itself and not use built in background:

#pragma strict

var image : Texture2D;

function Start()
{
	image = Resources.Load("Image") as Texture2D;
}

function OnGUI()
{
	GUI.skin.button.normal.background = image;
	GUI.skin.button.hover.background = image;
	GUI.skin.button.active.background = image;
	GUI.Button(Rect(0, 0, 128, 128), "");
}

You could of course use a GUIStyle to do this in the inspector, you could also use different images for each button state.

This function needs the name of the asset (or the asset path) as a string:

Resources.Load("card.img")


Edit:

var img : Texture;

if(GUILayout.Button(img, ...))

Hi,

You should just write in "" the name of the file you placed in the Resources folder inside your project, take away the extension. See the example:

if(GUILayout.Button(Resources.Load("card"));

You need to explicitly state that the resource you are loading is a texture. Looks like Resource.Load(); returns a texture, but GUILayout.Button(); is not sure whether it is a texture, a string or something else.

if ( GUILayout.Button( (Texture)Resources.Load(“robot”), GUILayout.Width(cardW) ) )

This worked for me. For C#. Not sure if casting is done the same way in JavaScript.

Just create a folder named “Resources” in your Assets folder → Assets/Resources and place your robot.jpg inside the Resources folder. And Bam! Your code works…