In accordance to
I want to invoke OnCollisionEnter for another MonoBehaviour, like
public MonoBehaviour logicalCollider;
[...]
logicalCollider.OnCollisionEnter();
I get the mentioned error.
In accordance to
I want to invoke OnCollisionEnter for another MonoBehaviour, like
public MonoBehaviour logicalCollider;
[...]
logicalCollider.OnCollisionEnter();
I get the mentioned error.
That’s … kinda … exciting. You do realize that’s not normally how it should be used, right?
MonoBehaviour doesn’t have such a public method. The engine calls it for you, same as any other monobehaviour “message” method.
Does not exist, as expected. Unity calls Start()
for you.
It sounds like maybe you want to use interfaces perhaps, or a base class with your own version of that method.
OnCollisionEnter is a message, not a member of MonoBehaviour. Messages in this context are magic methods that Unity will look for and call if they exist. They do not automatically exist. If you have a specific script that implements OnCollisionEnter, then you can make a variable of that script type specifically and call it from another script.
public class CollisionScript : MonoBehaviour
{
public void OnCollisionEnter(Collider other)
{
Debug.Log("calling");
}
}
public class OtherScript : MonoBehaviour
{
public CollisionScript logicalCollider; // public variable for the script above
private void Start()
{
Collider col = GetAColliderSomeHow();
logicalCollider.OnCollisionEnter(col); // OnCollisionEnter requires a collider argument
}
}
Thank you. I understand now. I find the “message” thing a bit off.
The idea is that the main GO would have a MonoBehaviour with OnCollisionEnter etc. as if it had a collider (logical collider).
A child GO has the actual collider and a script that accepts the logical collider in inspector. This in turn invokes the logical collider methods when the respective events trigger.
I thought I could have both:
I finally went for separate interfaces for trigger and collider, each with 3 methods.
EDIT:
I forgot about the overloads for collision methods, with / without Collision parameter.
And you’re forced to using the public access modifier.
And you can’t drag interfaces in inspector, i.e. drag logical collider GO onto actual collider child GO.
Yeah, they have those limitations, but interfaces are pretty awesome. They can be used with MonoBehaviours though too, so I suppose you could have a reference to that MB and do something like:
public MonoBehaviour Thingy;
IMyColliderInterface mycol = Thingy as IMyColliderInterface;
if (mycol != null)
{
// call that OnCollisionEnter method in your interface.
// NOTE: I would name the method something different to reduce confusion
}
Using Interfaces in Unity3D:
https://discussions.unity.com/t/797745/2
https://discussions.unity.com/t/807699/2
Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.