picking up weapons script?

i’m making a small game where you choose a rifle from a rack and take it to a range. The issue is, every pickup script I see is made to use 2 or more switchable weapons. With some help, I started a script, but I suck at scripting in the first place. I parented a small sphere to the main camera that would swap out with a weapon on one of the racks when you get close enough, but I can’t seem to get it to work. I do have my controller tagged as “player”. Here’s my script:

var SpawnTo:Transform;
var Gun : Transform;
function OnCollisionEnter(hit:Collision)
{
if(hit.gameObject.tag == "Player")
{
Gun.parent = SpawnTo;
Gun.transform.position = SpawnTo.transform.position;
Gun.transform.rotation = SpawnTo.transform.rotation;
}
}

I could use help ASAP

I don’t get why that doesn’t work, but I usually use triggers (just a personal preference). Here’s how I would do it: (JavaScript)

//Remember to check is trigger on the gun's collider 

var spawnTo : Transform; 
var gun : gameObject;

function OnTriggerEnter(col : Collider){

if(col.tag == "Player"){

print("Player touched weapon!");

gun.parent = spawnTo; 
gun.transform.position = spawnTo.transform.position; 
gun.transform.rotation = spawnTo.transform.rotation;

}

}

apparently, the script itself worked! thank you!

issue is, cosmetically it didn’t. the weapon didn’t spawn on the sphere and I ended up getting this error:

MissingFieldException: Field ‘UnityEngine.GameObject.parent’ not found.

This code should get you on the right track:

var SelectedWeapon : GameObject; //Current equipped weapon

var Primary : GameObject;     //Primary weapon

var isLocked = false; //Checks if switching is off

function Start () {
	SelectedWeapon = Primary; //Selects Primary weapon
}

function Update () {

    if(Input.GetKey(KeyCode.LeftShift)){
        if(isLocked){
            isLocked = true;
        }
        
        if(!isLocked){
            isLocked = false;
        }
    }

    if(Input.GetKey(KeyCode.Alpha1) && (!isLocked)){
        SelectedWeapon = Primary;
    }
    
    if(SelectedWeapon == Primary){
        SelectedWeapon = Primary;
    }
}

function ChangeWeapon(WeaponType : String){
   WeaponType = "Primary";
}

function ChangeWeapon(WeaponObject : GameObject, WeaponType : String){

    if(WeaponType == "Primary"){
        Primary = WeaponObject;
    }
}

Only thing is that for changing, make sure the weapon is in the hand just like the others but just inactivated. When you want to change what weapon you use, just call the ChangeWeapon function. Designed this script just for this cause too :slight_smile: