Why can't I call a function within the same class? (Or: how does unity handle instancing?)
Hi, I'm new to unity and trying to learn but ran into something I don't understand. I'm trying to make a 2d sprite with animations controlled by a state variable. I attached a script to the sprite object and set my outgoing animator transitions to be triggered on the state variable, modified by script on button press. This works, but I wanted one animation to play once and stop, so I added an animation event in the animation to call a function that set the variable back to idle:
const int stateIdle = 0;
const int stateClick = 1;
int _currentAnimationState;
void Start () {
animator = GameObject.Find("computer_dude").GetComponent<Animator>();
}
public void butClose()
{
changeState(stateClick);
}
public void resetAction()
{
changeState(stateIdle);
}
public void changeState(int state)
{
// if (_currentAnimationState == state)
// return;
switch (state)
{
case stateIdle:
animator.SetInteger("state", stateIdle);
break;
case stateClick:
animator.SetInteger("state", stateClick);
break;
}
_currentAnimationState = state;
}
But it doesn't stop - the value of _currentAnimationState seems to sometimes not persist and it interferes with the check on the commented out lines
If I put a break in I can see that: the first time it's called on button press - with value 1, current is 0 - this is correct The end animation calls it with value zero, but the current is still also zero (it just got set to 1?) Press the button again and now its comparing the new value of 1 to the old value of.. 1?
I can only think that its holding two instances of the class - one in the button, one in the sprite? But if so, how to I tell it to use the same instance? It wouldn't let me make it static.
Thanks!
I managed to solve it with a workaround - it was different instances of the script, but I couldn't attach the animation event to the same instance as the main game one, it had to be a script in the sprite, so I just made a seperate script for it and made that script call the function in the main one.
Your answer
Follow this Question
Related Questions
Interchangeable animations in a script? 0 Answers
Movement and Jump with animator 0 Answers
When I run this code Unity crashes(ANIMATOR RELATED) 0 Answers
Errors in script when trying to play animation clips 1 Answer
animator and script issue 0 Answers