Give object velocity based on spawn object rotation?

I have a spawn cube on the gun in my game. The Z axis of the cube is pointing forward away from the gun. I want to instantiate an object at that point with a random rotation (i have this working properly) but i cant figure out how to give the object forward(Z) velocity based on the spawn object and not based on the object spawned. How do i do this? an example script would be great, to help my understanding. Thanks

You should reference the spawn object when giving the initial velocity rather than using the newly spawned object. Something like

var spawnObject:Transform;
var projectile:Transform;

function SpawnProjectile(){
    projectile = Instantiate(....
    projectile.rigidbody.AddForce(spawnObject.forward * 20,ForceMode.Force);

instead of saying

rigidbody.velocity = Vector3(0,0,20);

you should be able to say

rigidbody.velocity = spawnObject.forward * speed;

the important part is the spawnObject.forward, that will return a normalized vector representing the direction that the spawnObject is facing.

though OperationDogBird is right, velocity is not usually set directly, it sounds like in the context you’re using it, i should work.