# Accessing RigidBody2d from OnTriggerEnter2D(Collider)

I have the following script on my water object which, when the Players ship triggers it, the ships gravity is inverted to give the sense of buoyancy. I have added a 'print' statement to prove that the collision is working and that the Name condition check works, which it does. However it throws an error when trying to access the plays ship Rigidbody2D property to then access the GravityScale with the message:

There is no 'Rigidbody2D' attached to the "Player" game object, but a script is trying to access it. You probably need to add a Rigidbody2D to the game object "Player"...

void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.name == "Player")
{
print("Player Hit Water");
Rigidbody2D tmp = coll.gameObject.GetComponent<Rigidbody2D>();
tmp.gravityScale *= -1;
}
}


Update: It turns out this code is fine it was the structure of my gameobjects that was the problem as the Rigidbody2D was in the child object, not the parent. See comments below for details.

• The player ship does have a Rigedbody2D component attached btw. – TheGrovesy Jul 31 '16 at 8:32
• what's wrong?! it work correctly – Seyed Morteza Kamali Jul 31 '16 at 9:53
• @smkplus It works for you?? For me when the event fires I get the message as shown in my OP saying there is no rigidbody2d! What version of Unity are you using? – TheGrovesy Aug 1 '16 at 15:23
• @smkplus Turns out there was nothing wrong with my code (your suggestions also worked). The problem was my Rigidbody was on a gameobject, within my player game object. I recreated the components in my top level player object, deleted the lower level object and it works. Out of interest, if I have 2 levels of game object how would you access the lower level? – TheGrovesy Aug 1 '16 at 20:28
• sorry i don't understand your mind.what's mean top level and lower level and how you could fix it by deleting the lower level object.if top level mean parent and lower level mean child? or level1 & level2 – Seyed Morteza Kamali Aug 2 '16 at 4:12

you should use cast

Rigidbody2D tmp = coll.gameObject.GetComponent<Rigidbody2D>() as Rigidbody2D;


or

Rigidbody2D tmp = (Rigidbody2D)coll.gameObject.GetComponent<Rigidbody2D>();


but if don't work try this:

void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.name == "Player")
{
print("Player Hit Water");
GameObject tmp = coll.gameObject;
tmp.GetComponent<Rigidbody2D>().gravityScale *= -1;
}
}