Star☆Unityメモ

Unityのちょっとしたことをメモって後で見返せれたらいいなサイト

Listにクラスを入れると予想以上に便利になった

概要

  1. List内要素に自作クラスの型を入れるとものすごくコードが読みやすくなったのでメモ

編集前のクソコード(モンスターコード)

// モンスターの回転と攻撃anim
if (sm.playerArray[enemyPositionX, enemyPositionZ -1] == 2) {
    iTween.RotateTo(monsterList[i], iTween.Hash("y", 180, "islocal", true, "time", 0.2f));
    monsterList[i].GetComponent<Animator>().SetTrigger("Attack");
    sm.player.GetComponent<PlayerStatus>().Receive(1);
    yield return new WaitForSeconds(0.4f);
} else if(sm.playerArray[enemyPositionX, enemyPositionZ + 1] == 2){
    iTween.RotateTo(monsterList[i], iTween.Hash("y", 0, "islocal", true, "time", 0.2f));
    monsterList[i].GetComponent<Animator>().SetTrigger("Attack");
    sm.player.GetComponent<PlayerStatus>().Receive(1);
    yield return new WaitForSeconds(0.4f);
} else if(sm.playerArray[enemyPositionX + 1, enemyPositionZ] == 2) {
    iTween.RotateTo(monsterList[i], iTween.Hash("y", 90, "islocal", true, "time", 0.2f));
    monsterList[i].GetComponent<Animator>().SetTrigger("Attack");
    sm.player.GetComponent<PlayerStatus>().Receive(1);
    yield return new WaitForSeconds(0.4f);
} else if(sm.playerArray[enemyPositionX - 1, enemyPositionZ] == 2){
    iTween.RotateTo(monsterList[i], iTween.Hash("y", 270, "islocal", true, "time", 0.2f));
    monsterList[i].GetComponent<Animator>().SetTrigger("Attack");
    sm.player.GetComponent<PlayerStatus>().Receive(1);
    yield return new WaitForSeconds(0.4f);
}

パット見でわかる同じことの繰り返し.

f:id:zvn_X:20170122164656p:plain

赤と青で囲った部分以外は全て同じなのに繰り返し繰り返し処理を書いてあげてます....これだと入力ミスの可能性は上がりますし可読性が皆無です.
この状況をなんとかしたい....

ステップ1.必要な情報を持つクラスを作る

今回は方角,またそれらに付随した回転角度などをまとめたクラスを作ります.

public class NEWS{
    public string name { get; set;}
    public int[] direction { get; set;}
    public int rotateValue { get; set; }
}

ステップ2List<リスト内の要素の型>

リスト内の要素の型を自作のクラスにしてインスタンスを作成します. 後はリストにインスタンスとそれに必要なデータを入れてあげる.

List<NEWS> news = new List<NEWS>();
news.Add(new NEWS() { name = "N", rotateValue = 0, direction = new int[] { 0, -1 } });
news.Add(new NEWS() { name = "E", rotateValue = 90, direction = new int[] { 1, 0 } });
news.Add(new NEWS() { name = "S", rotateValue = 180, direction = new int[] { 0, 1 } });
news.Add(new NEWS() { name = "W", rotateValue = 270, direction = new int[] { -1, 0 } });

ステップ3 後はfor文で回すだけ!

bool isAttack = false;
for (int j = 0; j < news.Count; j++){
    if (sm.playerArray[enemyPositionX + news[j].direction[0], enemyPositionZ - news[j].direction[1]] == 2) {
        iTween.RotateTo(monsterList[i], iTween.Hash("y", news[j].rotateValue, "islocal", true, "time", 0.2f));
        monsterList[i].GetComponent<Animator>().SetTrigger("Attack");
        sm.player.GetComponent<PlayerStatus>().Receive(1);
        yield return new WaitForSeconds(0.4f);
        isAttack = true;
    }
}