- Home /
Move a Person to a point / Repeat a function called from another script?
So I have 2 scripts set up, one on the monster and one on the player, when the player right clicks on the monster it tells the monster to send the player to start moving towards it. (if you need to know more about those scripts to call the function, see my last question http://answers.unity3d.com/questions/4845/attack-a-target-using-mouse-over/4850#4850)
now the problem is when you right click the monster, it only moves a little bit, and you have to actually spam right click on it to move anywhere. My function to move is:
var speed = 4.0; function AttackMonster(Position) { var targetRotation = Quaternion.LookRotation(Position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
// Move the object forward.
transform.position += transform.forward * speed * Time.deltaTime;
}
is there a way to set it to loop inside that function, so it only loops when its called and until it is a certain distance away from the targets position (that way it doesnt end on top of it)?
Answer by StephanK · Feb 28, 2010 at 11:58 PM
Yes, you can use a Coroutine for this. Add a while-loop around your movement code. At the end of the loop insert:
yield WaitForFixedUpdate();
As breaking condition for the while-loop check if the distance to target is below a certain value. The function will execute until the yield statement and and continue the loop on the next fixedUpdate.
Your answer
![](https://koobas.hobune.stream/wayback/20220612090638im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Can't transform position of an object after a certain point. Help? 0 Answers
Translate Craig Reynolds's steering behaviors 0 Answers
Getting an Objects position once 2 Answers
Why is Input.GetAxisRaw() not returning whole numbers when using a joystick? 1 Answer