我是一名新程序员,使用c#在Unity中制作自上而下的2d游戏,但不断出现错误:
UnassignedReferenceException:PlayerMovement的变量动画师尚未分配。您可能需要在检查器中分配PlayerMovement脚本的动画器变量。UnityEngine.Animator.SetFloat(System.String名称,System.Single值)(位于<049be2afe36f487eb06ef49d51a0bab6>:0)PlayerMovement.Update()(位于Assets / Scripts / PlayerMovement.cs:23)
我不知道这意味着什么,但是我认为我没有正确地将PlayerMovement变量分配给某些东西?这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Animator animator;
Vector2 movement;
// Update is called once per frame
void Update()
{
// Input
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
movement = movement.normalized;
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Speed", movement.sqrMagnitude);
}
void FixedUpdate()
{
// Movement and physics
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
感谢您的任何帮助:)
没有对象引用来调用方法SetFloat()。您必须在Start方法中实例化Animator
对象,以避免发生此异常:
void Start()
{
//Get the animator, which you attach to the GameObject you are intending to animate.
animator= gameObject.GetComponent<Animator>();
});