Last active
December 18, 2015 11:59
-
-
Save asus4/5779756 to your computer and use it in GitHub Desktop.
Randomize the oher component properties.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
using System.Reflection; | |
/// <summary> | |
/// Ramdomize Other Component Property | |
/// </summary> | |
[AddComponentMenu("Libs/Modules/PropertyRandomizer")] | |
public class PropertyRandomizer : MonoBehaviour { | |
[Serializable] | |
public class RandomProp { | |
public string compName; | |
public string propName; | |
public float ramdomness; | |
} | |
[SerializeField] | |
RandomProp[] props; | |
void Start () { | |
foreach(var prop in props) { | |
Randomize(prop); | |
} | |
// auto destroy | |
Destroy(this); | |
} | |
void Randomize(RandomProp prop) { | |
Component comp = this.GetComponent(prop.compName); | |
if(comp == null) { | |
Debug.LogError("[PropertyRandomizer] "+ this.name +" : invaild component name - "+prop.compName); | |
return; | |
} | |
Randomize(comp, prop); | |
} | |
void Randomize (Component comp, RandomProp prop) | |
{ | |
Type type = comp.GetType(); | |
PropertyInfo field = type.GetProperty(prop.propName); | |
if(field == null) { | |
Debug.LogError("[PropertyRandomizer] "+ this.name +" : invaild property name - "+prop.propName); | |
return; | |
} | |
Type fieldType = field.PropertyType; | |
if(fieldType == typeof(float)) { | |
float val = (float) field.GetValue(comp, null); | |
val = val + val * UnityEngine.Random.Range(-prop.ramdomness, prop.ramdomness); | |
field.SetValue(comp, val, null); | |
} | |
else if(fieldType == typeof(Vector3)) { | |
Vector3 val = (Vector3) field.GetValue(comp, null); | |
val = val + val * UnityEngine.Random.Range(-prop.ramdomness, prop.ramdomness); | |
field.SetValue(comp, val, null); | |
} | |
else if(fieldType == typeof(int)) { | |
float val = (float) (int) field.GetValue(comp, null); | |
val = (float)val + val * UnityEngine.Random.Range(-prop.ramdomness, prop.ramdomness); | |
field.SetValue(comp, Mathf.RoundToInt(val), null); | |
} | |
else if(fieldType == typeof(Vector2)) { | |
Vector2 val = (Vector2) field.GetValue(comp, null); | |
val = val + val * UnityEngine.Random.Range(-prop.ramdomness, prop.ramdomness); | |
field.SetValue(comp, val, null); | |
} | |
else { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment