- Home /
Add Weapon
I need help attaching a weapon to a firstPersonController.. How do you attach a weapon to a FirstPersonController?
You can make it a child object of the controller so it will always follow the controller around, happy new year!
Child it to the controller's camera though, NOT the controller itself ; otherwise you'll be back asking how to get your weapon to quit moving goofy when you make your player look around.
Answer by aldonaletto · Dec 31, 2011 at 06:02 PM
The best way is to child all weapons to the camera, like @Lo0NuhtiK said - this way every weapon will point to the direction you're looking at. Set each weapon's position/rotation in the Editor, and attach this script to the camera to select the weapon and fire:
function Start(){ SelectWeapon(0); // select weapon 0 at Start; // if you want to have no weapons initially, use SelectWeapon(-1) }
function SelectWeapon(num: int){ for (var i=0; i < transform.childCount; i++){ // activate the weapon index "num", and deactivates all the others: transform.GetChild(i).gameObject.SetActiveRecursively(i == num); } }
function Update(){ // repeat the code below for each weapon: if (Input.GetKeyDown("1")) SelectWeapon(0); if (Input.GetKeyDown("2")) SelectWeapon(1); if (Input.GetKeyDown("3")) SelectWeapon(2); // this is the fire code: if (Input.GetButtonDown("Fire1")){ transform.BroadcastMessage("Fire"); } } HOW IT WORKS: when you press keys 1, 2, 3 etc. the function SelectWeapon activates only the selected weapon and deactivates all the others. If you pass a non-existent index to SelectWeapon, all weapons are deactivated. When you press the button Fire1 (left mouse button by default), the function Fire will be called in the active weapon, thus you must write a Fire function in each weapon to effectively shoot - something like this (script suitable for fast bullet weapons like rifles, guns etc. - must be attached to the weapon):
var shotSound: AudioClip; // drag the shot sound here at the Inspector
function Fire(){ var hit: RaycastHit; if (Physics.Raycast(transform.position, transform.direction, hit)){ if (shotSound) audio.PlayOneShot(shotSound);
hit.transform.SendMessage("ApplyDamage", 5, SendMessageOptions.DontRequireReceiver) } } This approach is used in the First Person Tutorial - download the Completed version and see how they set up the 2 weapons.
Your answer
Follow this Question
Related Questions
Making a Game like 'Kitty Cannon'? 1 Answer
Textfield in javascript, make unity read it on pressing enter 1 Answer
How to update unity web player 0 Answers
How to check my Game System Requirements? 2 Answers
Question about network items 0 Answers