- Home /
Animator gets stuck when disabling gameObject
I have a system in which a main character has a bunch of weapons. When you change between them each weapon has a time in which it saves the weapon and animates it as such, then disables the gameobject of that weapons, enables the new one, plays an animation in which it takes it out and then goes into its main loop.
The way I first instantiate the weapons is as follows
foreach (WeaponBase weapon in weaponsList)
{
WeaponBase weaponBase = Instantiate(weapon,transform.position,Quaternion.identity);
weaponBase.gameObject.SetActive(false);
weapons.Add(weaponBase);
}
weapons[0].gameObject.SetActive(false);
where weaponsList is a list the character holds to which you can add prefabs in the inspector.
I have another snipper to try changing between two weapons, as follows
if (Input.GetKeyDown("space"))
{
weapons[0].animator.SetTrigger("Exit");
weapons[0].finishing = true;
changeTimer = 0.05f;
}
if (changeTimer>0)
{
changeTimer-=Time.deltaTime;
}
if (changeTimer<0)
{
changeTimer = 0.0f;
weapons[0].gameObject.SetActive(false);
weapons[1].gameObject.SetActive(true);
weapons[1].Activate();
}
where Activate() is a method that is supposed to play the first animation.
The weapon script has the following
void Start()
{
waitingForCooldown = 0.0f;
player = FindObjectOfType<HeroController>();
animator = gameObject.GetComponent<Animator>();
}
public void Activate()
{
animator.SetTrigger("Start");
waitingForCooldown = 0.1f;
starting = true;
}
this already gave an unasigned reference, complaining that animator was not set to anything even though it's supposed to be set in the Start() method. I had to run another animator = gameObject.GetComponent(); to fix that in the Activate() method.
Lastly, the update method of the weapon has this
if (waitingForCooldown > 0)
{
waitingForCooldown -= Time.deltaTime;
if (waitingForCooldown < 0)
{
waitingForCooldown = 0.0f;
if (starting)
{
starting = false;
animator.SetTrigger("Finished_in");
}
}
}
else if ((Input.GetMouseButton(0) && automatic == true) || Input.GetMouseButtonDown(0))
{
//Shoot
if (hasCooldown)
{
waitingForCooldown = cooldown;
}
if (hasRecoil)
{
//Recoil
}
//Shoot
}
the if (starting) part is supposed to check whether the waitingforcooldown set in activate is less than 0, in which case set a trigger to finish the animation in which it takes out the weapon. However, what happens is that those three lines are never called and the animation is stuck in a loop until i click the mouse (so the next if is getting executed).
I thought this was very weird and had something to do with disabling the gameObjects as soon as I instantiated them, so I tried, instead of doing so, to leave them enabled from start and then put an active bool so that the update method only executes if active is true, and active=false would disable the sprite renderer, this now works exactly as I intended, although I find it less elegant.
Does anyone see what's happening here?
Thanks!