Lesson 100 +10 XP

Constraints System

Constraints System

Unity's Constraints system allows you to constrain one GameObject's position, rotation, or scale based on one or more source GameObjects. They are commonly used in animation rigs, procedural systems, and complex object hierarchies.

Types of Constraints

ConstraintEffect
Position ConstraintObject follows the position of its sources.
Rotation ConstraintObject copies the rotation of its sources.
Scale ConstraintObject matches the scale of its sources.
Parent ConstraintObject follows a source as if it were its parent.
Aim ConstraintObject always rotates to face its source(s).
Look At ConstraintA simplified version of Aim Constraint.

Adding a Constraint

  1. Select the GameObject you want to constrain.
  2. In the Inspector, click Add Component > Animation > [Constraint Type].
  3. Add source GameObjects to the Sources list.
  4. Click Activate to lock the constraint in. If the object moves, click Zero or Freeze to set the rest offset.

Position Constraint Example

A camera target that stays halfway between two objects:

using UnityEngine;
using UnityEngine.Animations;

public class ConstraintSetup : MonoBehaviour
{
    [SerializeField] private Transform _sourceA;
    [SerializeField] private Transform _sourceB;

    void Start()
    {
        PositionConstraint constraint = GetComponent<PositionConstraint>();

        ConstraintSource srcA = new ConstraintSource { sourceTransform = _sourceA, weight = 0.5f };
        ConstraintSource srcB = new ConstraintSource { sourceTransform = _sourceB, weight = 0.5f };

        constraint.AddSource(srcA);
        constraint.AddSource(srcB);
        constraint.constraintActive = true;
    }
}

Aim Constraint Example

Make a turret always aim at the player:

  1. Add an Aim Constraint to the turret's barrel GameObject.
  2. Set the World Up Type to align the up-axis correctly.
  3. Add the player Transform as a source with weight 1.
  4. Click Activate.

Enabling/Disabling Constraints at Runtime

PositionConstraint pc = GetComponent<PositionConstraint>();
pc.constraintActive = false; // Deactivate
pc.constraintActive = true;  // Reactivate

Constraints vs Parenting

  • Parenting changes the object's actual hierarchy position.
  • Constraints maintain the original hierarchy but drive transforms procedurally.
  • Constraints are more flexible for animation rigs and allow weighted blending between multiple sources.

TL;DR

  • Constraints drive Position, Rotation, Scale, or Aim based on source GameObjects.
  • Multiple sources with different weights allow blending between targets.
  • Use the Activate button after adding sources to lock the constraint offset.
  • Constraints are more flexible than direct parenting for animation rig setups.