更改长按精灵的图像

Changing the image of long clicked Sprite

我正在尝试更改长时间点击的 sprite 图像。

除了在 LongPress 方法中,我的以下代码有效,它更改了将此脚本指定为检查器组件的所有精灵的图像。此外,代码会在长按屏幕上的任意位置后触发,而不是将自身隔离为仅使用脚本分配的精灵

OnMouseDownAsButton 可以解决很多问题,但是将我的代码位包装在 OnMouseDownAsButton 函数中以隔离碰撞器似乎取消了 update() 方法。

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;
    }
    }

尝试使用 OnMouseDown functions and OnMouseUpAsButton。您当前的问题似乎是 Input 检测到鼠标在屏幕上的任何地方按下,这会导致所有脚本激活,从而导致更改。

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

您可以使用“OnPointerEnter”和“OnPointerExit”事件向游戏对象添加一个 EventTrigger 组件,以检查鼠标是否在该对象上(使 OnPointerEnter 调用一个函数,将布尔值设置为 true,OnPointerExit 将其设置为布尔值到假)。

您可以做的是让您的脚本实现在命名空间 UnityEngine.EventSystems 中找到的接口 IPointerEnterHandler、IPointerExitHandler。在 onPointerEnter 和 onPointerExit 中,您可以设置布尔变量的值。