Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

add rigidbody through scripting?

Discussion in 'Scripting' started by tool55, May 23, 2010.

  1. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    Hi guys,

    I have a parent object, like a ball, with another object as a child inside. I have it scripted such that when the parent ball collides, it unparents the child. No problem there. The problem is that I don't want to child object to react to physics or gravity until it's unparented. After it's unparented, I want it to fall, bounce etc. I've tried setting isKinematic to true until the parent is detached, but there's still mass in the child object and it goes flying on it's own away from the parent. Is there a way to make the rigidbody null until the child is unparented, then add it back? And is this the best solution? Here's the script I'm using now that isn't working very well:

    Code (csharp):
    1. function Update () {
    2. if (transform.parent == "ball")
    3. {
    4. transform.rigidbody.isKinematic = true;
    5. }
    6. else
    7. {
    8. transform.rigidbody.isKinematic = false;
    9. }
    10. }
    I've attached this to the child object.

    As always, thanks in advance for your help. :roll:
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Use AddComponent(Rigidbody).

    --Eric
     
  3. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    Thanks, that worked perfectly. My only other question is how can I change the rigidbody parameters once it's added? Do I write a line of code for each: Mass, Drag etc.?

    Thanks again, Eric5h5.
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. var rb : Rigidbody = AddComponent(Rigidbody);
    2. rb.mass = .5;
    3. rb.drag = 2.0;
    4. //etc.
    --Eric
     
  5. tool55

    tool55

    Joined:
    Jul 10, 2009
    Posts:
    334
    Perfect. Thanks!
     
  6. GeorGios1

    GeorGios1

    Joined:
    Aug 10, 2016
    Posts:
    3
    AddComponent(Rigidbody) is removed from unity because unity throws an error :

    AddComponent is not a member of 'myscriptname'
     
  7. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802