1
\$\begingroup\$

I am making use of OnTriggerEnter(Collider other), is there a way to get access to the script attached to my other gameobject without explicitly writing the name of the script? my code is:

void OnTriggerEnter()
{
  other.attachedRigidBody.GetComponent<xyz>();
}

xyz is the name of the script attached to other, but I don't want to write xyz, but rather want to find a way to make my other gameobject implicitly look for whatever script is attached to it.

\$\endgroup\$
3
  • \$\begingroup\$ You probably won't be able to do so, because the code needs to know what script to get information from. Though it would be curious to see if anyone knows a way to do this. \$\endgroup\$ Commented May 10, 2018 at 11:52
  • \$\begingroup\$ How do you want your code to behave when there is more than one script attached to the object? \$\endgroup\$
    – Philipp
    Commented May 10, 2018 at 12:29
  • \$\begingroup\$ Maybe an interface or abstract class can help you in this case. Then your MonoBehaviours to implement/inherit it. \$\endgroup\$
    – Nikaas
    Commented May 11, 2018 at 7:33

1 Answer 1

2
\$\begingroup\$

I am not sure what are you planning to achieve with this, but here you go:

other.GetComponent<MonoBehaviour>();

Returns you a MonoBehaviour attached to the other. I am not sure which one, probably the first as seen in the editor. If you want to get all of the components, use GetComponents<MonoBehaviour>().

\$\endgroup\$
3
  • \$\begingroup\$ and how can I call a specific function from the script? \$\endgroup\$
    – NAnn
    Commented May 10, 2018 at 13:35
  • 1
    \$\begingroup\$ @D.g cast it to xyz. Jokes aside, you can use either reflection or dynamic, but most importantly: if you have to do this you are doing something wrong, really wrong. \$\endgroup\$
    – wondra
    Commented May 10, 2018 at 15:13
  • 1
    \$\begingroup\$ You're correct, it's the first one in the list shown in the inspector. GetComponent works this way for any kind of component. \$\endgroup\$
    – Galandil
    Commented May 10, 2018 at 15:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .