Pickup Script

i have this script for weapon switching and was thinking couldn’t you make it an OnCollisionEnter to change the weapon so here is what i have.

function Awake() 

{
// Select the first weapon
SelectWeapon(0);
}
function Update()
{
// Did the user press fire?
if (Input.GetKeyDown(“1”))
{
SelectWeapon(0);
}
else if (Input.GetKeyDown(“2”))
{
SelectWeapon(1);
}
}
function SelectWeapon(index : int)
{
for (var i=0;i<transform.childCount;i++)
{
// Activate the selected weapon
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
// Deactivate all other weapons
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}

okay. To select a weapon using OnCollisionEnter use this in the FPS controller and in the same script that has the function SelectWeapon :

function OnTriggerEnter(other : Collider){

    if(other.gameObject.tag == "aColliderThatChangesToWeaponNumber3")
        SelectWeapon(3);  
    if(other.gameObject.tag == "aColliderThatChangesToWeaponNumber2")
        SelectWeapon(2);
    //and so on

}

You can either have different tags like aColliderThatChangesToWeaponNumber0, aColliderThatChangesToWeaponNumber1, aColliderThatChangesToWeaponNumber2 and so on that individually tell the FPS controler to change the weapon.

Or its better that you create one more code that can be applied to every collider that can change the weapon of the FPS controller and this code stores a number like 0,1,2 and it can be used like this.

This is lets say this is a code called “colliderScript.js” which is attached to all the colliders that can change the weapon of the player. Plus, mark the colliders as Trigger:

var weaponNumber : int;  //this value can be changed in editor for each collider 
                         //if you put is as 1 then it changes FPS weapon to weapon 1
                         //if its 2 then it changes to weapon 2
function Update(){ //this is nothing
}

Now the code that you have above will have this function. Add this function to the same script that has the selectWeapon function and remove the previous OnTriggerEnter function :

function OnTriggerEnter(other : Collider){
    
        switch (other.gameObject.GetComponent(colliderScript).weaponNumber){
            case 0 :SelectWeapon(0);
                    Debug.Log("weapon 0 selected");
                    break;
            case 1 :SelectWeapon(1);
                    Debug.Log("weapon 2 selected");
                     break;
            // and so on
        } //switch ends
  }  //function ends

I hope this helps! PS : not tried this code in Unity so reply if you get any error(s).