Loading lessons...
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
| Constraint | Effect |
|---|---|
| Position Constraint | Object follows the position of its sources. |
| Rotation Constraint | Object copies the rotation of its sources. |
| Scale Constraint | Object matches the scale of its sources. |
| Parent Constraint | Object follows a source as if it were its parent. |
| Aim Constraint | Object always rotates to face its source(s). |
| Look At Constraint | A simplified version of Aim Constraint. |
Adding a Constraint
- Select the GameObject you want to constrain.
- In the Inspector, click Add Component > Animation > [Constraint Type].
- Add source GameObjects to the Sources list.
- 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:
- Add an Aim Constraint to the turret's barrel GameObject.
- Set the World Up Type to align the up-axis correctly.
- Add the player Transform as a source with weight 1.
- 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.