How can i add simple back and forth movement on the Y-axis to an enemy that has velocity on the X-axis attached to it?

Hello,

I m creating a 2D horizontal side-scroller shooter and I have enemies being spawned, whose rigidbody component is being used to give them a velocity like so:

public class Mover : MonoBehaviour
{
    public float speed;
    public new Rigidbody2D rigidbody;
    public bool random;

    void Start()
    {
        if(random)
        rigidbody.velocity = Random.value* transform.right * speed;
        {
            rigidbody.velocity =  transform.right * speed;
        }
    }
}

How can i have these enemies also move up and down constantly on the the Y-axis while they are moving with a velocity on the X-axis? Everything i have tried seems to interfere with the velocity of the objects. I am basically trying to create a simply behavioral pattern so as to make the targets less easy for the player to aim.

Any ideas?

The problem is that your x velocity is set to transform.right * number which would be the same as new Vector2(number * 1, 0). This means that you set the y velocity to 0. I’m assuming what you did is had another line that said velocity = transform.up * number, bu this sets the x velocity to 0, so whichever of the two lines you had on the bottom would be the one that you would see when you run the game. If you want it to move on the y- axis while moving on the x - axis you’ll have to do something like:

rb.velocity = new Vector2(Xvelocity, Yvelocity);

Try this
transform.position.y += Mathf.Sin (Time.fixedTime * Mathf.PI * frequency) * amplitude;

Where frequency and amplitude are your own values

I have found the solution by following the answer given under this link:
https://gamedev.stackexchange.com/questions/96878/how-to-animate-objects-with-bobbing-up-and-down-motion-in-unity?newreg=ccb2eaf1b725413ca777a68348637990

Here is my updated code:

public class EnemyMover : MonoBehaviour {
    public float speed;
    public new Rigidbody2D rigidbody;
    public bool random;
    float originalY;
 
    public float floatStrength = 1;  

    void Start()
    {
        this.originalY = this.transform.position.y;
        
         if (random) {
              rigidbody.velocity = Random.value * transform.right * speed;
          }else
          {
            rigidbody.velocity = transform.right * speed;
        }

       
    }


    void Update()
    {
        transform.position = new Vector3(transform.position.x,
               originalY + ((float)System.Math.Sin(Time.time) * floatStrength),
               transform.position.z);
    }

}