【问题标题】:How to call Update function's code by button click如何通过按钮单击调用更新功能代码
【发布时间】:2019-01-03 11:21:48
【问题描述】:

如何在Update 函数中使用public 方法调用代码?

我需要存档的是,使用另一个函数调用Update

以便Update 使用其他方法触发。

还有一点,代码只能在长按按钮时运行。

非常感谢四位帮助

using UnityEngine;
using System.Collections;

public class CarController : MonoBehaviour
{

    public float speed = 1500f;
    public float rotationSpeed = 15f;

    public WheelJoint2D backWheel;
    public WheelJoint2D frontWheel;

    public Rigidbody2D rb;

    private float movement = 0f;
    private float rotation = 0f;



    void Update()
    {

        rotation = Input.GetAxisRaw("Horizontal");
        movement = -Input.GetAxisRaw("Vertical") * speed;

    }

    void FixedUpdate()
    {
        if (movement == 0f)
        {
            backWheel.useMotor = false;
            frontWheel.useMotor = false;
        }
        else
        {

            backWheel.useMotor = true;
            frontWheel.useMotor = true;

            JointMotor2D motor = new JointMotor2D { motorSpeed = movement, maxMotorTorque = 10000 };
            backWheel.motor = motor;
            frontWheel.motor = motor;


        }

        rb.AddTorque(-rotation * rotationSpeed * Time.fixedDeltaTime);
    }

    //public void Rotate()
    //{
    //    rotate = true;
    //    print("aa");
    //}
    //public void Move()
    //{
    //    rotation = Input.GetAxisRaw("Horizontal");
    //    movement = -Input.GetAxisRaw("Vertical") * speed;
    //}
}

【问题讨论】:

    标签: function unity3d long-press


    【解决方案1】:

    这实际上是两个问题。

    1。长按按钮

    Unity UI.Button 本身没有长按的方法,但您可以使用IPointerXHandler 接口自行实现:

    using UnityEngine;
    using UnityEngine.Events;
    using UnityEngine.EventSystems;
    using UnityEngine.UI;
    
    // RequireComponent makes sure there is Button on the GameObject
    [RequireComponent(typeof(Button))]
    public class LongPressButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
    {
        private void Awake()
        {
            ResetButton();
        }
    
        // set the long press duration in the editor (in seconds)
        public float LongPressDuration = 0.5f;
    
        // Here you reference method just like in onClick
    
        public UnityEvent onLongPress;
    
        private float _timer;
        private bool _isPressed;
        private bool _pressInvoked;
    
        private void Update()
        {
            // prevent multiple calls if button stays pressed
            if (_pressInvoked) return;
    
            // if button is not pressed do nothing
            if (!_isPressed) return;
    
            // reduce the timer by the time passed since last frame
            _timer -= Time.deltaTime;
    
            // if timeout not reached do nothing
            if (!(_timer <= 0)) return;
    
            // Invoke the onLongPress event -> call all referenced callback methods
            onLongPress.Invoke();
            _pressInvoked = true;
        }
    
        // reset all flags and timer
        private void ResetButton()
        {
            _isPressed = false;
            _timer = LongPressDuration;
            _pressInvoked = false;
        }
    
    
        /* IPointer Callbacks */    
    
        // enable the timer
        public void OnPointerDown(PointerEventData eventData)
        {
            _isPressed = true;
        }
    
        // reset if button is released before timeout
        public void OnPointerUp(PointerEventData eventData)
        {
            ResetButton()
        }
    
        // reset if cursor leaves button before timeout
        public void OnPointerExit(PointerEventData eventData)
        {
            ResetButton();
        }
    }
    

    这个脚本必须放在Button 组件旁边。

    您没有引用Button 中的回调方法 onClick 而是在这个LongPressButtononLongPress

    别忘了在检查器中调整LongPressDuration

    例子

    2。致电CarControllerUpdate

    我不知道你为什么想要这个(我猜你禁用了该组件但还是想调用Update

    解决方案 A

    为了能够在 Inspector 中引用该方法,有几个选项:

    1. 只需让你的Update方法public

      public void Update()
      {
          rotation = Input.GetAxisRaw("Horizontal");
          movement = -Input.GetAxisRaw("Vertical") * speed;
      }
      
    2. Update 的内容包装在另一个public 方法中,并改用那个方法:

      private void Update()
      {
          DoUpdateStuff();
      }
      
      public void DoUpdateStuff()
      {
          rotation = Input.GetAxisRaw("Horizontal");
          movement = -Input.GetAxisRaw("Vertical") * speed;
      }
      
    3. 反过来(您如何请求)- 从另一个 public 方法调用 Update

      private void Update()
      {
          rotation = Input.GetAxisRaw("Horizontal");
          movement = -Input.GetAxisRaw("Vertical") * speed;
      }
      
      public void DoUpdateStuff()
      {
          Update();
      }
      

    所以剩下的就是在LongPressButtononLongPress 事件中引用CarControllerUpdateDoUpdateStuff 方法。


    解决方案 B

    或者,您可以直接在运行时添加该回调,无需引用任何内容,也无需创建回调方法 public,因此您可以直接使用 private void Update 而无需包装方法。

    缺点:对于这种方法,您必须以某种方式在您的 CarController 脚本中获取对 LongPressButton 的引用

    public class CarController : MonoBehaviour
    {
        // Somehow get the reference for this either by referencing it or finding it on runtime etc
        // I will asume this is already set
        public LongPressButton longPressButton;
    
        private void Awake()
        {
            // make sure listener is only added once
            longPressButton.onLongPress.RemoveListener(Update);
    
            longPressButton.onLongPress.AddListener(Update);
        }
    
        private void Update()
        {
            rotation = Input.GetAxisRaw("Horizontal");
            movement = -Input.GetAxisRaw("Vertical") * speed;
        }
    
        private void OnDestroy()
        {
            // clean up the listener
            longPressButton.onLongPress.RemoveListener(Update);
        }
        
        //...
    }
    

    【讨论】:

      【解决方案2】:

      感谢您的描述性回复。我所做的是将我的脚本更改为跟随并添加事件触发器组件。然后相应地调用公共函数。

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class CarMve : MonoBehaviour
      {
      
          bool move = false;
          bool moveR = false;
          public Rigidbody2D rb;
      
          public float speed = 20f;
          public float rotationSpeed = 2f;
      
          private void FixedUpdate()
          {
              if (move == true)
              {
                  rb.AddForce(transform.right * speed * Time.fixedDeltaTime * 100f, ForceMode2D.Force);
              }
              if (moveR == true)
              {
                  rb.AddForce(transform.right *- speed * Time.fixedDeltaTime * 100f, ForceMode2D.Force);
              }
          }
      
          /* Will be used on the UI Button */
          public void MoveCar(bool _move)
          {
              move = _move;
          }
          public void MoveCarR(bool _moveR)
          {
              moveR = _moveR;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 2021-09-06
        相关资源
        最近更新 更多