Passing a method as a argument

Updated on October 16, 2017 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on October 15, 2017

Hello everyone, I was cleaning up my code and I bumped in to a interesting problem. I don’t know if what I am trying to achieve is possible in Unity C# but here it is. So I have a list of Objects and I want a function that iterates through all of the objects in the list and calls a certain function on the object. Here is simplified code of what I am trying to achieve:

void ForAllIn(List<Enemy> eList, /* the action to preform */  action)
{
foreach(Enemy e in eList)
{
e.action();
}
}

I could just pass the action a string and then check with switch statement, but then my code wont look as clean and slick :p . I googled about the problem and found some way to do this with a delegate, but it doesnt work for me since I want to call a methhod in the Enemy object. If you have any ideas feel free to comment. Thanks 🙂

  • Liked by
Reply
1 on October 15, 2017

It’s unclear what you’re asking. You want to pass an action to the action method?

on October 15, 2017

I dont know how to explain it better so I will add a couple of examples to hopefully make it clear

Show more replies
  • Liked by
Reply
Cancel
0 on October 16, 2017
  • Liked by
Reply
Cancel