I have an empty game object on my Player object called "retreat"located (0,0-10) behind my Player. This holds the Transform data so the Player Object will know where to move to when the retreat command is executed.
I have a temporary Transform variable called “temp” that is supposed to take a snapshot of the location of the “retreat” empty and feed that into my Movement Coroutine. I have a condition that if the command is given, the “temp” variable gabs the current Transform data of the “retreat” object. This is on a GetKeyDown which should only fire once before beginning the Coroutine.
The issue I’m having is the “temp” variable is behaving as if it is the “retreat” game object and perpetually chases the empty which is always be -10 away creating an infinite loop. Why isn’t the target.position staying the value of the “retreat” empty when the GetKeyDown is triggered?
Here’s the C# code:
using UnityEngine;
using System.Collections;
public class CombatController : MonoBehaviour {
public float smoothing = 1f;
public Transform meleeRange;//The position of an empty on the enemy's object
public Transform self;//The position of the player's object
public Transform retreat;
void Update ()
{
if (Input.GetKeyDown (KeyCode.W)) {
StartCoroutine (Movement (meleeRange));
}
if (Input.GetKeyDown (KeyCode.S)) {
Transform temp = retreat;
Debug.Log ("Position: :" +temp.position);
StartCoroutine (Movement (temp));
}
}
IEnumerator Movement (Transform target)
{
while(Vector3.Distance(transform.position, target.position) > 0.1f)
{
transform.position = Vector3.Lerp(transform.position, target.position, smoothing * Time.deltaTime);
Debug.Log ("Position = " +target.position);
yield return null;
}
print("Reached the target.");
}
}