- Home /
Best practice for checking which object has collided.
In terms of performance, what is the best approach for checking which object has interacted with a collider/trigger? For instance, picking up items.
Is it better to have one script attached to the player that checks for the explicitly stated tags of each individual item; and checks through them all via an else if statement. Or rather, would the more optimal approach for performance be having a script on each individual item that then checks for the "Player" tag, thus not running through slews of if statements?
Sorry if I'm missing something obvious here, thanks.
Answer by Cornelis-de-Jager · Jan 07, 2019 at 10:36 PM
I would say on the player. Also if would do an overarching tag for all the intractable items. For example there is a sword and a healing potion. I would tag them both as interact-able.
That way all you need to do is write code for the player:
OnTriggerEnter (Collider collider) {
if (collider.tag == "interactable"){
// Do further things specific to the item
}
}
That way you don't have do go through a list of items, and you stop the execution of the collision check on however many X amount of items, which in itself would have been X times more computationally expensive.
Answer by cdr9042 · Jan 08, 2019 at 05:01 AM
Cornelis's answer is correct, but when comparing tags, you should use gameObject.CompareTag https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
Otherwise, you risk generating too much garbage in memory.
The best way is to check their LayerMask, it's numeric comparison, more efficient than string comparison.
static LayerMask itemLayer = LayerMask.NameToLayer("LAYER_NAME")
function OnCollisionEnter(collision : Collision)
{
if (collision.collider.gameObject.layer == itemLayer )
{
Debug.Log("Touched an item");
}
}
Thanks for that info. Just for clarification, if you could, on this overarching tag/layer comparison method stated above. This couldn’t be used if each individual item claimed a unique quality I.e it’s first instance needing to be added to a list. Each item would need its own unique tag/layer in that circumstance, correct?
You mean like checking if it's colliding against an unique object? Or only check colliding against first object and ignore the rest if it's colliding against multiple objects in one frame?
The approach of having each item that can be picked up under the same tag. What if each item on pick up needed to call its own individual functionality, this overarching tag approach wouldn’t be possible right, or do I use another method to distinguish between what’s been picked up other than checking it’s tag?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
OnTriggerEnter is running twice when collisions is detected. Couldnt fix. 1 Answer
How Does OnTriggerEnter() Work? 0 Answers
Problem with OnTriggerEnter 2 Answers