- Home /
Get the script instance associated with a collider
So I'm still not completely solid on how a GameObject is composed and how to access its various parts.
I have a reference to a Collider, and need to cast it to the type of a script on the same GameObject, but I'm not sure what this would look like.
My scenario looks like this (using C#):
- Two objects:
PlayerPrefab
, which has a collider/rigid body, and thePlayer
script.EnemyPrefab
, which has a collider/rigid body, and theEnemy
script.
Scripts:
public class Player : MonoBehavior {
public void Kill() { //... }
}
And:
public class Enemy : MonoBehavior {
void OnTriggerEnter( Collider other ) {
Player p = (Player)other; // This does not work!
p.Kill();
}
}
So how exactly do I perform that cast in the Enemy script?
Thanks.
Found this similar question which has the same answer: http://answers.unity3d.com/questions/17039/how-to-get-a-script-component-in-c
Answer by Mike 3 · Dec 09, 2010 at 07:48 PM
Unity uses a composition model - you can access the other components from a gameobject or component using GetComponent. In your case you want something like this:
Player p = other.GetComponent<Player>();
Thanks. I found the answer (posted in a comment on the question) a few $$anonymous$$utes after posting this. Yay generics!
Generics are fun! You can also use the non generic version if you're strange like that, Player p = (Player)other.GetComponent(typeof(Player));