Home > Blockchain >  Assets\Scripts\PlayerMovement.cs(18,9): error CS0029: Cannot implicitly convert type 'void�
Assets\Scripts\PlayerMovement.cs(18,9): error CS0029: Cannot implicitly convert type 'void�

Time:06-05

When I fixed the code from this post I get this error: Assets\Scripts\PlayerMovement.cs(18,9): error CS0029: Cannot implicitly convert type 'void' to 'System.Action<UnityEngine.InputSystem.InputAction.CallbackContext>' How do I fix it?

This is my code that gets errors:

        controls.Gameplay.Move_Left.performed  = Left();

        controls.Gameplay.Move_Right.performed  = Right();

and

    void Left()
    {
        rb.AddForce(leftrightForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    void Right()
    {
        rb.AddForce(-leftrightForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

(There is a simalar post here but it didn't work)

Please help, I am really stuck and need to get this done soon! Go to this post to get my full code!

CodePudding user response:

So you have two problems here.

  1. You should be passing the method itself to the event delegate, not the result of calling the method (which is null, so there isn't one).
  2. You have the wrong method signature.

The error message tells you as much:

error CS0029: Cannot implicitly convert type 'void' to 'System.Action<UnityEngine.InputSystem.InputAction.CallbackContext>'

It essentially says that it requires a method that takes a CallbackContext, but you're trying to pass void. This implies 1 and 2 as mentioned above.

So to fix one, we change your code like this:

controls.Gameplay.Move_Left.performed  = Left;
controls.Gameplay.Move_Right.performed  = Right;

And to fix 2, we need to match the System.Action<UnityEngine.InputSystem.InputAction.CallbackContext> signature, which looks like this:

public delegate void Action<in T>(T obj); 

Meaning we need a method that doesn't return anything (void) and accepts a T (in this case CalllbackContext). Fixing your methods to look like this, we get the following:

void Left(UnityEngine.InputSystem.InputAction.CallbackContext context)
{
    rb.AddForce(leftrightForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}

void Right(UnityEngine.InputSystem.InputAction.CallbackContext context)
{
    rb.AddForce(-leftrightForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}

And now your code is fixed.

Note that I don't use Unity, but understood this information from the error message, so it really does pay to read them carefully.

CodePudding user response:

In this simple solution, just use Context Default delegate:

controls.Gameplay.Move_Left.performed  = _ => Left();

controls.Gameplay.Move_Right.performed  = _ => Right();
  • Related