delegate event OnCollisionEnter...

Hi,

I have one script attached to the MainCamera.
I create all objects dynamically.
Now I want in this unique script, to add some collision detection to some objects.

I want to use something like:

onject1.collider.enter += OnCollisionEnter(Collision col){};
onject2.collider.enter += OnCollisionEnter(Collision col){};

It’s this possible?
How can achieve this?

Thanks.

To actually answer the question (as I was just looking for the answer myself), no, it is not possible. There is only the workaround mentioned in the OP’s comment i.e. dynamically add a component script which inherits from MonoBehaviour and implements OnCollisionEnter().

This is a shame as we can dynamically do stuff like this on Buttons;

Button b = go.GetComponent<Button>();
b.onClick.AddListener(...);

…and other stuff in EventTrigger which ties in to UnityEngine.EventSystems. But Collider & Trigger stuff is not exposed in EventSystems, which is a shame…

Collider.OnCollisionEnter is a Message, but not a public method. Collider.OnTriggerEnter is the same, but in the docs for that it states “Note: OnTriggerEnter is not technically part of Collision. It is a MonoBehaviour function” and it seems we cannot hook in to these MonoBehaviour functions.

You have the entire .NET library at your disposal. Check out the tutorial on events

Unity will give you call backs to OnCollisionXXX. Simply fire your event from one of the built in functions.