Script not doing anything
i have a simple script that is supposed to apply torque to objects (the characters legs) while the navMeshAgent is moving.But it doesnt do anything, i tried increasing the force, reducing the mass and make the script affect a weightless zero G cube but nothing. And detecting movement is not the issue, even if i set the "moving" bool to true and disable the scripts ability to make it false, it still doesnt work. Im still very new to scripting so i Wonder if someone can help me out. Here is the C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class WalkingScript : MonoBehaviour
{
public float amount = 50;
public NavMeshAgent agent;
public Rigidbody rightLeg;
public Rigidbody leftLeg;
bool moving = false;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update()
{
float velocity = agent.velocity.magnitude;
if (velocity > 0.5)
{
moving = true;
}
else if (velocity < 0.5)
{
moving = false;
}
}
IEnumerator Move()
{
while (moving == true)
{
float up = amount * Time.deltaTime;
float down = -amount * Time.deltaTime;
rightLeg.AddForce(transform.up * up, ForceMode.VelocityChange);
yield return new WaitForSeconds(1);
rightLeg.AddForce(transform.up * down, ForceMode.VelocityChange);
leftLeg.AddForce(transform.up * up, ForceMode.VelocityChange);
yield return new WaitForSeconds(1);
leftLeg.AddForce(transform.up * down, ForceMode.VelocityChange);
}
}
}
thanks in advance...
Answer by SilverSho0t · Aug 23, 2017 at 12:36 PM
I men, your IEnumerator Move() is never executed you need to launch this IEnumerator in your function Start () with :
StartCoroutine (Move ());
Doc link
and to don't need to re-run Move() you should modify with this :
IEnumerator Move()
{
while (true)
{
if (moving)
{
float up = amount * Time.deltaTime;
float down = -amount * Time.deltaTime;
rightLeg.AddForce(transform.up * up, ForceMode.VelocityChange);
yield return new WaitForSeconds(1);
rightLeg.AddForce(transform.up * down, ForceMode.VelocityChange);
leftLeg.AddForce(transform.up * up, ForceMode.VelocityChange);
yield return new WaitForSeconds(1);
leftLeg.AddForce(transform.up * down, ForceMode.VelocityChange);
}
yield return new WaitForEndOfFrame();
}
}
Another thing, you don't need to use Time.deltaTime here.
I hope I help, Sean.
Your answer
Follow this Question
Related Questions
FormatException: Input string was not in the correct format 0 Answers
Dodgeroll script crashing game 0 Answers
Errors With Game Over Script 1 Answer
Need help making a stamina bar. 0 Answers
My coroutine script isn't working, it has no errors 0 Answers