简体   繁体   中英

Unity referencing all images in scene instead of just one

I'm trying to change the color of an image when I hover over it. It runs PointerEnter when I hover over it, and PointerExit when my mouse goes away.

Instead of changing the color of just the image I'm hovering over, it changes the color of every image in the scene. Can anybody help?

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class click : MonoBehaviour {

    void Start(){
        
    }

    void Update(){
        
    }
    
    public void PointerEnter(){
        gameObject.GetComponent<Image>().material.color=new Color(1,1,0);
    }
    
    public void PointerExit(){
        gameObject.GetComponent<Image>().material.color=new Color(1,1,1);
    }

}

The material is shared for optimisation, it's the same one used for all the images using it.

You need to change the color of the image, simply remove material on your lines.

gameObject.GetComponent<Image>().color=new Color(1,1,0);

The Button component has transition settings where you can set colors for state, maybe you dont need the extra code.

Unity has 2 pre-programmed functions called OnMouseOver() and OnMouseExit() . Which you can use to see if the mouse entered your Image .

You would need to add this Code Snippet to each Image you want the Color to be changed on Hover and make sure that you get the .Color Component instead of the .material.color Component.

Example:

public class OnMouseOverExample : MonoBehaviour
{
    void OnMouseOver() {
        // Executes when you Hover over this GameObject with the Mouse
        gameObject.GetComponent<Image>().color = new Color(1f, 1f, 0f);
    }

    void OnMouseExit() {
        // Executes when you no longer Hover over this GameObject with the Mouse
        gameObject.GetComponent<Image>().color = new Color(1f, 1f, 1f);
    }
}

If you want to change a UI Components Color , you could also use the Button Component. Which already has functionality built in, you can use to tint the Color of your Image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM