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

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

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

Q&A

1回答

937閲覧

Unity NullReferenceエラー

ShunyaKogure

総合スコア7

0グッド

0クリップ

投稿2018/03/18 09:52

Unity 2017.3f1を使用してRPGゲームのターン制システムを実装しようとしているのですが、

NullReferenceException: Object reference not set to an instance of an object
TurnController.Update () (at Assets/Scripts/TurnController.cs:27)

というエラーが出てしまってなかなか解決できません。
1ターンに置ける行動とをを1アクションとして、アクションのキューを作って一つ一つ実行しようとしています。
エラーしたから5行目のwaitAction.fight()のところで生じているようです。
よろしくお願いします。

以下がソースコードです。

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

public class TurnController : MonoBehaviour {

public BattleChara[] playerList;
public Queue<ActionController> waitActions;
public GameObject Action;
// Use this for initialization
void Start ()
{
Queue<ActionController> waitActions = new Queue<ActionController>();
int length = playerList.Length;
int i;
for (i = 0; i < length; i++)
{
GameObject action = Instantiate(Action);
ActionController a = action.GetComponent<ActionController>();
a.attacker = playerList[i];
a.defender = playerList[Random.Range(0, length)];
waitActions.Enqueue(a);
}
}
// Update is called once per frame
void Update () {
foreach(ActionController waitAction in waitActions)
{
waitAction.fight();
waitActions.Dequeue();
}
}
}

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

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

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

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

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

guest

回答1

0

C#

1public class TurnController : MonoBehaviour { 2 3 // これを(1)とする 4 public Queue<ActionController> waitActions; 5 6 // Use this for initialization 7 void Start () 8 { 9 // (1)と同じ名前の変数を改めて定義している 10 // そのため、このwaitActionsは(1)とは別物 11 Queue<ActionController> waitActions = new Queue<ActionController>(); 12 13 // …(中略) 14 15 } 16 // Update is called once per frame 17 void Update () { 18 // (1)が使われるが、(1)には何も代入されていない(=null)なので、NullReferenceExceptionが発生する 19 foreach(ActionController waitAction in waitActions) 20 { 21 waitAction.fight(); 22 waitActions.Dequeue(); 23 } 24 } 25}

質問文にソースコードを書く際は、「```」で囲むと見やすくなります。

投稿2018/03/18 10:34

fiveHundred

総合スコア9805

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問