Search Unity

Resolved System Method Inheritance and Jobs

Discussion in 'Entity Component System' started by toomasio, Nov 23, 2020.

  1. toomasio

    toomasio

    Joined:
    Nov 19, 2013
    Posts:
    199
    If I wanted to do something like:

    Code (CSharp):
    1. [BurstCompile]
    2.     protected struct ConsumeEventJob: IJobEventReaderForEach<TEvent>
    3.     {
    4.         public void Execute(NativeEventStream.Reader stream, int foreachIndex)
    5.         {
    6.             int count = stream.BeginForEachIndex(foreachIndex);
    7.             for (int i = 0; i < count; i++)
    8.             {
    9.                 var comp = stream.Read<TEvent>();
    10.                 ConsumeEvent(i, comp);
    11.             }
    12.         }
    13.     }
    14.  
    15. protected static void ConsumeEvent(int index, TEvent e) { }
    And expand on the ConsumeEvent in a subclass, how would I go about doing that while following the DOTS rules?

    I looked into PointerFunctions, but I am not sure If that solves my problem here.

    has anyone been able to solve this issue already?

    Also, is it a bad idea to use static methods inside Jobs anyways? Will it cause me issues down the line?

    Thanks,
     
  2. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    4,271
    Static methods are perfectly fine in jobs and Burst and I would even argue they are necessary for more complex things. Heck, if you ever typed
    math.
    you are probably invoking a static method.

    However, static methods don't have an instance to polymorph, so subclassing won't help you. FunctionPointers might work, but if you need to associate data, then you probably want to look at generics instead. Generic jobs have a couple a pitfalls in that you need to have a concrete instance of a job traceable in the typespec, but there's a clever trick you can use to make the compiler generate that for you. https://github.com/Dreaming381/BurstGenericsTest

    Anyways, if that all went over your head, no worries. The short answer is that subclassing is probably the wrong answer. Static methods are usually a right answer. And generic jobs constrained to an interface are typically how people solve the problem you are trying to solve.
     
    Egad_McDad and toomasio like this.
  3. toomasio

    toomasio

    Joined:
    Nov 19, 2013
    Posts:
    199
    @DreamingImLatios Thanks for taking the time and providing an example! Looks like I am going to stick to static methods and generic jobs. Kinda hard to get out of the inheritance mentality once you get used to it.