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

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

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

Unityは、Unity Technologiesが開発・販売している、IDEを内蔵するゲームエンジンです。主にC#を用いたプログラミングでコンテンツの開発が可能です。

Q&A

解決済

1回答

7636閲覧

MissingComponentExceptionのエラー

退会済みユーザー

退会済みユーザー

総合スコア0

Unity

Unityは、Unity Technologiesが開発・販売している、IDEを内蔵するゲームエンジンです。主にC#を用いたプログラミングでコンテンツの開発が可能です。

0グッド

0クリップ

投稿2016/10/26 02:53

MissingComponentException: There is no 'Rigidbody2D' attached to the "Cube" game object, but a script is trying to access it.
You probably need to add a Rigidbody2D to the game object "Cube". Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody2D.get_position () (at /Users/builduser/buildslave/unity/build/artifacts/generated/common/modules/Physics2D/Physics2DBindings.gen.cs:1345)
Player2D.FixedUpdate () (at Assets/Player2D.cs:18)
とエラーが出ました。

CubeのインスペクタにRigidbody2Dをつけても、エラーが消えません。

CubeについているスクリプトはPlayer2D.csで

using UnityEngine; using System.Collections; public class Player2D : MonoBehaviour { Rigidbody2D rigidbody; Vector2 velocity; void Start () { rigidbody = GetComponent<Rigidbody2D> (); } void Update () { velocity = new Vector3 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical")).normalized * 10; } void FixedUpdate() { rigidbody.MovePosition (rigidbody.position + velocity * Time.fixedDeltaTime); } }

と書きました。

どこを直せば良いのでしょうか?

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

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

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

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

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

guest

回答1

0

ベストアンサー

StartでGetComponentした後、Rigidbody2Dの取得が完了する前にUpdate/FixedUpdateが呼ばれるのが原因かと思います。

「void Start()」を「void Awake()」に変えるか、
「void FixedUpdate()」を以下のように書き換えてみてください。

C#

1void FixedUpdate() { 2 if (rigidbody != null) { 3 rigidbody.MovePosition (rigidbody.position + velocity * Time.fixedDeltaTime); 4 } 5}

投稿2016/10/27 02:49

sakura_hana

総合スコア11427

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問