Variable access simulateneously

Quick question, I have some global static variables in my application and I’m wondering if it would be accidentally possible for 2 functions/objects to try accessing/modifying the same variable at the same time?

As in, Object 1 has it’s own update script (which accesses/uses global variable), and Object 2 has it’s own update script (which accesses/uses the same global variable). As Unity allows each object to be updated independently, doesn’t that mean it’s possible that both those objects might try access/modify the global variable at the same time (causing a memory access issue)?

It will not cause an issue, it can however cause unexpected behavior.

Update methods are actually run in sequence, not in parallel. Unity is only single-core on the logic threading portion of the application.

Unless you’re doing some threading of your own, you’re fine. However, if you start threads that reference data from another function, then you might want to start using locks. (short version: don’t start your own threads.)

The basics to locking:

  1. You create a lock object that derives directly from Object.

    // In the class somewhere, not inside a method
    Object lockObject = new Object();

  2. You only use this object to get and release a lock.

  3. You perform a lock through this:

    lock(lockObject){
    // Stuff here is locked
    }

  4. You only “lock” around variable lookups or value sets. If you need a variable for more than a line or two, look up the value and store it to a local variable.

    var myLocalFloat = 0f;
    lock(lockObject){
    myLocalFloat = someOtherFloatThatHasLockingConcerns;
    }

  5. You “lock” the variable everywhere it’s used from now on.

  6. You can use the same “lock” object for multiple items that share similar data. Use different locks for different data sets. Thus, locks should be class-scoped and not globally scoped.

  7. Use getters and setters or explicitly implemented properties for any data that should be accessed or modified from a lock.

    public int WidgetCount {
    get {
    int widgetCount = 0;
    lock(objectLock) {
    widgetCount = this.widgetCount;
    }
    return widgetCount;
    }
    }

Therefore, keep locking to a minimum. Set up classes for threads before executing them and then don’t mess with any data within the thread. Don’t use threading unless you know what you’re doing.

Note that if you get locking wrong, you could freeze your application while one lock waits for another that will never complete. (Such as locking and then using something that has the same object lock.)

There are Synchronization methods
both in C# (Thread Synchronization (C# and Visual Basic) | Microsoft Learn)
and in Java (java - difference between synchronizing a static method and a non static method - Stack Overflow)