So I have a game with 5 scenes, and each have a timer with very similar code to what I’ve put below (I cut out unrelated sections)
So when the character hits a certain number, it plays an animation which changes the way it looks.
When I then change scenes, it reverts back to the original form/start of the animation, and I need to keep it in whatever state I left it in from the previous scene.
I’ve tried playing around with PlayerPrefs, but nothing I do seems to be working, so any advice would be greatly appreciated.
public class Timer : MonoBehaviour
{
public Image timerBar;
public float maxTime = 200f;
float timeLeft;
public Animator animComponent;
public void Update()
{
if (timeLeft > 0)
{
timeLeft -= Time.deltaTime;
timerBar.fillAmount = timeLeft / maxTime;
}
else
{
Time.timeScale = 0;
}
if (timeLeft <= 100)
{
animComponent.SetBool("IsLiving", false);
}
if (timeLeft >= 101)
{
animComponent.SetBool("IsLiving", true);
}
}
}
6 Answers
6
If you don’t need to save it on disk/cloud, then the simplest way would be to use static class and enum:
public enum CharacterState
{
STATE_1,
STATE_2,
STATE_3
}
public static class State
{
public static CharacterState characterState;
}
Then you will write/read your state and apply whatever animation you need at scene start like this:
State.characterState = CharacterState.STATE_2;
CharacterState currentState = State.characterState;
Would this work if the state is not always the same though?
The state is dependent on how much time remains in the timer, so sometimes it will be State1, other times State2
Yeah, of course, you will control your state through this variable based on your logic, e.g. a quick example:
if (timer < 0.1f)
{
State.characterState = CharacterState.STATE_1;
}
else if (timer < 1f)
{
State.characterState = CharacterState.STATE_2;
}
else if (timer < 2f)
{
State.characterState = CharacterState.STATE_3;
}
The state will be preserved until you stop your application.
Thank you, and sorry if this sounds stupid, I’m new to Unity in general, but how exactly would I apply the Animator state into the code?
Very simple, you will have something like this:
public void SetAnimation()
{
switch (State.characterState)
{
case CharacterState.STATE_1:
{
animComponent.SetBool("IsLiving", true);
break;
}
case CharacterState.STATE_2:
{
animComponent.SetBool("IsLiving", false);
break;
}
case CharacterState.STATE_3:
{
animComponent.SetBool("IsDying", true);
break;
}
default:
break;
}
}
I’ve just tried this, and when it switches scenes it does now to change, however it plays the animation to get to the state first, rather than just staying as it was. Is there a way to solve this?
Should the variable name use a different capitalization than the enum type? (e.g. characterState)
– dstearsYep, you're correct! I've edited the naming, thanks :)
– ajlert11