I’m running into a weird issue with my AI character setup. When I drag the prefab directly into the scene through the Unity editor, everything works perfectly. The character moves around normally and all animations play correctly.
But when I try to instantiate the exact same prefab during gameplay using code, something goes wrong with the character controller. The AI gets stuck in the idle animation loop and won’t transition to walking. I noticed that in the PlayerController script (I’m using Unity’s standard character assets), there’s a problem in the “GroundCheck()” method where this line causes issues:
animatorComponent.applyRootMotion = false;
Instead of playing the walk animation properly, the character just slides across the ground to reach its target position. It seems like the ground detection isn’t working when the prefab is spawned dynamically.
I can’t figure out why the same prefab behaves differently depending on how it gets added to the scene. Any ideas what might be causing this?
I’ve hit this exact problem tons of times. It’s almost always a timing issue with runtime spawned prefabs.
Your GroundCheck is probably running before the colliders get properly set up in the physics system. When you place the prefab directly in the scene, Unity has all that loading time to initialize everything correctly.
Add a small delay before your AI starts moving. Use a coroutine that waits a frame or two:
StartCoroutine(DelayedStart());
private IEnumerator DelayedStart()
{
yield return new WaitForFixedUpdate();
// Now start your AI movement
}
Also check if your ground detection distance is too small. I bump up the raycast distance a bit for runtime spawned objects since they might spawn slightly above ground.
And don’t call any movement code in Start() or Awake() for spawned prefabs. Move that stuff to after the delay.
Had the same issue with my third person controller. This root motion problem happens because the Animator isn’t properly initialized when you spawn it at runtime. Fix: force the animator to update its state machine before disabling root motion. Right after spawning, call animatorComponent.Update(0f) to tick it once, then set your root motion properties. Also check if your NavMeshAgent has the same settings as the scene version. Sometimes stopping distance or angular speed gets reset during spawning, messing with animation transitions. Pro tip: spawn the prefab slightly above ground - the physics system needs a moment to register collision when objects appear at runtime.
yeah, could be the layer mask. when u spawn at runtime, make sure ur groundcheck raycast is pointing to the correct ground layer. check if the layers of the spawned prefab match with the one u placed directly in the scene.