Unityで汎用性高そうな関数(練習)
現在Unityでゲーム開発をしてますが、
どこでも使えそうな関数がいくつか見つかったり出来たりしたので載せます。
using System.Linq; using UnityEngine; using UnityEngine.UI; /* * 他の場所でも使えそうな汎用的関数をまとめてあります。 * */ namespace Assets.Script.Common { public static class UsefulFuncs { /* * 画像パスからSpriteオブジェクトを生成 * 引数 :画像パス * ※ :assets直下のResourcesフォルダからの相対パスにすること * :これは、途中使用するResources.Loadによる作用です * 返り値:画像パスのSpriteオブジェクト */ public static Sprite Path2Sprite(string path) { Texture2D texture = Resources.Load(path) as Texture2D; return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); } /* * Spriteオブジェクトを、オブジェクトのimageに貼り付け * 引数 :Spriteオブジェクト, 貼り付け先のオブジェクトパス * ※ :言わずもがな、オブジェクトパスはHierarcyにおけるもの * :GameObject.Findの引数に出来れば何でも良い * 返り値:無し */ public static void SetSprite2Object(Sprite sprite,string objPath) { GameObject.Find(objPath).GetComponent<Image>().sprite = sprite; } /* * 画像パスの画像を、オブジェクトに貼り付け * 引数(1つ目) :画像パス、貼り付け先のオブジェクトパス * 引数(2つ目) :画像パス、貼り付け先のGameObject * 返り値:無し */ public static void SetImage2Object(string imgPath,string objPath) { SetSprite2Object(Path2Sprite(imgPath), objPath); } public static void SetImage2Object(string imgPath,GameObject obj) { obj.GetComponent<Image>().sprite = Path2Sprite(imgPath); } /* * オブジェクトの複製(ジェネリックメソッド版) * 引数 :複製元 * 返り値:複製物 * サイト:ttp://l-s-d.sakura.ne.jp/2016/04/class_obj_copy/ * * 使い方: * var hogeA = new HogeParam(); * HogeParam hogeB; * hogeB = UsefulFuncs.DeepCopy(hogeA); <=これ */ public static T DeepCopy<T>(T target) { T result; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); System.IO.MemoryStream mem = new System.IO.MemoryStream(); try { b.Serialize(mem, target); mem.Position = 0; result = (T)b.Deserialize(mem); } finally { mem.Close(); } return result; } /* * すべての子オブジェクトを返します * 引数 :self : GameObject 型のインスタンス * includeInactive : 非アクティブなオブジェクトも取得する場合 true * 返り値:すべての子オブジェクトを管理する配列 * サイト:ttp://baba-s.hatenablog.com/entry/2014/07/29/082441 */ public static GameObject[] GetChildren( this GameObject self, bool includeInactive = false) { return self.GetComponentsInChildren<Transform>(includeInactive) .Where(c => c != self.transform) .Select(c => c.gameObject) .ToArray(); } } }