- Home /
The question is answered, right answer was accepted
Translating an Array of Transforms
Hi there! I have been refraining from asking this question for a long time, but I cannot find a similar case online. So here goes.
I have an array of GameObjects and I am interested in translating them all at the same time. To do this, my approach was to loop through the array, toggle a bool in the GO to true, and use the GO's update method to perform the translation. This works when the GO's Update method looks like this:
void Update()
{
if(moveThis == true)
{
transform.Translate(0,0,0.01f);
}
}
This works fine! But when I add additional logic to limit the translation such as this:
void Update()
{
if(moveThis == true)
{
float x = 0f;
while (x < 5f)
{
transform.Translate(0,0,0.01f);
x += 0.04f;
}
moveThis = false;
}
}
All of the objects teleport to their destination. I have tried this with lerp, translate, and transform.position += new Vector3(x,y,z), but they all give this teleporting behaviour. Any insight into this would be greatly appreciated! Thanks and have a great day, cheers!
They still teleport in the second example because even with a while loop in there the Update() method will still complete in one frame. You need to find a way to only move a bit each frame of Update(). One way could be to have each gameobject have a targetDestination field so that you can then lerp from your current position to your target. Then, if you want, ins$$anonymous$$d of sending just a bool saying to move, you can send a destination to move to.
Answer by bpaynom · Feb 15, 2019 at 09:51 PM
According to your code, what I guess you want to do is
float x = 0f;
void Update()
{
if(moveThis == true)
{
if (x < 5f)
{
transform.Translate(0,0,0.01f);
x += 0.04f;
}else
moveThis = false;
}
}
Wow, thanks so much! That did the trick and I see now why it wasn't working. Thank you :)
Follow this Question
Related Questions
Making a smooth camera translation and rotation, C# 1 Answer
Move Objects Relative in Viewport 2 Answers
Language/translation connector to Unity - will it be useful? 0 Answers
Create mesh array from content inside FBX 1 Answer
Saving a variable from an editor script into something like a gamemanager script? 0 Answers