x


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 the Player script.
    • EnemyPrefab, which has a collider/rigid body, and the Enemy 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.

more ▼

asked Dec 09 '10 at 07:44 PM

Ipsquiggle gravatar image

Ipsquiggle
186 7 9 16

Found this similar question which has the same answer: http://answers.unity3d.com/questions/17039/how-to-get-a-script-component-in-c

Dec 09 '10 at 07:53 PM Ipsquiggle
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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>();
more ▼

answered Dec 09 '10 at 07:48 PM

Mike 3 gravatar image

Mike 3
30.5k 10 65 253

Thanks. I found the answer (posted in a comment on the question) a few minutes after posting this. Yay generics!

Dec 09 '10 at 07:55 PM Ipsquiggle

Generics are fun! You can also use the non generic version if you're strange like that, Player p = (Player)other.GetComponent(typeof(Player));

Dec 09 '10 at 08:03 PM Mike 3
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2505
x2097
x1707
x30

asked: Dec 09 '10 at 07:44 PM

Seen: 1126 times

Last Updated: Dec 09 '10 at 07:44 PM