Spawn prefab only while Player is moving

I am trying to spawn prefabs into my game. But I only want to call the spawn function while my player is actually moving. Below is the code that I am trying to use and when I run the game I get no errors. It seems that the Spawn function just is never getting called.

using UnityEngine;
using System.Collections;

public class SpawnTesting : MonoBehaviour {
	public GameObject[] obj;
	public float spawnMin = 1f;
	public float spawnMax = 2f;
	public float yPos;
	public Rigidbody2D rb;
	
	// Get Rigidbody component of Player
	void Start(){
		if (gameObject.tag == "Player") {
			rb = GetComponent<Rigidbody2D> ();
		}
	//Check if player is moving
		if (rb.velocity.magnitude > 0) {
			Spawn ();
		}
	}
//Spawn prefab
	void Spawn(){
			Vector2 newPosition = new Vector2 (this.transform.position.x, yPos);
			Instantiate (obj [Random.Range (0, obj.GetLength (0))], newPosition, Quaternion.identity);
			Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
	}
	
}

I can get the code working as soon as the game starts but I only want the spawns to happen when my player is actually moving.

Try using FixedUpdate instead of Start:

void FixedUpdate()
{
     //Check if player is moving
     if (rb.velocity.magnitude > 0) {
             Spawn ();
     }
}

If you want to limit too much occurances of this spawn you can create a float value called coolDownTimer and let it stop spawnning for desired time.

Hope it helps!

**EDIT: **

Discard the FixedUpdate approach I didn’t noticed the spawn method implementation.

Try like this:

void Spawn(){

    if (rb.velocity.magnitude > 0) {     
        Vector2 newPosition = new Vector2 (this.transform.position.x, yPos);
        Instantiate (obj [Random.Range (0, obj.GetLength (0))], newPosition, Quaternion.identity);
    }

    Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
}

Thanks for the help. I implemented your code and now nothing spawns into my game until my player starts moving along the x-axis which is what I wanted. But now the problem is that it will spawn in the prefabs with every FixedUpdate which is every 0.2 seconds and ignores the spawnMin and spawnMax values causing Unity to crash because it is now using too much resource.

I see you already have a solution, but not entirely sure it’s exactly what you are after? What happens/should happen when the player stops moving, and then when they start moving again?

I feel it should be more like:

void Update(){
	if (rb.velocity.magnitude > 1)
		Spawn();
}

void Spawn(){
	Vector2 newPosition = new Vector2 (this.transform.position.x, yPos);
	Instantiate (obj [Random.Range (0, obj.GetLength (0))], newPosition, Quaternion.identity);
	Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
}