- Home /
Why does Unity animator makes calling children's SetActive fail?
I'm working on a gameObject prefab to show animations of getting a yellow star(change from grey to yellow) or losing a yellow star(change from yellow to grey), and it should also support showing only 2 status according to data(show yellow or grey star at the beginning with no animation).
My gameObject structure: ObjectA yellowStarObj(image) greyStarObj(image) testImageObj(image)
OjbectA has a script ClassA, and an animator, with 5 animations called: DoNothing, Hide, Show, Hidden, Shown. "DoNothing" does nothing, and it is the default animation. "Show" set the yellowStarObject to active, grey to inactive, and then change to Shown animation. "Shown" set the yellowStarObject to active, grey to inactive and loops. "Hide" and "Hidden" do the opposite of "Show" and "Shown".
In the script, I have these following code to manually call them and change the object to a start status according to data(shown or hidden in the beginning).
public void Show()
{
animator.enabled = false; // if comment this line out, the two lines of "SetActive" won't work
print("before setActive, yellowStarObj.activeInHierarchy = " + yellowStarObj.activeInHierarchy);
yellowStarObj.SetActive(true);
print("after setActive, yellowStarObj.activeInHierarchy = " + yellowStarObj.activeInHierarchy);
greyStarObj.SetActive(false);
testImageObj.SetActive(true); // this line always works, I think it's because it has nothing to do with the animator
}
public void Hide()
{
animator.enabled = false; // same
print("before setActive, yellowStarObj.activeInHierarchy = " + yellowStarObj.activeInHierarchy);
yellowStarObj.SetActive(false);
print("after setActive, yellowStarObj.activeInHierarchy = " + yellowStarObj.activeInHierarchy);
greyStarObj.SetActive(true);
testImageObj.SetActive(false); // same
}
Please see the comment in the code. Notice the outcome of the printing lines are always show the correct line(with animator enabled). I think it means the two gameObject setActive are working fine, but somehow the animator just changed them back to prefab status. It's very similar to my other designing approaches describe in the following paragraph.
Reason why I don't use a parameter for the animator and use the two animations(hidden/shown) to show the status, or why I don't just call Play("hidden", 0, 0) is it doesn't work. Right after I set the parameter in Start() it got changed by the animator to default. It only works if I set it after at least two frames after the animator completed initialization. The same when I use calling Play
; When called play, the animation got triggered however it then switched to the default animation at the same time(by the animator I guess).
So what should I do to let the animator show the right animation in the beginning? I'm willing to change my design pattern, Thanks!