今回は、Untiyの2Dゲームで背景を右から左にループして動かしていきます。画像は1枚だけを使い、右から左だけでなく、左から右、上から下、下から上も簡単に動かすことが出来る方法です。
はじめに
Unityのバージョンは2021.3.3f1です。
画像を2枚並べて、動かす方法は下記で紹介しています。
今回は画像を1枚だけ用意してスクロールして動かしていきます。
画像を用意
まずは背景画像を用意します、下記は適当に作成した画像です。

1枚の画像をループさせるので右端と左端がつながる画像にします。
実装開始
画像の設定を行った後、ゲーム画面に組み込んでいきます。
画像の設定変更
まずはUnityに画像を取り込みます。

次に画像の設定を変更します。TextureTypeを「Default」、WrapModeを「Repeat」にします。

Materialの作成
Project→Assetsフォルダ内にMaterialを追加します。名前はbackgroundにしておきます。

Materialの設定を変更します。Shaderを「Unlit/Texture」に変更して、画像をセットします。

画面作成
Hierarchyで「3DObject」→「Quad」を追加します。Planeでも可。

MeshRendererのMatarials→Elementに作成したマテリアルをセットしてスケールをいい感じに変更します。

下記の様になります。

マテリアルのOffset数値を変更すると画像を動かすことが出来ます。

これをスクリプトで実装して動かしていきます。
スクリプトの作成
下記スクリプトを作成します。今回は右から左に動かすのでOffsetのXが時間経過で増加するようにしています。
using UnityEngine; public class background : MonoBehaviour { [SerializeField] private float _speed; private Material _material; void Start() { _material = GetComponent<Renderer>().material; } void Update() { _material.mainTextureOffset += new Vector2(Time.deltaTime * _speed, 0); } }
Quadに追加してSpeedに適当な数値を入力します。

実行すると下記の様な感じで背景画像が右から左に動きます。
