Hi everyone,
My question is maybe a bit complex, but i’ll try to give all the details that I can.
In my game, I made a system for instantiating prefabs that will be used as player weapon.
First, how I manage my prefab :
The player walks in the trigger zone of a weapon that is on ground, he picks it up, and the weapon goes in player hands, by instantiating a prefab that is spawned inside hierarchy of player model.
Second, I need to manage the box collider of the weapon during animation of player.
The main problem is that box collider is always on, when I walk towards an enemy, the weapon triggers a damage on him without attacking. So, I wanted to disable box collider when the player is not attacking (idle animation, walking, etc.)
So I used keyframes on player animation, but it goes weird since I’m trying to change box collider of an instantiated prefab.
I think that property showing inside animation window is the one of the previous runtime instantiated prefab, when I reload the party, It cannot works as it will instantiate another prefab…
What is the solution here?
Thanks!
All right, I found a way when looking for info on Unity docs.
I attached a script on the prefab supposed to spawn in the player hands. Here it is :
public Animator playerAnimator;
private BoxCollider2D weaponBoxCol; //I declare the collider of the weapon itself
void Start()
{
playerAnimator = GameObject.FindGameObjectWithTag("Player").GetComponent<Animator>(); //I'm getting the Player Animator
weaponBoxCol = GetComponent<BoxCollider2D>(); //I get the collider of the weapon
weaponBoxCol.enabled = false; //The collider starts disabled
}
void Update()
{
if (playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("player_weapon")) //I check if the animation played is the one when player swings weapon
{
if (playerAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0 && playerAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime <= 0.5) //If the animation is between the beginning and middle of it, the collider stays disabled
{
weaponBoxCol.enabled = false;
}
else if (playerAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime > 0.5) //If the animation is at middle of it, the collider enables
{
weaponBoxCol.enabled = true;
}
else if (playerAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime == 0) //If the animation didn't begin, the collider stays disabled
{
weaponBoxCol.enabled = false;
}
}
if (playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("Player_walk") || playerAnimator.GetCurrentAnimatorStateInfo(0).IsName("Player")) //If the animation of walking and idling are played, the collider stays disabled
{
weaponBoxCol.enabled = false;
}
}
It’s maybe not optimized, but it works. The Animator.GetCurrentAnimatorStateInfo
was the key!