简体   繁体   中英

Changing the image of long clicked Sprite

I am trying to change the image of a sprite that's had a long click on it.

My below code works except in the LongPress method it changes the image of all sprites that have this script assigned as an inspector component. Additionally, the code triggers after long clicking anywhere onscreen, not isolating itself to just the sprites with the script assinged

OnMouseDownAsButton would solve a lot of the issues, however wrapping bits of my code in an OnMouseDownAsButton function to isolate the colliders seems to cancel out the update() method.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class LongClickButton : MonoBehaviour

{
public Sprite flagTexture;
public Sprite defaulttexture;

public float ClickDuration = 2;
public UnityEvent OnLongClick;

bool clicking = false;
float totalDownTime = 0;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        totalDownTime = 0;
        clicking = true;
    }

    if (clicking && Input.GetMouseButton(0))
    {
        totalDownTime += Time.deltaTime;
        if (totalDownTime >= ClickDuration)
        {
            clicking = false;
            OnLongClick.Invoke();
        }
    }
    if (clicking && Input.GetMouseButtonUp(0))
    {
        clicking = false;
    }
}

public void LongPress()
{    
    if (GetComponent<SpriteRenderer>().sprite == flagTexture)
    {
        GetComponent<SpriteRenderer>().sprite = defaulttexture;
    }
    else if(GetComponent<SpriteRenderer>().sprite == defaulttexture)
        GetComponent<SpriteRenderer>().sprite = flagTexture;
    }
    }

Try using OnMouseDown functions and OnMouseUpAsButton . Your current issue seems that the Input detects of a mouse down anywhere on screen, which causes all scripts to activate, which causes the changes.

void OnMouseDown() {
    clicking = true
}
void OnMouseUpAsButton(){
    clicking = false
}
void Update() {
    if(clicking){
       //your time stuff
    }
}

You could add a EventTrigger component to the gameobject with the "OnPointerEnter" and "OnPointerExit" events to check if the mouse is on that object (Make OnPointerEnter call a function that sets a boolean to true and OnPointerExit to set that boolean to false).

What you could do is make your script implement interafaces IPointerEnterHandler, IPointerExitHandler found in namespace UnityEngine.EventSystems. Inside onPointerEnter and onPointerExit you could set a value of boolean variable.

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