Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411423 Posts in 69363 Topics- by 58416 Members - Latest Member: JamesAGreen

April 19, 2024, 05:46:21 AM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)Unity Trick : Start the animation at a random frame
Pages: [1]
Print
Author Topic: Unity Trick : Start the animation at a random frame  (Read 14817 times)
bombjack
Level 3
***

That's me :)


View Profile WWW
« on: August 08, 2015, 09:54:26 AM »

When you have several identical animated sprites in your scene, they all start at the same frame.
I wanted to have them start at random frames
I googled a lot about this subject without finding any working and clever solution.

So here is the simple solution I found:

Animator anim = GetComponent<Animator>();
AnimatorStateInfo state = anim.GetCurrentAnimatorStateInfo(0);//could replace 0 by any other animation layer index
anim.Play(state.fullPathHash, -1, Random.Range(0f, 1f));


Here is a downloadable script that you can just drop on an animated GameObject:
RandomStartTime.cs

I hope this will be useful to someone else.
Logged

diegzumillo
Level 10
*****


This avatar is so old I still have a some hair


View Profile WWW
« Reply #1 on: August 16, 2015, 08:00:12 PM »

Thanks for that. I remember trying to do that once but I don't remember how I solved it.
Logged

26PM
Level 1
*



View Profile WWW
« Reply #2 on: February 21, 2017, 05:00:11 AM »

THANK YOU! This works like a charm! Toast Right
Logged

“If you look for beauty, you will find it.”
oahda
Level 10
*****



View Profile
« Reply #3 on: February 22, 2017, 12:10:40 AM »

Semi-related thing that I had to do yesterday which may be obvious to some, but for reference in case it helps anybody:

I already had a working state machine (mecanim) integrated with the code and everything that I didn't want to modify, but then changes were made to design by the artist, who wanted to play a different animation in one of the states depending on some variable. Solution was to replace the old state (just an animation clip) with a blend tree, so that I could retain that one state, with the same transition arrows, but have it select one of five different animations depending on the blend value (which I modified to go between whole integers instead of 0-1), which was filled in by the variable in question. Hand Thumbs Up Right
Logged

Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic