Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Question about ref keyword usage and static methods

Discussion in 'Entity Component System' started by AlexAdach, Jul 14, 2023.

  1. AlexAdach

    AlexAdach

    Joined:
    Jan 25, 2023
    Posts:
    24
    I supposed this is more of a general C# question, but is there a rule for what needs to be passed by ref when creating a private method inside a system?

    I understand the concept behind the ref keyword, but I'm struggling to understand when it's required. Basically when you use ref, the parameter you pass in isn't a copy of that object, but a reference to the object itself. In ECS is there a rule of thumb for when that is required?

    If I created a native array in the OnUpdate of the system and I wanted to pass it into a method, I should probably use ref as there's a memory allocator associated with it and I don't want to create a new instance of that native array during method invocation?

    also, my understanding of static methods is that you do not want to reference any fields outside what was passed into the method parameters for thread safety? Basically give input, operate on input, provide output.

    If my logic here is correct, would that mean that any method that has a ref parameter should not be static, as it's operating on a resource that exists outside the method scope? Or does it not matter in this context as there's generally only one instance of a system?

    I'm just an audio guy who's found a passion in programming, no comp sci degree here. so any help is appreciated :)
     
  2. DreamingImLatios

    DreamingImLatios

    Joined:
    Jun 3, 2017
    Posts:
    3,976
    Except for some codegen IJobEntity stuff, there isn't a hard rule. But it is recommended for larger structs. For me, I try to use ref for any struct larger than 16 bytes. The 9-16 byte range tends to be volatile to the use case whether it is better with or without. Also, when using Burst, the "in" keyword can substitute ref if you only ever need to read the argument.

    The NativeArray is a struct which contains a pointer to the underlying memory, so copying a NativeArray struct by value does not deep-copy it. With that said, I still usually pass it by in or ref personally.

    You want to ignore static fields. Otherwise, try to avoid secondary surprise effects, but there's no hard rules.

    No, because the resource is in scope of the caller, which is locked to the same thread.

    Systems are completely irrelevant to everything else discussed.
     
    apkdev and xVergilx like this.