更改长按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函数和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内部,您可以设置布尔变量的值。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...