Как исправить ошибку «Невозможно прочитать значение типа Vector2 из композита» в Unity?C#

Место общения программистов C#
Anonymous
Как исправить ошибку «Невозможно прочитать значение типа Vector2 из композита» в Unity?

Сообщение Anonymous »

Я создаю 2D-игру на Unity, используя новую систему ввода. Я хочу перевернуть персонажа игрока, когда он меняет направление.
Я пробовал использовать spriteRenderer.flipX, чтобы перевернуть игрока, но поскольку он состоит из трех частей (тела и двух глаза), это не сработало (я не мог преобразовать их в один спрайт, потому что мне нужны были глаза для их анимации). Итак, я решил использовать Transform.localscale для переворота и изменения значения motionInput с числа с плавающей запятой на Vector2.
Проблема в том, что когда я нажимаю стрелку или клавиши AD для перемещения символа, появляется сообщение об ошибке: «Невозможно прочитать значение типа Vector2 из составного». Эта ошибка связана с InputActionState — длинным и сложным кодом, связанным с новой системой ввода. Кроме того, получение ввода с геймпада вызывает ту же ошибку. Я не знаю, что означает эта ошибка и как ее исправить.
Теперь игрок может прыгать, но не может двигаться или переворачиваться. Ниже вы можете увидеть код, ошибку и мою карту действий.
Это мой контроллер проигрывателя:

Код: Выделить всё

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed, jumpSpeed;
[SerializeField] private LayerMask ground;
private PlayerActionControls playerActionControls;
private Rigidbody2D rb;
private PolygonCollider2D pol;
private Animator animator;
private bool facingRight = true;
private Vector2 movementInput;

private void Awake() {

playerActionControls = new PlayerActionControls();
rb = GetComponent();
pol = GetComponent
();
animator = GetComponent();

}

private void OnEnable() {

playerActionControls.Enable();

}

private void OnDisable() {

playerActionControls.Disable();
}

void Start()
{
playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue());

}

private void Jump(float val) {
if (val == 1 && IsGrounded()) {
rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);
}
}

private bool IsGrounded() {

Vector2 topLeftPoint = transform.position;
topLeftPoint.x -= pol.bounds.extents.x;
topLeftPoint.y += pol.bounds.extents.y;

Vector2 bottomRightPoint = transform.position;
bottomRightPoint.x += pol.bounds.extents.x;
bottomRightPoint.y -= pol.bounds.extents.y;

return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
}
void FixedUpdate()
{
if(facingRight == false && movementInput.x > 0){
Flip();
} else if (facingRight == true && movementInput.x < 0){
Flip();
}
}
void Flip(){
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}

void Update()
{
Vector2 movementInput = playerActionControls.Land.Move.ReadValue();

Vector2 currentPosition = transform.position;  // This was a Vector3 but since I got the error  "Operator '+=' is ambiguous on operands of type 'Vector3' and 'Vector2", I changed it to a Vector2.
currentPosition += movementInput * speed * Time.deltaTime;
transform.position = currentPosition;

}
}
Это ошибка, которую я получаю, когда хочу переместить проигрыватель.
[img]https://i.sstatic. net/fZyXz.png[/img]
Это моя карта действий.
Изображение


Подробнее здесь: https://stackoverflow.com/questions/650 ... r-in-unity

Вернуться в «C#»