Unityでゲーム開発中に調べたこと。

フレームレートの設定

参照元 https://blog.unity.com/ja/technology/precise-framerates-in-unity

using System.Collections;
using System.Threading;
using UnityEngine;

public class ForceRenderRate : MonoBehaviour
{
    public float Rate = 50.0f;
    float currentFrameTime;

    void Start()
    {
        QualitySettings.vSyncCount = 0;
        Application.targetFrameRate = 9999;
        currentFrameTime = Time.realtimeSinceStartup;
        StartCoroutine("WaitForNextFrame");
    }

    IEnumerator WaitForNextFrame()
    {
        while (true)
        {
            yield return new WaitForEndOfFrame();
            currentFrameTime += 1.0f / Rate;
            var t = Time.realtimeSinceStartup;
            var sleepTime = currentFrameTime - t - 0.01f;
            if (sleepTime > 0)
                Thread.Sleep((int)(sleepTime * 1000));
            while (t < currentFrameTime)
                t = Time.realtimeSinceStartup;
        }
    }
}

アニメーションを使わずにスプライトをアニメーションさせる

参考元 https://unity-yuji.xyz/simple-sprite-animation-script/

アニメーションは、視覚的にわかりやすいが、ぱんぞうゲームは、スクリプトで制御した。できるかどうかの確認。
参照元は、エラーで動かなかったので、一部修正した。

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

public class SpriteAnimation : MonoBehaviour {




    [SerializeField] Sprite[] sprites;  //アニメーションに使うスプライト
    [SerializeField] int frame;  //何フレームでスプライトを切り替えるか(=アニメーションの速さ)
    [SerializeField] int offset;  //何個目のスプライトから始めるか(通常は0でいいはず)
    [SerializeField] bool loop;  //アニメーションをループさせるか
    [SerializeField] bool playOnAwake;  //起動時からアニメーションさせるか

    SpriteRenderer myRenderer;  //SpriteRendererをキャッシュ
    int count;  //フレームのカウント用
    int spriteCount;  //スプライトの数
    int nowSprite;  //現在のスプライト番号
    [System.NonSerialized] public bool active;  //外部からアニメーションの再生・停止するための変数

    

    // Start is called before the first frame update
    void Start()
    {
       
      myRenderer = gameObject.GetComponent<SpriteRenderer>();

     spriteCount = sprites.Length;
        nowSprite = offset;
        active = playOnAwake;
        count = 0;
        myRenderer.sprite = sprites [nowSprite];

    }

        void Update(){
        if (active) {
            count++;
            if (count == frame) {
                count = 0;
                NextSprite ();
            }
        }
    }




    void NextSprite(){
        if (!loop && nowSprite == spriteCount - 1) {
            active = false;
        } else {
            nowSprite = (nowSprite + 1) % spriteCount;
           myRenderer.sprite = sprites [nowSprite];
        }

}


   
}

Start() or Awake()

Awakeは、開始時、Startの先に1回のみ呼び出される。複数のAwakeの順番の制御はできない。初期化に使うとよい。

コンソールにログを表示させる

Debug.Log("コンソールに表示");

この記事が気に入ったらサポートをしてみませんか?