How do you detect player collision with a object?

I am trying to create a Clip object that sits on the ground and if the player does not have the maximum amount of pistol ammo and touches said object he or she will pick it up. I am new to unity script (2 days) and have managed to make the Weapon Manager as well as pistol, but i just can’t get the ammo to work.

// when player touches ammo.
function OnControllerColliderHit ()
{	
	//access WeaponManager.js
	var weaponManager : Component = GetComponent(WeaponManager);	

        // If player does not have the maximum amount of ammo.
	if (weaponManager.ammoCountPistol >= 48)
	{
                // Add one clip to the pistol bullet pile.
                weaponManager.ammoCountPistol += weaponManager.maxClipCountPistol;
                //destroy pistol clip.
                Destroy(this.gameObject);
	}
	
}

the above code does not cause any errors, but at the same time if i walk through it with a Character Controller no ammo is added and no Debug.Log logs which i guess means no collider hit is being detected?

2 Answers

2

OnControllerColliderHit is called on the player, not the ammo. Use OnTrigger / OnCollision instead.

If i use OnTrigger or OnCollision how would i set that up to detect the player and not other objects in the scene, and is one of those functions more efficient than the other?

–

You could use that script, but I assumed it was on the pick up object, because of the destroy function. If you put that script on your player, you should get the event. You'll have to add (hit : ControllerColliderHit) as a parameter though, to have access to the pickup object.

–

[Tag the object so the script can recognize it.] 1

Berenger told me what was wrong, but you have told me how to fix my problem. This was a hard one, Thanks.

–