So I have a parent game object with a reference to a box collider. The box collider is located inside a game object that is the child of the parent object.
Now what is the best way to get the OnCollision method to get called in the parent game object? Since this is on the iPhone I want to use the approach that gives me the best performance, so I would like to avoid things like SendMessage.
What i’m thinking about now is creating a script and put it on the child game object that invokes a method on the parent using MonoBehavior.Invoke… but shouldn’t there be a better way? Am I missing something here? What is the “correct” way of doing this?
Yes exactly that is what i suspected would be the solution… it would be nice if parents could automatically get the OnCollision for their childrens… but I guess it’s often the other way around
// On the child gameObject:
class CollisionHandler : MonoBehaviour
{
private TheParentsScript parentsScript;
void Awake()
{
parentsScript = transform.parent.GetComponent<TheParentsScript>();
}
void OnCollisionEnter(Collision CollisionInfo)
{
if (theCollisionMeetsYourCriteria)
{
parentsScript.SomeMethod();
}
}
}
// On the parent gameObject:
class TheParentsScript : MonoBehavior
{
void SomeMethod()
{
// Your code here.
}
}
This code is bound to work faster, even if only a tiny bit, because:
It spares you the unnecessary store of the transform.parent reference into a temporary variable; instead, it uses GetComponent() on it directly (one less pointer dereference, yay!).
It uses the generic version of GetComponent(), which saves you from having to use typeof and is more type-safe than the ‘as’ typecast operator.