きっかけ
Trailの色をスクリプトから変更できないか探していたところ、StackOverFlowに以下の様な質問が。
I am creating a Trail Renderer that is modified in script (width, life, material, etc.) I was wondering if there is a way to change the colors array in script as well.
I’ve tried getting the game objects “colors” variable but it says that does not exist even though it is in blue.
This is what I tried:
回答として
The colors array isn’t accessible from the script API, unfortunately.
とあったりするので諦めかけつつスクロールさせると…
// Generate a random color. nColor = new Color(Random.value, Random.value, Random.value, Random.value); // Find the child game object that contains the TrailRenderer. GameObject sphere = transform.Find("Sphere").gameObject; // Get the material list of the trail as per the scripting API. Material trail = sphere.GetComponent<TrailRenderer>().material; // Set the color of the material to tint the trail. trail.SetColor("_Color", nColor);
ほほうなるほど!
さらにスクロールさせると…
using UnityEngine; using System.Collections; namespace UnityEditor { public class trailtest : MonoBehaviour { private void Start() { TrailRenderer tr = GetComponent<TrailRenderer>(); SerializedObject so = new SerializedObject(tr); so.FindProperty("m_Colors.m_Color[0]").colorValue=Color.red; so.FindProperty("m_Colors.m_Color[1]").colorValue = Color.green; so.FindProperty("m_Colors.m_Color[2]").colorValue = Color.blue; so.FindProperty("m_Colors.m_Color[3]").colorValue = Color.white; so.FindProperty("m_Colors.m_Color[4]").colorValue = Color.black; so.ApplyModifiedProperties(); // To show all properies SerializedProperty it = so.GetIterator(); while (it.Next(true)) Debug.Log(it.propertyPath); } } }
というサンプルと共に投稿が。
これは!と思い試すと動かない。
SerializedObjectはUnityEditor namespace 内なので動かない。
– SerializedObject
ならばInspectorを拡張すればいいじゃない…
public override void OnInspectorGUI(){ DrawDefaultInspector(); if( GUILayout.Button("!!") ){ var script = target as TargetComponent; var trail = script.gameObject.GetComponent<TrailRenderer>(); SerializedObject so = new SerializedObject(trail); so.FindProperty("m_Colors.m_Color[0]").colorValue= Color.red; so.FindProperty("m_Colors.m_Color[1]").colorValue = Color.green; so.FindProperty("m_Colors.m_Color[2]").colorValue = Color.blue; so.FindProperty("m_Colors.m_Color[3]").colorValue = Color.white; so.FindProperty("m_Colors.m_Color[4]").colorValue = Color.black; so.ApplyModifiedProperties(); // To show all properies SerializedProperty it = so.GetIterator(); while (it.Next(true)) Debug.Log(it.propertyPath); } }
ボタンを用意してボタンが押されたら取得したコンポーネントの中身を全部ぶんまわす。
見れました。
これで文字列でアクセス可能に。わーい。
で、Runtime上ではどうするの?