为什么我在 Unity 中的操纵杆会出现此错误?
Why do I get this error for a joystick in Unity?
我目前正在制作一个 2D 游戏作为初学者,我想在我的游戏中添加操纵杆控件。我做的一切都像 Brackeys 的 youtube 视频,但我总是得到这个错误:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:21)
有人能帮我吗? YouTube 视频和时间戳的 link 是:
https://youtu.be/bp2PiFC9sSs?t=780
我当前的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController2D controller;
public Animator animator;
public Joystick joystick;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
// Update is called once per frame
void Update() {
if (joystick.Horizontal >= .2f)
{
horizontalMove = runSpeed;
} else if (joystick.Horizontal <= -.2f)
{
horizontalMove = -runSpeed;
} else
{
horizontalMove = 0f;
}
float verticalMove = joystick.Vertical;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (verticalMove >= .5f)
{
jump = true;
animator.SetBool("IsJumping", true);
}
if (verticalMove <= -.5f)
{
crouch = true;
}
else
{
crouch = false;
}
}
public void OnLanding ()
{
animator.SetBool("IsJumping", false);
}
public void OnCrouching (bool isCrouching)
{
animator.SetBool("IsCrouching", isCrouching);
}
void FixedUpdate ()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
}
根据视频,您必须将场景层次结构中的 FixedJoystick 对象拖放到 PlayerMovement 的操纵杆字段中在检查器中(从视频中查看 11:24)
我目前正在制作一个 2D 游戏作为初学者,我想在我的游戏中添加操纵杆控件。我做的一切都像 Brackeys 的 youtube 视频,但我总是得到这个错误:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:21)
有人能帮我吗? YouTube 视频和时间戳的 link 是:
https://youtu.be/bp2PiFC9sSs?t=780
我当前的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController2D controller;
public Animator animator;
public Joystick joystick;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
// Update is called once per frame
void Update() {
if (joystick.Horizontal >= .2f)
{
horizontalMove = runSpeed;
} else if (joystick.Horizontal <= -.2f)
{
horizontalMove = -runSpeed;
} else
{
horizontalMove = 0f;
}
float verticalMove = joystick.Vertical;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (verticalMove >= .5f)
{
jump = true;
animator.SetBool("IsJumping", true);
}
if (verticalMove <= -.5f)
{
crouch = true;
}
else
{
crouch = false;
}
}
public void OnLanding ()
{
animator.SetBool("IsJumping", false);
}
public void OnCrouching (bool isCrouching)
{
animator.SetBool("IsCrouching", isCrouching);
}
void FixedUpdate ()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
}
根据视频,您必须将场景层次结构中的 FixedJoystick 对象拖放到 PlayerMovement 的操纵杆字段中在检查器中(从视频中查看 11:24)