Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- namespace ReflectionTest
- {
- public abstract class SomeBehaviour
- {
- internal MethodInfo startMethod = null;
- internal MethodInfo updateMethod = null;
- }
- public class SomeScript : SomeBehaviour
- {
- private void Start()
- {
- Console.WriteLine("SomeScript.Start");
- }
- }
- public class AnotherScript : SomeBehaviour
- {
- private void Start()
- {
- Console.WriteLine("AnotherScript.Start");
- }
- private void Update()
- {
- Console.WriteLine("AnotherScript.Update");
- }
- }
- internal class Program
- {
- private static List<SomeBehaviour> objects = new List<SomeBehaviour>();
- public static SomeBehaviour CreateObject(string typeName)
- {
- SomeBehaviour ret = null;
- try
- {
- Type type = Type.GetType("ReflectionTest." + typeName);
- if (type != null)
- {
- if (type.IsSubclassOf(typeof(SomeBehaviour)))
- {
- ret = (SomeBehaviour)(Activator.CreateInstance(type));
- try
- {
- ret.startMethod = type.GetMethod("Start", BindingFlags.NonPublic | BindingFlags.Instance);
- }
- catch (Exception e)
- {
- Console.Error.WriteLine(e);
- }
- try
- {
- ret.updateMethod = type.GetMethod("Update", BindingFlags.NonPublic | BindingFlags.Instance);
- }
- catch (Exception e)
- {
- Console.Error.WriteLine(e);
- }
- objects.Add(ret);
- }
- }
- }
- catch (Exception e)
- {
- Console.Error.WriteLine(e);
- }
- return ret;
- }
- public static void Run()
- {
- foreach (SomeBehaviour obj in objects)
- {
- if (obj.startMethod != null)
- obj.startMethod.Invoke(obj, new object[0]);
- }
- while (true)
- {
- foreach (SomeBehaviour obj in objects)
- {
- if (obj.updateMethod != null)
- obj.updateMethod.Invoke(obj, new object[0]);
- }
- }
- }
- static void Main(string[] args)
- {
- CreateObject("BlahScript");
- CreateObject("SomeScript");
- CreateObject("AnotherScript");
- Run();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement