- Home /
Character controller collision
i am attempting to make it so that when you collide with an object you collect it so i have this script on the object:
function OnCollisionEnter(collision : Collider){
if(collision.gameObject.tag == "Player"){
print(gameObject.name);
var player = GameObject.Find("First Person Controller");
var stacking = GameObject.Find(gameObject.name+"_model").GetComponent(stacking);
if (stacking.stackAmount >=1){
stacking.stackAmount++;
Destroy(gameObject);
}else if (Inventory.itemNum < 8){
player.GetComponent(Inventory).AddItemToInventory(gameObject);
stacking.stackAmount++;
} } }
the issue is since im using the character controller it isnt registering the collision and i cant use OnControllerColliderHit as it causes me alot of issues. thanks in advance
Answer by aldonaletto · May 10, 2012 at 12:03 AM
Usually you should make the item a trigger and use OnTriggerEnter in the player or item script (the event is sent to both). But when the item has a rigidbody with Use Gravity checked, it falls through the floor. A solution is to place the trigger in a child of the main object: child an empty object to the item, add a collider (usually a sphere) and set Is Trigger. Modify the OnCollisionEnter to OnTriggerEnter like below and attach the script to the trigger, not to the item:
function OnTriggerEnter(other: Collider){ if (other.tag == "Player"){ print(parent.name); // the parent is the item var player = other.gameObject; // the player is the "other" object // use the parent's name to find the script stacking var stacking = GameObject.Find(parent.name+"_model").GetComponent(stacking); if (stacking.stackAmount >=1){ stacking.stackAmount++; Destroy(gameObject); } else if (Inventory.itemNum < 8){ player.GetComponent(Inventory).AddItemToInventory(gameObject); stacking.stackAmount++; // I suspect you should destroy the object in this case too... } } }
ill try this out now and see it works, thanks for the help
yea this works just need to make it destroy the parent object now and I am golden so thanks =D
$$anonymous$$y bad! It should be
Destroy(transform.parent.gameObject);
By the way, other references like parent.name should also be altered to trasnsform.parent.name etc.
Answer by Levantez · May 09, 2012 at 05:22 PM
If it's collecting an item, try using TriggerEnter instead.
Make sure you check is trigger on the item's collision component.
i tried a trigger and that didn't work either, also a trigger makes it fall through the floor.
Your answer
Follow this Question
Related Questions
Weird Collision Detection with a Cube and OnCollisionEnter 2 Answers
Check if collider is colliding with anything non specific? 1 Answer
Make Character Controller a Box? 2 Answers
Quickly spinning player glitches through walls 2 Answers
OnCollisionEnter2D being called upon exiting collider? 1 Answer