Hyluss icon

[Unity] GameObjectExtensions

Hyluss | PRO | 11/29/17 09:05:18 PM UTC | 0 ⭐ | 439 👁️ | Never ⏰ | []
C# |

1.83 KB

|

None

|

0 👍

/

0 👎

public class GameObjectExtensions
{
    private static void InvokeParameterisedAwake(GameObject newObject, object[] arg)
    {
        foreach (MonoBehaviour behaviour in newObject.GetComponents<MonoBehaviour>())
        {
            foreach (MethodInfo info in behaviour.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance))// | BindingFlags.DeclaredOnly))
            {
                if (String.Compare(info.Name, "Awake") == 0)
                {
                    ParameterInfo[] parameters = info.GetParameters();
                    if (parameters.Length == arg.Length)
                    {
                        bool typesMatch = true;
                        for (int i = 0; i < (parameters.Length)  (typesMatch == true); i++)
                        {
                            if (parameters[i].ParameterType != arg[i].GetType())
                            {
                                typesMatch = false;
                            }
 
                        }
 
                        if (typesMatch == true)
                        {
                            info.Invoke(behaviour, arg);
                        }
 
                    }
 
                }
            }
        }
    }
    public static GameObject Instantiate(GameObject O, params object[] arg)
    {
        GameObject newObject = GameObject.Instantiate(O) as GameObject;
 
        InvokeParameterisedAwake(newObject, arg);
        return newObject;
    }
 
}
 
 
public class AwakeTest : MonoBehaviour
{
    public GameObject target;
 
    void Start()
    {
        GameObject go1 = GameObjectExtensions.Instantiate(target, 10);
        GameObject go2 = GameObjectExtensions.Instantiate(target, "Hello world!");
        GameObject go3 = GameObjectExtensions.Instantiate(target, 10.2f, 20.5f, 30);
    }
 
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎