Search Unity

Create Script then add to RigidBody error

Discussion in 'Scripting' started by dansav, Apr 26, 2008.

  1. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    510
    I'm creating a script in the project folder called doPhysics. I want to attach it to a Sphere gameObject during runtime from my main script worldsetup.js using addComponent.

    It tries to compile itself ahead of time? But since it's not attached to a rigidbody yet it can't compile?

    It says RigidBody is not a member of UnityEngine
    How do I get past this?
    Thanks,
    Dan

    Here is the script.


    function FixedUpdate () {
    if (this.gameObject.Rigidbody){
    this.gameObject.Rigidbody.AddForce(Vector3(0,10,0));
    }
    }
     
  2. Charles Hinshaw

    Charles Hinshaw

    Joined:
    Feb 6, 2008
    Posts:
    1,070
    Hint: Your code won't work if you manually add it either.

    edit: off the top of my head:

    Code (csharp):
    1. if (rigidbody){
    2.     rigidbody.AddForce(Vector3(0,10,0));
    3. }
     
  3. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    510
    It works.
    Why does that work.
    what is rigidbody?
    It is not Rigidbody so what's the difference?

    I don't get it.
    and I can't find the lowercase one in the manual.

    Thanks,

    Dan
     
  4. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    All of the lowercase references are here:

    http://unity3d.com/support/documentation/ScriptReference/Component.html

    The lowercase "rigidbody" is a reference to the instance of a RigidBody component on the GameObject, if one exists.

    Likewise, "transform" is a reference to the instance of a Transform component on the Game Object (which will always exist).

    It's just a naming convention. Class names are done in CamelBack style, with the first letter uppercase, while variables generally start lowercase.
     
  5. Charles Hinshaw

    Charles Hinshaw

    Joined:
    Feb 6, 2008
    Posts:
    1,070
    Rigidbody can be viewed as a type of component. Most common components can be attached as member variables... the lowercase rigidbody is the member variable for that.

    Easier than writing GetComponent(Rigidbody).AddForce(Vector3(0,10,0));

    edit: Matthew beat me to the reply...
     
  6. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    If it helps you think about it, writing "rigidbody" is basically shorthand for writing GetComponent(Rigidbody).