Do you want a button that has an image on the button instead of text? If so the Button already has an Image script attached to it. If you look on the main button you’ll see an Image script there.
In the third line of code, you are assigning bImg to the parent’s Image component while presumably you want to assign it to the child Image gameobject. If thats the case, then all you have to do is to Find(or better cache) the child Image gameobject and then assign the ButtonImageHover sprite to it.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections.Generic;
[RequireComponent(typeof(EventTrigger))]
public class MyButtonClass : MonoBehaviour,IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler
{
public Sprite ButtonImageHover;
public void OnPointerEnter(PointerEventData eventData) {
Debug.Log ("OnPointerEnter");
if (this.transform.Find ("Image")) {
Debug.Log ("OnHover");
// Error
// Cannot implicitly convert type 'UnityEngine.Sprite' to UnityEngine.UI.Image'
Button button = GetComponent<Button>();
button.image = ButtonImageHover;
}
}
}
Sorry needed to be button.image.sprite. I created a normal UI button and attached this script to it:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections.Generic;
[RequireComponent(typeof(EventTrigger))]
public class MyButtonClass : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public Sprite ButtonImageHover;
Button button;
void Awake()
{
button = GetComponent<Button>();
}
public void OnPointerEnter(PointerEventData eventData)
{
button.image.sprite = ButtonImageHover;
}
public void OnPointerExit(PointerEventData eventData)
{
button.image.sprite = null;
}
}
}
After dragging a sprite onto ButtonImageHover in the inspector, clicking play works fine. When my mouse goes over the button the button changes to the sprite image. When my mouse leaves the button it reverts back to a default button.