Search code examples
c#unity-game-engineunity3d-mirror

Animation not playing correctly unless field is changed in inspector


I have created a animator to animate my character holding a weapon. The problem is that the animator does not animate the weapon, but it animates everything else. I thought this was because it was being spawned in and didn't exist yet but I tried using Invoke() and IEnumerable to run the method that plays the animation later, but that didn't change anything. I am very frustrated and do not understand what I am doing wrong.

Something that is wierd is that if I change any of the Animator properties in the Inspector panel, the animation fixes itself (demonstration: https://i.sstatic.net/mmtPB.jpg)

How my animator looks like: https://i.sstatic.net/ZJWAM.jpg (I have verified and the animation is playing)

My object hierarchy: https://i.sstatic.net/vQeZc.jpg (The object that doesn't animate is "Stick", the other objects that do animate are "ref_right_hand_grip" and "ref_left_hand_grip")

Code that sets the animation:

GameObject newHolding = null;
if (holding && holding.name != item.data.name)
{
    DestroyImmediate(holding);
    newHolding = Instantiate(item.data.holdingItem, holdingParent.transform, false);
    newHolding.name = item.data.name;
    holding = newHolding;
}
else if (!holding)
{

    newHolding = Instantiate(item.data.holdingItem, holdingParent.transform, false);
    newHolding.name = item.data.name;
    holding = newHolding;
}
anim.Play("equip_" + item.data.id);

EDIT: I did further investigation. The issue is probably something to do with the object being created. When I created the object beforehand and simply enable/disable it when the player selects it, the animation plays correctly. I should mention I am using Mirror (Networking)


Solution

  • The way I fixed this is by encapsulating the object that was instantiated (stick) in another GameObject, and animed the encapsulator instead.