AddFunction
void AddFunction(Action function);
Adds a function to the internal thread pool. All functions are synchronized and executed precisely once per frame during Unity’s update call. Data exclusive to the main thread can be accessed during the normal Update function and used in every parallel executed function. Unless variables are accessed from multiple parallel functions, there will be no race conditions, and no additional steps are needed to ensure data integrity.
Parameters
function
Function to be added. Only takes functions with no parameters and no return value.
Example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerController : ThreadHarmonizerEngine.MonoBehaviourMultithreaded
{
public float speed = 5.0f; // Movement speed
public float jumpForce = 5.0f; // Jump force
public float gravity = 9.81f; // Gravity force
private CharacterController controller;
private Vector3 moveDirection = Vector3.zero;
private bool isGrounded;
private bool isJumping;
private float moveHorizontal;
private float moveVertical;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
AddFunction(ParallelUpdate);
}
void Update()
{
isGrounded = controller.isGrounded;
isJumping = Input.GetButtonDown("Jump");
moveHorizontal = Input.GetAxis("Horizontal");
moveVertical = Input.GetAxis("Vertical");
// Move the character
controller.Move(moveDirection * Time.deltaTime);
}
// ParallelUpdate is called once per frame
void ParallelUpdate()
{
// Calculate movement direction
Vector3 direction = new Vector3(moveHorizontal, 0, moveVertical);
direction *= speed;
// If grounded, allow jumping
if (isGrounded)
{
moveDirection = direction;
if (isJumping)
{
moveDirection.y = jumpForce;
}
}
else
{
// Apply gravity while not grounded
moveDirection.y -= gravity * DeltaTime;
}
}
private void OnDestroy()
{
DisableMultithreading();
}
private void OnDisable()
{
DisableMultithreading();
}
private void OnEnable()
{
EnableMultithreading();
}
}