How does one instantiate a prefab with velocity?


I’m experimenting with methods and came up with this, but it’s not working entirely as intended.

My code is supposed to instantiate a prefab called “ball” in front of the player. The ball is supposed to already be flying forward when it appears, and it’s supposed to always spawn a set distance from the player.

What happens instead is that the balls appear the proper distance away, but only from where the player first appears. Despite the player moving, the balls spawn in the same place. Also, the balls spawn with no velocity at all, and simply stack on top of eachother.


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

public class LevelManager : MonoBehaviour {

private Player player;
private Vector2 playerPos;

[SerializeField] private GameObject ball;
[SerializeField] private GameObject deathParticle;


void Start () {

    player = FindObjectOfType<Player> ();
    StartCoroutine (summonFlyingObjects(ball, new Vector2(playerPos.x+5,playerPos.y),new Vector2 (50,100),1,25));
}


void Update () {
    Vector2 playerPos = player.transform.position;
}

public void setVelocity(Vector2 vel, GameObject _object){
    Rigidbody2D obRB = _object.GetComponent<Rigidbody2D>();
    if (obRB != null) {
        Vector2 obRBVel = obRB.velocity;
        obRBVel = vel;
    }
}


public IEnumerator summonFlyingObjects(GameObject _object,Vector2 coords, Vector2 velocity,float summonTime, int howMany){
    for (int i = 0; i <= howMany; i++){
        if (_object.GetComponent<Rigidbody2D> ()) {
            GameObject newOb = Instantiate (_object, coords, _object.transform.rotation);
            setVelocity(velocity,newOb);
        }
        yield return new WaitForSeconds (summonTime);
    }
}

}

What is it that I’m missing here?

EDIT: I’ve solved the issue with the velocity of the object, so the balls do spawn flying now. However, they’re still spawning in an awkward, seemingly nonsensical place, and the position where they spawn still does not change based on where the player is standing.

The velocity fix was just changing the setVelocity method to call for an RB2D rather than a game object. The summonFlyingObjects method was modified accordingly by passing in an RB2D to setVelocity of course.

Also, sorry to ask an irrelevant question, but it says for me that this question has 400 followers and has no responses. Is that a bug?

Hello. Did you resolve this problem?

I have found out that it is better to ask questions in the forum.
@CatFisting