带有UI图像的Unity触摸式运行代码-C# [英] Unity run code on touch with a UI Image - c#

查看:127
本文介绍了带有UI图像的Unity触摸式运行代码-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Unity3D的新用户,需要帮助.

I'm a new user to Unity3D and need a hand.

我有一些代码,我想在按下UI图像时将其激活,并在释放该按钮后将其结束.该游戏将同时在Android和IOS上运行,因此需要两个平台都支持.

I have some code which I want to be activated when the UI image is pressed and to end once the press has been released. The game is going to run on both Android and IOS so needs to be supported by both platforms.

这是我的代码:

public class RPB : MonoBehaviour {

public Transform LoadingBar;
public Transform TextIndicator;
[SerializeField] private float currentAmount;
[SerializeField] private float speed;
[SerializeField] private float numSec;





// Update is called once per frame
void Update () {

    if (currentAmount < 100) {
        currentAmount += speed * Time.deltaTime;


    } else if (currentAmount > 100){
        currentAmount = 0;

        numSec += 1;


    }

        LoadingBar.GetComponent<Image>().fillAmount = currentAmount /100;
        TextIndicator.GetComponent<Text> ().text = ((int)numSec).ToString () + "s";


}
}

我该怎么做?

谢谢

推荐答案

关于您的触摸屏问题,我建议您使用Unity的UI按钮系统.它在Android和iOS平台上均能很好地工作.我建议观看以下视频,以了解如何编写该接口将要求您的功能: https://unity3d.com/learn/tutorials/topics/user-interface-ui/ui-button

In regards to your issue with the touch screen, I would recommend using Unity's UI button system. It works very well with both Android and iOS platforms. I recommend watching these videos to understand how to write a function that the interface will call for you: https://unity3d.com/learn/tutorials/topics/user-interface-ui/ui-button

另一方面,每帧运行GetComponent<>()在移动系统上的负担非常大.

On another note, running GetComponent<>() every frame is incredibly taxing on a mobile system.

我建议进行以下更改:

using UnityEngine;
using UnityEngine.UI;

public class RPB : MonoBehaviour {

  public Image LoadingBar;
  public Text TextIndicator;
  // other variables redacted //

  void Start () {
    LoadingBar = GetComponent<Image>();
    TextIndicator = GetComponent<Text>();
  }

  void Update () {
    // other functions redacted //

    LoadingBar.fillAmount = currentAmount / 100;
    TextIndicator.text = ((int)numSec).ToString () + "s";
  }

  public void TouchFunction() {
    // Do the thing here. //
  }
}

这篇关于带有UI图像的Unity触摸式运行代码-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆