How to synrchonize two floats from different scripts?

Hey,

I am working on a game, where you have a car as a player and you move left and right to avoid collision with some obsticals coming your way. The BG and the obsticals are moving to create the illusion, that the player is moving, but in reality, the player isnt moving.

This is the code for both:

BG:

__ public float speed = 2.0f; __

// Update is called once per frame
void Update()
{
    float y = transform.position.y;

    y = transform.position.y - speed * Time.deltaTime;

    transform.position = new UnityEngine.Vector2(transform.position.x, y);

    if(transform.position.y <= -10f)
    {
        transform.position = new UnityEngine.Vector2(0, 9.94f);
    }

    speed += 0.1f * Time.deltaTime;
    
}

Obsticals:

__ public float obsticalspeed = 2.0f; __

private void Start()
{
    
}

void Update()
{
    
    
    
    float y = transform.position.y;

    y = transform.position.y - obsticalspeed * Time.deltaTime;

    transform.position = new UnityEngine.Vector2(transform.position.x, y);

    obsticalspeed += 0.1f * Time.deltaTime;
    

}

So my Main Problem is, that the BG is faster then the obsticals which are spawning, because the start to gain speed as soon as they are spwaned and not having the same speed as the BGs which are just teleporting to the positions when they are out of the screen.

So i want to synronize both floats which eachother, so that the obsticals will have the same speed as the BGs when they are spwaning!

Any Ideas?

You can try to extract this velocity to another script, that does the update for both cases. Then you can just add this to a single object inside your Scene and get the value directly from the SpeedController.

public class SpeedController : MonoBehavior
{
    public float speed;

    private void Awake() 
    {
        speed = 2.0f;
    }

    private void Update()
    {
        speed += 0.1 * Time.deltaTime;
    }
}

With this you could apply this script to a GameObject in your scene and get the reference to it in your scripts, like this:

// Your obstacles script
{
    ...
    public SpeedController speedController;

    private Update() 
    {
        float y = transform.position.y;
        y = transform.position.y - speedController.speed * Time.deltaTime;
        transform.position = new UnityEngine.Vector2(transform.position.x, y);
    }
}

You have to remind to set the SpeedController on the Inspector by dragging and dropping the GameObject with this script.