Multiple Fire on different launcher GameObjects

Currently working on a tank simulator and I am having issues with the scripting of my launchers. I have two GameObjects that act as instantiation points (where the projectiles will be fired) one is for a machine gun the other for the main cannon. The code I have works if I split it up into two different scripts and attach them directly to the launchers G.O’s themselves, but I feel thats a little ridiculous and not efficient. Currently I am stuck with this code. Any ideas how to remedy the situation?

Thanks!

-Keith-

public Rigidbody machineGunPrefab;
public Rigidbody mainCannonPrefab;
public GameObject machineGunLauncher;
public GameObject cannonLauncher;

void Update () 
{

if(Input.GetMouseButtonDown(0)) //if you left click on the mouse...
{       
Debug.Log("Machine Gun");
Rigidbody clone;
        clone = Instantiate(machineGunPrefab, machineGunLauncher, machineGunLauncher) as Rigidbody;
        clone.velocity = transform.TransformDirection(Vector3.forward * 10);
} 

if(Input.GetMouseButtonDown(1)) //if you right click on the mouse...
{      
Debug.Log ("Main Cannon");
        Rigidbody clone;
        clone = Instantiate(mainCannonPrefab, cannonLauncher, cannonLauncher) as Rigidbody;
        clone.velocity = transform.TransformDirection(Vector3.forward * 500);
    }

}
    }

[2135-screen+shot+2012-07-24+at+2.24.10+pm.png|2135]

  • first
transform.TransformDirection(Vector3.forward * 10)
is same as
transform.forward * 10
  • second you need not parent transform’s forward direction, but a cannon’s, so use machineGunLauncher or cannonLauncher instead of ‘transform’ in velocity calculation line
  • third as i remember Instantiate method needs obj, position and rotation as parameters, so you should use
clone = Instantiate(mainCannonPrefab, cannonLauncher.position, cannonLauncher.rotation) as Rigidbody;

finally this should looks like

Rigidbody clone;
clone = Instantiate(machineGunPrefab, machineGunLauncher.position, machineGunLauncher.rotation) as Rigidbody;
clone.velocity = machineGunLauncher.transform.forward * 10f;