Hi, I’m new to Unity and am making a point-and-click type movement rpg. I’ve tried to start and stop a walking animation with the movement of the character, but have not been able to do so successfully. Here is my code for player behavior:
using UnityEngine;
using UnityEngine.AI;
public class PlayerBehavior : MonoBehaviour
{
NavMeshAgent agent;
Animator anim;
private Vector3 animDest;
void Start()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
anim.enabled = false;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
{
agent.destination = hit.point;
}
}
if (transform.position != agent.destination)
{
anim.enabled = true;
}
else
{
anim.enabled = false;
}
}
}
Not sure if this helps or not, but to start and stop my animations in my game, i added parameters to the animation contoller thing, which are bools. I then did
object.GetComponent<Animator>().SetBool("anim",truefalse)
If you know how to set the parameters, then set them and apply them to the transitions. I recommend setting the parameters in the script while you are walking to that destination, in the same if statement, and at the end of the walk you disable the walk anim
Heres the modified code. It should work if you set the idle anim parameter to “Idle” and set the walk anim parameter to “Walk”. Hope this helps
` using UnityEngine;
using UnityEngine.AI;
public class PlayerBehavior : MonoBehaviour
{
NavMeshAgent agent;
Animator anim;
private Vector3 animDest;
void Start()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
anim.SetBool("Walk", false)
anim.SetBool("Idle", true)
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
{
agent.destination = hit.point;
}
}
if (transform.position != agent.destination)
{
anim.SetBool("Walk", true)
anim.SetBool("Idle", false)
}
else
{
anim.SetBool("Walk", false)
anim.SetBool("Idle", true)
}
}
}`
@cham3l3on3
@cham3l3on3 Instead of
anim.enabled = false;
You can create a bool in the ‘Parameters’ section of the animator component and call it ‘IsMoving’.
Then,
if (transform.position != agent.destination)
{
anim.SetBool("IsMoving", true);
}
else
{
anim.SetBool("IsMoving", false);
}
You also have to create an ‘Idle’ animation and link it up with the ‘Moving’ animation