Random.range script is not working, please help!

Can anyone tell me why this script is not working? The rigidbodies are not moving.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    private float speed;

    void Update ()
    {
        speed = Random.Range (2, 5);
    }

    void Start ()
    {
        GetComponent<Rigidbody> ().velocity = transform.right * -speed;
    }
}

Okay, first of all, just comment out the ‘speed = Random’ part in Update().
Put the speed code you had just before the GetComponent and try again.
Please do that part first to make sure there aren’t any bugs or anything. It should show you object moving at one speed.

Then, if that works, I’d suggest you make a Coroutine or InvokeRepeating to reset the speed at various time intervals.
It makes no sense to update the speed once per frame, in my opinion :slight_smile:

I’m not sure what you are talking about, Could you give an example please?

Also, I need the speed to be updated every time a new instance of the gameobject with movement.cs on it is created

Okay, it’s not complicated. Here we go.
just delete your Update() method - just get rid of it for now.

At the top of your script where you have:

private float speed;
// add these lines
Rigidbody rb;
void Awake() {
  rb = GetComponent<Rigidbody>();
 }

Then, in Start() do this:

speed = Random.Range (2, 5);
rb.velocity = transform.right * -speed;

Then tell me if that’s working and we’ll move on from there.

Yup this works. Thanks :slight_smile:

Okay, glad to hear it. Is that everything - you don’t need the speed to change over time or anything? :slight_smile:

Nope. I only need a random random velocity when the gameobject is spawned.

Okay, cool :slight_smile: Enjoy your game.