Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Created May 23, 2014 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/eb4856bc7a0f98fdc026 to your computer and use it in GitHub Desktop.
Save tsubaki/eb4856bc7a0f98fdc026 to your computer and use it in GitHub Desktop.
複雑なスプライトをUVスクロールしたい場合の例。textureのread/writeにチェックが入っていることが必須条件
using UnityEngine;
using System.Collections;
public class ScrollTexture : MonoBehaviour
{
public Vector2 UVDirection;
private Texture2D tex2d;
private Vector2 currentUVOffset = new Vector2 (0, 1);
void Start ()
{
// ①:テクスチャをロード
Texture2D t1 = Resources.Load<Texture2D> ("Texture1");
Texture2D t2 = Resources.Load<Texture2D> ("Texture2");
// ②:①で取得したテクスチャが全部入る大きさのテクスチャを生成
tex2d = new Texture2D (t1.width, t1.height + t2.height);
// ③:②で作成したテクスチャの色を塗る
tex2d.SetPixels (0, 0, t1.width, t1.height, t1.GetPixels ());
tex2d.SetPixels (0, t1.height, t2.width, t2.height, t2.GetPixels ());
// ④:①でロードしたテクスチャを破棄
Resources.UnloadAsset (t1);
Resources.UnloadAsset (t2);
// ⑤:色を実際に塗る
tex2d.Apply ();
// ⑥:テクスチャからスプライトを生成
var sprite = Sprite.Create (tex2d, new Rect (0, 0, tex2d.width, tex2d.height), new Vector2 (0.5f, 0.5f), 10);
GetComponent<SpriteRenderer> ().sprite = sprite;
}
void OnDestroy ()
{
Destroy (tex2d);
}
void Update ()
{
// UVでスクロール
currentUVOffset += UVDirection * Time.deltaTime;
renderer.material.SetTextureOffset ("_MainTex", currentUVOffset);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment