Unity3D: Return value with a Delegate

I want to be able to get the return values from all the methods in my delegate. This is the code I have written in c#.

    using UnityEngine;
    using System.Collections;

    public static class DelagetsAndEvents {

        public delegate int UnitEventHandler(string _unit);
        public static event UnitEventHandler unitSpawn;

        public static int UnitSpawn(string _unit)
        {
            if(unitSpawn != null)
            {
                unitSpawn(_unit);
            }

            // here I want to return 1 + 2 from Planet/UnitSpawn and SolarSystem/UnitSpawn
            // is it possible to run a foreach on every method in the delegate and add their returns?

            return (method 1's return value) + (method 2's return value) (Or both seperately, that would be even better)
        }
    }

    public class Planet {

        public Planet()
        {
            DelagetsAndEvents.unitSpawn += UnitSpawn;
        }

        int UnitSpawn(string _unit)
        {
            Debug.Log("yo");
            return 1;
        }
    }

    public class SolarSystem{

        public SolarSystem()
        {
            DelagetsAndEvents.unitSpawn += UnitSpawn;
        }

        int UnitSpawn(string _unit)
        {
            Debug.Log("bla");
            return 2;
        }
    }

As you can see, the delegate has a return type of int. Then the methods I put into my delegate also have the return type of int. One of them return 1 and the other one return 2. Is there a way to get those results to the location where I execute my delegate? That will be here:

using UnityEngine;
using System.Collections;

public class TestDelagets : MonoBehaviour {

    void Start () {
        SolarSystem s = new SolarSystem();
        Planet p = new Planet();
        string g = "";
        int i = DelagetsAndEvents.UnitSpawn(g);
        Debug.Log(i);
    }
}
Jon Skeet
people
quotationmark

Well, in the "regular" .NET framework, you could use Delegate.GetInvocationList. For example, to combine that with LINQ:

// Note: do all of this after checking that unitSpawn is non-null...

var results = unitSpawn.GetInvocationList()
                       .Cast<UnitEventHandler>()
                       .Select(d => d(_unit))
                       .ToList();

I don't know offhand whether that will work with Unity, but I'd hope it would...

If the LINQ part doesn't work, you could use:

var invocations = unitSpawn.GetInvocationList();
var results = new int[invocations.Length];
for (int i = 0; i < invocations.Length; i++)
{
    results[i] = ((UnitEventHandler)invocations[i]).Invoke(_unit);
}

people

See more on this question at Stackoverflow