0

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;
        }
    }
}

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

2 Comments

That's a great way of doing this
Agree, great way of doing this (great link too!) and totally solved my problem - thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.