why this code doesnt rewind the time ?
hey im pretty new to unity and im trying to make as you can understand from the title to get the time moving backward. i made the following code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class rewindtimes : MonoBehaviour { float x; float y; float z; public Transform trans; Stack stk; Vector3 vec3; Vector3 output; void Start() { trans = GetComponent(); } void FixedUpdate() {
if (Input.GetKey ("r")) {
output = stk.Pop ();
trans.position = output;
}
else {
x = trans.position.x;
y = trans.position.y;
z = trans.position.z;
vec3 = new Vector3 (x,y,z);
stk.Push(vec3);
}
}
} when i hit the r button nothing happens why?
Comment
Best Answer
Answer by Hellium · May 20, 2018 at 12:32 PM
The following (simplified) script works perfectly fine:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimeRewinder : MonoBehaviour
{
[SerializeField]
private Transform target ; // Drag & drop the target in the inspector
private Stack<Vector3> positions;
void Start()
{
positions = new Stack<Vector3>();
if( target == null )
target = transform ;
}
void Update()
{
if ( Input.GetKey ( KeyCode.R ) )
{
if( positions.Count > 0 )
target.position = positions.Pop ();
}
else
{
positions.Push(target.position);
}
}
}
If the code has worked for you, don't forget to accept the answer (by clicking on the check mark at the left side of the answer)