- Home /
why I have to anim.getComponent in update() function when I had done in Start () function
Hi , I am trying to make a simple 2D game and I am using Animation State machine for making animations. I am having 4 animation states-
Idle
Walk
Jet
Wait
Layer default state is "Idle"
now I want to make transition from idle--> walk when moving and from walk --> Idle when not moving.
So what I did-
I had made animation parameter as "AnimState"
and set conditions as follows-
-AnimState EQUALS 1 (for transition Idle-->walk)
-AnimState EQUALS 2 (for transition walk-->Idle)
The thing is it is working in one condition and not working in another everything described below-
Case 1-
I had declared "anim" as a variable of type Animation, get its component in start function and then use it in update as described below in simplified version of code.
In this case it's not working.
[code=CSharp]private Animator anim;
void Start()
{
anim=getComponent();
}
void Update()
{
if (movement conditions)
{
movement code....................
..............................................
anim.setInteger("AnimState",1);
}
else(.......)
{
.................
}
}[/code]
case 2-
I had declared "anim" as a variable of type Animation, get its component in start function and then use it in update as described below in simplified version of code.
[code=CSharp]private Animator anim;
void Start()
{
anim=getComponent();
}
void Update()
{
if (movement conditions)
{
movement code....................
..............................................
anim.getComponent().setInteger("AnimState",1); //this is working
}
else(.......)
{
.................
}
}[/code]
this is working.
Answer by DiegoSLTS · Jan 26, 2016 at 03:11 PM
Animator and Animation are different things. If you want to change the state of an animator get the Animator component into an Animator variable, that's the component with the "SetInteger" method you need.
Also, if you want to share code, paste the one you use, don't write it like that. "getComponent" (with a lowercase "g") doesn't exists and you can introduce other errors by doing that.
Answer by milleniu · Jan 26, 2016 at 02:23 PM
Change your Start() void with :
anim = GetComponent<Animator>();
You can read more about GetComponent in the Doc : http://docs.unity3d.com/ScriptReference/Component.GetComponent.html