Reputation: 2742
I have a series of objects that are moving in a direction with a given speed (children) and another object that changes the speed of these objects (controller).
If the controller adjusts the speed of all children part way through the children moving themselves, the spacing becomes uneven as some have been moved with the old speed and some have been moved with the new speed.
I have been able to solve this issue by using the Edit->Project Settings->Script Execution Order to make the controller execute before the children, but this doesn't seem ideal. Is there a better way to solve this problem?
Below are the very simple child and controller scripts.
// Child
public class MoveVertically
: MonoBehaviour
{
public float Speed;
void Update ()
{
transform.Translate (Vector3.down * Time.deltaTime * Speed);
}
}
// Controller
public class MoveChildrenVertically
: MonoBehaviour
{
public float Speed;
MoveVertically[] children;
void Start()
{
children = GetComponentsInChildren<MoveVertically> ();
}
void Update()
{
foreach (var symbol in symbols)
{
symbol.Speed = Speed;
}
}
}
Upvotes: 0
Views: 407
Reputation: 10721
Get the controller to move all the items:
public class MoveVertically
: MonoBehaviour
{
public void Move (float speed)
{
transform.Translate (speed);
}
}
// Controller
public class MoveChildrenVertically
: MonoBehaviour
{
public float Speed;
MoveVertically[] children;
void Start()
{
children = GetComponentsInChildren<MoveVertically> ();
}
void Update()
{
Speed = ChangeSpeed(); // if needed
float speed = Vector3.down * Time.deltaTime * Speed;
foreach (var child in children)
{
child.Move(speed);
}
}
}
Double bonus, you don't have to call the change of speed on every child, you pass it in the Move call. Also, you have one less Update per child called.
To understand the benefit of calling child method instead of Update on children:
https://blogs.unity3d.com/2015/12/23/1k-update-calls/
Upvotes: 4