简体   繁体   English

模拟 Unity InputSystem 鼠标事件

[英]Simulate Unity InputSystem mouse events

I'm busy working on a game where the player can attack by clicking the left mouse button.我正忙于开发一款玩家可以通过单击鼠标左键进行攻击的游戏。 I have a InputManager class that will check the input events and then invoke a UnityEvent.我有一个 InputManager class,它将检查输入事件,然后调用 UnityEvent。 This is all working while playing the game.这一切都在玩游戏时起作用。 But I'm struggling to simulate mouse events in my tests.但我正在努力在我的测试中模拟鼠标事件。 Here's the test:这是测试:

[Test]
public void MouseAttackTest()
{
    var attacked = false;
    var inputManagerObject = new GameObject();
    var inputManager = inputManagerObject.AddComponent<InputManager>();
    inputManager.OnAttack.AddListener(() => attacked = true);

    var mouse = InputSystem.AddDevice<Mouse>();
    using (StateEvent.From(mouse, out var eventPtr))
    {
        mouse.leftButton.WriteValueIntoEvent(true, eventPtr); // Fails on this line
        InputSystem.QueueEvent(eventPtr);
    }

    Assert.IsTrue(attacked);
}

And here's the output:这是 output:

MouseAttackTest (0,091s)
---
System.ArgumentException : Expecting control of type 'Boolean' but got 'ButtonControl'
---
at UnityEngine.InputSystem.InputControlExtensions.WriteValueIntoEvent[TValue] (UnityEngine.InputSystem.InputControl control, TValue value, UnityEngine.InputSystem.LowLevel.InputEventPtr eventPtr) [0x0003f] in C:\Dev\Game\Library\PackageCache\com.unity.inputsystem@1.0.2\InputSystem\Controls\InputControlExtensions.cs:369 
  at Game.Tests.Play.InputSystemTests.MouseAttackTest () [0x00046] in C:\Dev\Game\Assets\Scripts\Tests\Play\InputSystemTests.cs:24 
  at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <9577ac7a62ef43179789031239ba8798>:0

I tried to search for examples online, but there's no real examples or even proper documentation.我试图在网上搜索示例,但没有真实的示例,甚至没有适当的文档。 Any ideas on how I can simulate these events?关于如何模拟这些事件的任何想法?

Below codes should work, post an answer for followers.下面的代码应该可以工作,为关注者发布答案。

((ButtonControl)mouse.leftButton).WriteValueIntoEvent(1f, eventPtr);

Change to '1f' works for me.更改为“1f”对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM