![見出し画像](https://assets.st-note.com/production/uploads/images/143535581/rectangle_large_type_2_c01e6bef6c9dc1837a81411eaea19f75.png?width=800)
初心者がUnityでゲーム作る Day9 ~整理整頓、削除、DoTween
Day9まとめ
単一責任原則の順守
石が時間で消えるようになった
石がいい感じに降ってくるようになった
クラスを整理する
https://www.slideshare.net/slideshow/unityzenject/82769092#4
資料いわく、役割に応じてクラスを分割した方がいいらしい。
![](https://assets.st-note.com/img/1717740238935-EW0J2ZksyR.png?width=800)
きのう作ったPlayerControllerには、キー入力の管理と移動のスクリプトが両方入っていたので、PlayerMoverとPlayerInputの2つに分割した。
他は一旦ブラックボックスなアイテム管理系以外大丈夫そう。アイテム管理系も適宜やっていく。
クラス名「Item」って奴があって最悪なんですよね。
やりたいことが膨らんできたのでクラス図ってのを作ってみようと思ったが、ブラックボックスを解体するまで一旦お預けとする。
自動書き出しのやり方だけ一旦スクラップしておく。
エンティティの削除と複製元のprefab化
一旦時間で消えるようにした。
public class EntitieDestroyer : MonoBehaviour
{
public float existTimeLimit = 10f;
private float existTime = 0f;
private void FixedUpdate()
{
// 生成からカウントを開始して、上限時間になったら削除
existTime += Time.deltaTime;
if (existTime > existTimeLimit)
{
Destroy(gameObject);
}
}
}
![](https://assets.st-note.com/img/1717750495049-Ldw6wKPlgC.png)
複製元はprefabにすればscene上から消し去れた。
clone1個ごとにexistTimeがカウントされるので、上記コードなら10秒後にエンティティが消える。マインクラフトだと5分で消えるやつ。
existTimeをpublicにすると全部のエンティティでタイマーが共有され、10秒後に全てが削除される。(笑った)
時間指定で発火させてみよう。
毎フレーム加算処理しているのでイケてない気もしないでもない。10秒後に発火する関数、とかないものか。
あった。
{
private float existTimeLimit = 3f;
private void Awake()
{
Invoke(nameof(DestroyTimeLimitEntitite), existTimeLimit);
}
private void DestroyTimeLimitEntitite()
{
// 削除
Destroy(gameObject);
print($"オブジェクト {gameObject.name} が削除されたよ!");
}
}
これで処理が軽くなった。
Invokeの呼び出しにはAwakeを使う。StartとかOnValidateでやったけど、シーンの開始時に1度呼び出すって関数なのでシーンにオブジェクトが生成されていないと意味をなさない模様。
生成される石がバラっとなるのを何とかする
![](https://assets.st-note.com/img/1717750713563-HBp0HTl0mh.png?width=800)
{
// 移動力の宣言
float landingHeight = -0.2f;
float jumpHeight = 3f;
float jumpPower = 0.2f;
float fallPower = 0.5f;
// 乱数で飛んでいくレンジの設定
float jumpX;
float jumpZ;
float jumpXRange = 1f;
float jumpZRange = 0.3f;
// アニメーション尺の設定
float jumpAnimDulation = 0.2f;
float fallDelay = 0.1f;
// Start is called before the first frame update
void Start() { }
// Update is called once per frame
void Update() { }
public void MinedJump(GameObject obj)
{
// 飛んでいく場所を設定
jumpX = Random.Range(-jumpXRange, jumpXRange);
jumpZ = Random.Range(-jumpZRange, 0);
// 跳ねさせるアニメーション
obj.transform
.DOLocalJump(
new Vector3(
this.transform.position.x + jumpX,
landingHeight + jumpHeight,
this.transform.position.z + jumpZ
),
jumpPower,
1,
jumpAnimDulation
)
.SetEase(Ease.OutQuad);
// 落とすアニメーション
obj.transform
.DOLocalMove(
new Vector3(
this.transform.position.x + jumpX,
landingHeight,
this.transform.position.z + jumpZ
),
fallPower
)
.SetEase(Ease.InCubic)
.SetDelay(jumpAnimDulation - fallDelay);
}
}
![](https://assets.st-note.com/production/uploads/images/143530604/picture_pc_b6985f3e22ea47b706fca5637065aff0.gif)
DoTweenを使ってアニメーションさせた。よい感じです。
この記事が気に入ったらサポートをしてみませんか?