Unity Cookbook
  • 2D
    • New Input System - 2D Move
    • Pixel Sprite Setup
    • Animations
    • Animator in Script
    • Tilemap
    • 2D Camera Follow Player
  • UI OnlyFans
    • 9-Splice Sprite
    • Interactible Game Objects
      • NPCs
      • Items
      • Interactible Marker
    • Dialogue System
      • Conversa Plugin
      • DiaManager.cs
      • DiaTrigger.cs
      • DiaManager.cs Alternate
      • Choices in Dialogue
    • New Input System - Interact
    • Designing the General Menu
    • New Input System - Open Menu
      • UI Buttons
      • GeneralMenu.cs
    • Controls Explanation UI
    • Items Menu
Powered by GitBook
On this page
  1. 2D

Animator in Script

Once the Animator Component is setup, you can control the parameters via script.

PreviousAnimationsNextTilemap

Last updated 1 year ago

The parameters can be set in the Animator controller. Anything in "Quotes" is what you wrote down as a variable there.

[SerializeField] private Animator anim;

Drag the GameObject in the scene view into the "Anim" field.

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

public class PlayerController : MonoBehaviour
{
    private Vector2 movementInput;
    [SerializeField] private float MOVESPEED = 4.0f;
    private Rigidbody2D rb;

    [SerializeField] private Animator anim;


    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }


    public void OnMove(InputAction.CallbackContext ctx)
    {
        movementInput = ctx.ReadValue<Vector2>();

        if (movementInput.x == 1 || movementInput.x == -1 || movementInput.y == 1 || movementInput.y == -1)
        {
            anim.SetFloat("lastMoveX", movementInput.x);
            anim.SetFloat("lastMoveY", movementInput.y);
        }
    }

    private void FixedUpdate()
    {
        //Moving the character
        rb.velocity = movementInput * (MOVESPEED * Time.fixedDeltaTime);

        //Animator Controls, make sure the quotations match the parameter names in the Animator controller
        anim.SetFloat("moveX", rb.velocity.x);
        anim.SetFloat("moveY", rb.velocity.y);
    }
}

Getting the direction of the look is something I'm thinking about. One thing that doesn't throw an error is this:

Debug.Log(anim.GetFloat("lastMoveX"));