use Update instead of Coroutines
I have a Prefab that gets instantiated everytime a ray (casted by a touch input) hit a gameobject that's in the layer mask of the ray, that prefab has to move from the position (Screen.width / 2, 0) to (Screen.width / 2, Screen.Height / 2). Originally I made it move by using a coroutine started at Start method, but after I read this https://unity3d.com/learn/tutorials/topics/performance-optimization/optimizing-scripts-unity-games?playlist=44069 I got that it would be better not to use too many coroutines to avoid GC issue. And that is my case because I start a new coroutine for every prefab instantiated. This is the code I used inside the coroutine to make prefab move:
var currentPos = transform.localPosition;
var t = 0f;
while (t < 1) {
t += Time.deltaTime / timeToMove;
transform.position = Vector3.Lerp (currentPos, endPos, t);
yield return null;
}
The question is: How can I use that code in Update function?
Answer by Pengocat · Mar 25, 2017 at 06:38 PM
Something along these lines should do the trick.
public float timeToMove = 2f;
private Vector3 startLerpPos;
private Vector3 endLerpPos;
private float currentLerpTime = -1f;
private float t;
void Update()
{
if (Input.touchCount > 0)
{
BeginLerp(Vector3.one);
}
Lerping();
}
public void BeginLerp(Vector3 destination)
{
startLerpPos = transform.localPosition;
endLerpPos = destination;
currentLerpTime = 0f;
}
private void Lerping()
{
if (currentLerpTime > timeToMove || currentLerpTime < 0f)
{
return;
}
else
{
currentLerpTime += Time.deltaTime;
t = currentLerpTime / timeToMove;
transform.position = Vector3.Lerp(startLerpPos, endLerpPos, t);
}
}
Just keep in mind that you should avoid "premature optimization". Chances are, what you think is slowing things down is actually insignificant compared to other things in your code. Use the profiler to find the worst parts and spend time fixing those first.
The game is actually not slow, I just wanted to be sure I was doing everything fine and optimized, so thanks for your advice about "premature optimization" and for your code, it worked well.
Your answer
Follow this Question
Related Questions
Using Coroutines and Update together 0 Answers
Unity C# Punching Coroutine not completing 0 Answers
Which is more efficient, Update() or a couroutine with while(true)? 1 Answer
garbage collection in between scene changes? 2 Answers
Trying to use coroutines in order to use Mathf.Lerp, Lerp instantly jumps values 0 Answers