0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ The player ship does have a Rigedbody2D component attached btw. \$\endgroup\$ – TheGrovesy Jul 31 '16 at 8:32
  • \$\begingroup\$ what's wrong?! it work correctly \$\endgroup\$ – Seyed Morteza Kamali Jul 31 '16 at 9:53
  • \$\begingroup\$ @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? \$\endgroup\$ – TheGrovesy Aug 1 '16 at 15:23
  • \$\begingroup\$ @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? \$\endgroup\$ – TheGrovesy Aug 1 '16 at 20:28
  • \$\begingroup\$ 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 \$\endgroup\$ – Seyed Morteza Kamali Aug 2 '16 at 4:12
1
\$\begingroup\$

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;
    }
}
|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.