0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】繰り返しアニメーションさせるだけのコンポーネント

Posted at

経緯

Unityで2Dゲームを作る際、繰り返しアニメーションをするだけのオブジェクトや、アニメーションが終わったら消滅するだけのオブジェクトを配置する事はよくありますが、一つひとつUnity標準のAnimatorControllerを使っていてはキリがありません。そこで、繰り返しアニメーションさせるだけのコンポーネントを実装しました。

実装

「SpriteAnimation」というスクリプトを作成し、下記をコピペして使用できます。

SpriteAnimation.cs
using System.Collections.Generic;
using UnityEngine;
using System;

public class SpriteAnimation : MonoBehaviour
{
    [SerializeField]
    SpriteRenderer spriteRenderer;
    [SerializeField]
    List<Sprite> sprites;
    [SerializeField]
    bool loop, destroy;
    [SerializeField]
    float second;

    int count;
    float time;

    void Start()
    {
        spriteRenderer.sprite = sprites[0];
    }

    void Update()
    {
        time += Time.deltaTime;
        if (time > second)
        {
            time -= second;
            count++;
            spriteRenderer.sprite = sprites[count];

            if (count < sprites.Count - 1) return;
            if (loop) count = -1;
            else if (destroy) Destroy(gameObject);
            else disposable.Dispose();
        }
    }
}

インスペクター上の項目説明

  • SpriteRenderer : アニメーションさせるSpriteRendererをアタッチ
  • Sprites : アニメーションに使用するSpriteを順番にアタッチ
  • Loop : Loopさせる場合はチェック
  • Destroy : アニメーションの終了後に破壊するならチェック
  • Second : アニメーションの速度

UniRX版

こっちの方が低負荷

SpriteAnimation.cs
using System.Collections.Generic;
using UnityEngine;
using UniRx;
using System;

public class SpriteAnimation : MonoBehaviour
{
    [SerializeField]
    SpriteRenderer spriteRenderer;
    [SerializeField]
    List<Sprite> sprites;
    [SerializeField]
    bool loop, destroy;
    [SerializeField]
    float second;

    int count;
    IDisposable disposable;

    void Start()
    {
        spriteRenderer.sprite = sprites[0];

        disposable = Observable.Interval(TimeSpan.FromSeconds(second))
        .Subscribe(_=>
        {
            count++;
            spriteRenderer.sprite = sprites[count];
            
            if (count < sprites.Count - 1) return;
            if (loop) count = -1;
            else if (destroy) Destroy(gameObject);
            else disposable.Dispose();

        }).AddTo(this);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?