유니티 메모장

키입력(InputAction) 직렬화 및 오브젝트 이동

게임을만들어보자 2025. 6. 3. 11:34
using UnityEngine;
using UnityEngine.InputSystem;

public class Movement : MonoBehaviour
{
    [SerializeField] InputAction upKey;
    //입력받을 버튼은 인스펙터에서 설정
    float moveSpeed = 1f;
    //이동속도 변수

    float xValue;
    //X좌표값 변수

    Transform myTransform;
    //Transform캐싱

    void OnEnable() //스크립트가 활성화 될 때마다 호출
    {
        upKey.Enable();  //해당 인풋액션을 활성화
    }

    void Start()
    {
        myTransform = GetComponent<Transform>();
        xValue = myTransform.position.x;
        //현재 위치값 획득
    }

    void Update()
    {
        zValue = zValue + upKey.ReadValue<float>() * moveSpeed * Time.deltaTime;
        //방향키 입력시 해당 값 만큼
        myTransform.position = new Vector3(xValue, 0, 0);
        //오브젝트 이동
    }
}