I’m experiencing a strange issue with my AI character prefab. When I place it directly in the scene using the Unity editor, it operates perfectly. However, when I instantiate the same prefab at runtime using code, the AI starts acting unexpectedly.
The core issue lies with the ThirdPersonCharacter script attached to my AI. Instead of transitioning to the walking animation when it moves towards a target, the character continues to perform the idle animation and slides along the ground. I’ve tracked the problem back to the CheckGroundStatus function, particularly this line:
animatorController.applyRootMotion = false;
It seems that the character isn’t registering the ground correctly, which results in the sliding behavior instead of a smooth walking transition. I’m puzzled as to why there’s a difference between the prefab placed in the editor and the one spawned at runtime, as they are identical. Any suggestions on what might be causing this discrepancy?
This happens because of component timing issues. When you instantiate a prefab at runtime, there’s usually a frame delay before everything’s fully initialized. Your CheckGroundStatus function is probably running before the character controller or rigidbody has stabilized, which breaks the behavior. I’ve fixed this by adding a small delay or using a coroutine to enable the AI movement after instantiation. Also, double-check your ground detection layer masks - instantiated prefabs don’t always inherit the layer settings from the editor, which can mess up ground detection.
Root motion breaks with runtime instantiation because the animator needs a frame to sync with the character controller.
I’ve seen this when the animator starts before the character’s grounded. That applyRootMotion = false line you mentioned probably runs while the character’s still “falling” from spawn height.
Try disabling the AI movement script on the prefab, then enable it one frame after instantiation:
GameObject ai = Instantiate(aiPrefab);
ai.GetComponent<YourAIScript>().enabled = false;
StartCoroutine(EnableAINextFrame(ai));
Check if your prefab has the same Y position as the editor version. Runtime spawning sometimes puts characters at weird heights and breaks ground detection.
Also make sure your instantiated prefab keeps the same physics update settings. I’ve had runtime objects default to different FixedUpdate timing, causing animation state to desync from movement.
Had this exact problem last month! The navmesh agent wasn’t fully baked when I instantiated at runtime. Call NavMeshAgent.Warp() right after instantiation - it’ll force the agent onto the navmesh properly. Also check your groundcheck raycast distance. Sometimes prefabs spawn slightly above ground level and the distance is too small to catch it.