Skip to main content

Variables API Reference

Complete API reference for SoapKit's variable system.

Base Classes

BaseVariable<T>

The foundation class for all variables in SoapKit.

[System.Serializable]
public abstract class BaseVariable<T> : ScriptableObject, IReadOnlyVariable<T>

Properties

PropertyTypeDescription
ValueTCurrent value of the variable
EnableChangeNotificationboolWhether to trigger change events (default: true)

Events

EventTypeDescription
OnValueChangedSystem.Action<T>Triggered when value changes

Methods

MethodReturn TypeDescription
SetValue(T newValue)voidSets the variable value and triggers change events
NotifyValueChanged()voidManually triggers change notification
TriggerChangeNotification()voidContext menu method for testing

Protected Methods

MethodReturn TypeDescription
AreValuesEqual(T a, T b)boolOverride for custom equality comparison

Editor Integration

  • Context Menu: "Trigger Change Notification" for testing
  • Custom Inspector: Enhanced property drawer with debug tools
  • Real-time Monitoring: Live value display in SoapKit Debug Window

Primitive Variable Types

BoolVariable

Boolean variable with logical operations.

[CreateAssetMenu(menuName = "SoapKit/Variables/Bool Variable")]
public class BoolVariable : BaseVariable<bool>

Specialized Methods

MethodParametersDescription
Toggle()-Toggles the boolean value
SetTrue()-Sets value to true
SetFalse()-Sets value to false
And(bool other)bool otherLogical AND operation
Or(bool other)bool otherLogical OR operation
Xor(bool other)bool otherLogical XOR operation

Usage Example

[SerializeField] private BoolVariable isGamePaused;

private void TogglePause()
{
isGamePaused.Toggle();
}

private void OnEnable()
{
isGamePaused.OnValueChanged += OnPauseStateChanged;
}

IntVariable

Integer variable with mathematical operations and constraints.

[CreateAssetMenu(menuName = "SoapKit/Variables/Int Variable")]
public class IntVariable : BaseVariable<int>

Properties

PropertyTypeDescription
MinValueintMinimum allowed value (optional)
MaxValueintMaximum allowed value (optional)
HasMinValueboolWhether minimum constraint is active
HasMaxValueboolWhether maximum constraint is active

Specialized Methods

MethodParametersDescription
Add(int amount)int amountAdds to current value
Subtract(int amount)int amountSubtracts from current value
Multiply(int factor)int factorMultiplies current value
Divide(int divisor)int divisorDivides current value
Increment()-Adds 1 to current value
Decrement()-Subtracts 1 from current value
SetMin(int min)int minSets minimum constraint
SetMax(int max)int maxSets maximum constraint
Clamp()-Applies min/max constraints

Usage Example

[SerializeField] private IntVariable playerHealth;

private void Start()
{
playerHealth.SetMax(100);
playerHealth.SetValue(100);
}

private void TakeDamage(int damage)
{
playerHealth.Subtract(damage);
if (playerHealth.Value <= 0)
{
// Player died
}
}

FloatVariable

Float variable with mathematical operations, constraints, and precision control.

[CreateAssetMenu(menuName = "SoapKit/Variables/Float Variable")]
public class FloatVariable : BaseVariable<float>

Properties

PropertyTypeDescription
MinValuefloatMinimum allowed value
MaxValuefloatMaximum allowed value
DecimalPlacesintRounding precision (default: 2)
HasMinValueboolWhether minimum constraint is active
HasMaxValueboolWhether maximum constraint is active

Specialized Methods

MethodParametersDescription
Add(float amount)float amountAdds to current value
Subtract(float amount)float amountSubtracts from current value
Multiply(float factor)float factorMultiplies current value
Divide(float divisor)float divisorDivides current value
AddPercentage(float percentage)float percentageAdds percentage of current value
SubtractPercentage(float percentage)float percentageSubtracts percentage of current value
Round()-Rounds to specified decimal places
SetMin(float min)float minSets minimum constraint
SetMax(float max)float maxSets maximum constraint
Lerp(float target, float t)float target, float tLinear interpolation

Usage Example

[SerializeField] private FloatVariable playerSpeed;

private void Start()
{
playerSpeed.SetMin(0f);
playerSpeed.SetMax(10f);
playerSpeed.SetValue(5f);
}

private void ApplySpeedBoost()
{
playerSpeed.AddPercentage(0.5f); // 50% speed boost
}

StringVariable

String variable with text manipulation operations and constraints.

[CreateAssetMenu(menuName = "SoapKit/Variables/String Variable")]
public class StringVariable : BaseVariable<string>

Properties

PropertyTypeDescription
MaxLengthintMaximum string length (0 = unlimited)
MinLengthintMinimum string length

Specialized Methods

MethodParametersDescription
Append(string text)string textAppends text to current value
Prepend(string text)string textPrepends text to current value
Replace(string oldValue, string newValue)string oldValue, string newValueReplaces text
Trim()-Removes leading/trailing whitespace
ToUpper()-Converts to uppercase
ToLower()-Converts to lowercase
Clear()-Sets value to empty string
IsEmpty()-Returns true if string is null or empty

Usage Example

[SerializeField] private StringVariable playerName;

private void SetPlayerName(string name)
{
playerName.SetValue(name.Trim());
}

private void AddTitle(string title)
{
playerName.Prepend($"{title} ");
}

Unity Type Variables

Vector2Variable

2D vector variable with vector operations and constraints.

[CreateAssetMenu(menuName = "SoapKit/Variables/Vector2 Variable")]
public class Vector2Variable : BaseVariable<Vector2>

Properties

PropertyTypeDescription
MaxMagnitudefloatMaximum vector magnitude
HasMagnitudeLimitboolWhether magnitude constraint is active

Specialized Methods

MethodParametersDescription
Add(Vector2 vector)Vector2 vectorVector addition
Subtract(Vector2 vector)Vector2 vectorVector subtraction
Scale(float factor)float factorScales vector by factor
Normalize()-Normalizes the vector
ClampMagnitude()-Clamps to max magnitude
Lerp(Vector2 target, float t)Vector2 target, float tLinear interpolation
MoveTowards(Vector2 target, float maxDistance)Vector2 target, float maxDistanceMoves towards target
SetX(float x)float xSets X component
SetY(float y)float ySets Y component

Vector3Variable

3D vector variable with comprehensive vector operations.

[CreateAssetMenu(menuName = "SoapKit/Variables/Vector3 Variable")]
public class Vector3Variable : BaseVariable<Vector3>

Properties

PropertyTypeDescription
MaxMagnitudefloatMaximum vector magnitude
HasMagnitudeLimitboolWhether magnitude constraint is active

Specialized Methods

MethodParametersDescription
Add(Vector3 vector)Vector3 vectorVector addition
Subtract(Vector3 vector)Vector3 vectorVector subtraction
Scale(float factor)float factorScales vector uniformly
Scale(Vector3 scale)Vector3 scaleScales vector per-component
Normalize()-Normalizes the vector
ClampMagnitude()-Clamps to max magnitude
Lerp(Vector3 target, float t)Vector3 target, float tLinear interpolation
Slerp(Vector3 target, float t)Vector3 target, float tSpherical interpolation
MoveTowards(Vector3 target, float maxDistance)Vector3 target, float maxDistanceMoves towards target
SetX(float x)float xSets X component
SetY(float y)float ySets Y component
SetZ(float z)float zSets Z component

ColorVariable

Color variable with color manipulation operations.

[CreateAssetMenu(menuName = "SoapKit/Variables/Color Variable")]
public class ColorVariable : BaseVariable<Color>

Specialized Methods

MethodParametersDescription
SetRed(float r)float rSets red component (0-1)
SetGreen(float g)float gSets green component (0-1)
SetBlue(float b)float bSets blue component (0-1)
SetAlpha(float a)float aSets alpha component (0-1)
Lerp(Color target, float t)Color target, float tColor interpolation
ToGrayscale()-Converts to grayscale
Invert()-Inverts RGB components
Brighten(float amount)float amountIncreases brightness
Darken(float amount)float amountDecreases brightness

GameObjectVariable

GameObject reference variable with component access and validation.

[CreateAssetMenu(menuName = "SoapKit/Variables/GameObject Variable")]
public class GameObjectVariable : BaseVariable<GameObject>

Properties

PropertyTypeDescription
RequiredTagstringRequired tag for validation
ValidateTagboolWhether to enforce tag validation

Specialized Methods

MethodParametersDescription
GetComponent<T>()-Gets component of type T
HasComponent<T>()-Checks if component exists
IsActive()-Returns active state
SetActive(bool active)bool activeSets active state
DestroyGameObject()-Destroys the GameObject
ValidateTagRequirement()-Checks tag validation

TransformVariable

Transform reference variable with position and rotation access.

[CreateAssetMenu(menuName = "SoapKit/Variables/Transform Variable")]
public class TransformVariable : BaseVariable<Transform>

Specialized Methods

MethodParametersDescription
GetPosition()-Returns world position
SetPosition(Vector3 position)Vector3 positionSets world position
GetLocalPosition()-Returns local position
SetLocalPosition(Vector3 position)Vector3 positionSets local position
GetRotation()-Returns world rotation
SetRotation(Quaternion rotation)Quaternion rotationSets world rotation
GetParent()-Returns parent Transform
GetChildCount()-Returns number of children

Best Practices

Variable Creation

  1. Use descriptive names for ScriptableObject assets
  2. Organize variables in folders by type or system
  3. Set appropriate constraints during asset creation
  4. Add tooltips and descriptions for clarity

Value Management

  1. Always check for null references before use
  2. Use SetValue() method instead of direct Value assignment
  3. Subscribe to OnValueChanged for reactive behavior
  4. Unsubscribe from events in OnDisable/OnDestroy

Performance Optimization

  1. Disable change notifications during bulk operations
  2. Use appropriate variable types (Int vs Float)
  3. Implement custom equality comparison for complex types
  4. Monitor listener counts in debug tools

Debugging

  1. Use SoapKit Debug Window for real-time monitoring
  2. Enable event history for development builds
  3. Use context menu actions for testing
  4. Implement validation in custom variables

See Also