質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%

Q&A

解決済

1回答

2720閲覧

UnityでのエラーNullReferenceExceptionの改善方法が知りたいです。

akatyann

総合スコア2

0グッド

0クリップ

投稿2020/08/23 12:48

前提・実現したいこと

アニメーションを移動に合わせて遷移させたいです。

発生している問題・エラーメッセージ

NullReferenceException: Object reference not set to an instance of an object
Character.AnimateMovement (UnityEngine.Vector2 direction) (at Assets/Script/Character.cs:39)
Character.Move () (at Assets/Script/Character.cs:33)
Character.Update () (at Assets/Script/Character.cs:25)
Player.Update () (at Assets/Script/Player.cs:21)

該当のソースコード

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

public abstract class Character : MonoBehaviour
{
//The Player's movement speed
[SerializeField]
private float speed;

private Animator animator; //The Player's direction protected Vector2 direction; // Start is called before the first frame update void Start() { animator = GetComponent<Animator>(); } // Update is called once per frame protected virtual void Update() { Move(); } public void Move() { transform.Translate(direction * speed * Time.deltaTime); AnimateMovement(direction); } public void AnimateMovement(Vector2 direction) { animator.SetFloat("x", direction.x); animator.SetFloat("y", direction.y); }

}

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

public class Player : Character
{

// Start is called before the first frame update void Start() { direction = Vector2.up; } // Update is called once per frame protected override void Update() { GetInput(); base.Update(); } private void GetInput() { direction = Vector2.zero; if (Input.GetKey(KeyCode.W)) { direction += Vector2.up; } if (Input.GetKey(KeyCode.A)) { direction += Vector2.left; } if (Input.GetKey(KeyCode.S)) { direction += Vector2.down; } if (Input.GetKey(KeyCode.D)) { direction += Vector2.right; } }

}

試したこと

ユーチューブにあった動画を参考に、キャラクターの動きにあわせてアニメーション遷移させようとしていたのですが、どうにもうまくいきません。
キャラクターは上下左右に動いてくれるし、直接「Animator」のパラメーターに数字を打ち込むと数値に合わせてアニメーションしてくれるのですが、
AnimateMovement(direction);の部分がうまく機能してくれません。
何度か動画を見直したり、いろいろネットで調べてみたのですがどうにも分からず質問させてもらいました。
どなたかよろしければご教授願えないでしょうかよろしくおねがいします。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

animator がnullだと思われます
これをアタッチしたオブジェクトにAnimatorがついていますか?

投稿2020/08/23 23:55

izmktr

総合スコア2856

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問