0
\$\begingroup\$
    private void SpeedUpdater()
    {
        if (changeSpeedOnce == false)
        {
            foreach (WaypointsFollower follower in waypointsFollowers)
            {
                if (randomSpeed)
                {
                    follower.speed = Random.Range(minRandomSpeed, maxRandomSpeed);
                }
                else
                {
                    follower.speed = speed;
                }
            }

            changeSpeedOnce = true;
        }
    }

I'm calling SpeedUpdater from inside the Update.

The problem is that if I'm not using the private flag bool changeSpeedOnce it will give each follower speed a random value every frame but I want that when it's random it will give each follower speed only one random speed value that is why I'm using the changeSpeedOnce flag.

but then I can't change the speed in run time when the game is running because changeSpeedOnce is false now.

I'm stuck here. From one side I want to give only one random speed value to each follower but I also want to do it any time in the run time when I'm changing the speed value in the Inspector.

\$\endgroup\$
0
\$\begingroup\$

Don't do this in Update. This is exactly what OnValidate was made for. OnValidate gets called in the editor when the inspector properties are changed by the user, or after deserialization.

You can use the [Delayed] attribute to hold off on calling OnValidate until the user finishes editing a field.

[Delayed]
public float speed;

public bool randomSpeed;

[Delayed]
public float minRandomSpeed;

[Delayed]
public float maxRandomSpeed;

void UpdateSpeeds() {
    foreach (WaypointsFollower follower in waypointsFollowers)
    {
        follower.speed = randomSpeed ? Random.Range(minRandomSpeed, maxRandomSpeed) : speed;  
    }
}

#if UNITY_EDITOR
bool _cachedRandomSpeed;
float _cachedSpeed;

void OnValidate() {
    if ((randomSpeed != _cachedRandomSpeed) || (!randomSpeed && speed != _cachedSpeed)) {
        UpdateSpeeds();
    }
    _cachedRandomSpeed = randomSpeed;
    _cachedSpeed = speed;
}
#endif

void Start() {
    UpdateSpeeds();
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.