- Home /
How to move GameObject after 1 second c#
Hi guys, I actually have this situation where there is a cube, when I place it a structure comes up from the ground using Vector3.Lerp and stops. I want to make the structure to start after 1 second, but I'm having problems since with this script it only moves 1 frame (i think it's because ienumerator dosn't update or stuff. I read on other answers that I should use a while loop but while trying I freezed Unity once and if I add break; to avoid freezes the gameobject only moves by 1 frame. Any ideas? Here's the script in c# (thank you in advance guys!):
using System.Collections;
public class WinScript : MonoBehaviour {
public GameObject wall;
private Vector3 startPos;
private Vector3 endPos;
private float distance = 16.82f;
private float lerpTime = 6;
private float currentLerpTime = 0;
private bool triggerEnter = false;
// Use this for initialization
void Start () {
startPos = wall.transform.position;
endPos = wall.transform.position + Vector3.up * distance;
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Cube")
{
triggerEnter = true;
StartCoroutine ("Portal");
}
}
// Update is called once per frame
IEnumerator Portal () {
if (triggerEnter == true) {
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime)
{
currentLerpTime = lerpTime;
}
float Perc = currentLerpTime / lerpTime;
yield return new WaitForSeconds (1);
while (true) {
wall.transform.position = Vector3.Lerp (startPos, endPos, Perc);
break;
}
}
}
}
Answer by iabulko · Oct 04, 2016 at 06:37 AM
When you want to make coroutine work like Update() all you need is to just add a
yield return new WaitForEndOfFrame();
and there is no need for break then (although is should break at some point. Try this:
while (Perc <= 1) {
wall.transform.position = Vector3.Lerp (startPos, endPos, Perc);
yield return new WaitForEndOfFrame();
}
PS: C# convention is to name variables startiing from small letter, so you should name Perc variable perc.
Answer by doublemax · Oct 04, 2016 at 06:41 AM
I think the Coroutine should look like this:
if (triggerEnter == true)
{
yield return new WaitForSeconds (1);
float elapsed = 0.0f;
while ( elapsed < lerpTime ) {
wall.transform.position = Vector3.Lerp (startPos, endPos, elapsed / lerpTime);
yield return null;
}
wall.transform.position = endPos;
}
Untested, but you should get the idea.
Your answer
Follow this Question
Related Questions
Vector3.Lerp snaps when called too frequently. 2 Answers
Move player to mouse position never go to exact position 0 Answers
Problem with while loop in Coroutine 2 Answers
Problems with While Loops Only repeating Once 1 Answer
IEnumerator in Update 2 Answers