Search Unity

How to get data from wheel collider?

Discussion in 'Scripting' started by lad00123, Dec 17, 2014.

  1. lad00123

    lad00123

    Joined:
    Dec 17, 2014
    Posts:
    2
    I'm trying to set up a log that prints the rpm of one of the wheel colliders in my vehicle once every frame. I have my code like this:

    Code (javascript):
    1.  
    2. #pragma strict
    3. var wheel = GetComponent("wheel_bl");
    4.  
    5. function Update () {
    6.     print(wheel.collider.WheelCollider.rpm);
    7. }
    8.  
    However, Unity gives this error:
    BCE0019: 'WheelCollider' is not a member of 'UnityEngine.Collider'.

    What am I doing wrong? The Scripting API page says that WheelCollider inherits from Collider, but it isn't working for me.
     
  2. Coldcalifornian

    Coldcalifornian

    Joined:
    Feb 11, 2014
    Posts:
    14
    The Error message tells you exactly what you need to know. While WheelCollider does inherit from Collider, it is not a member of Collider. When you have a Collider object, it has no inherent knowledge of the derived type's members. The Collider must be downcast to access these members I recommend you review some of the basic OOP concepts.

    Here are two solutions:

    You could expose a public variable of type WheelCollider, and assign the collider to the script to access the rpm:

    Code (CSharp):
    1. public class Example : MonoBehaviour {
    2.  
    3.     public WheelCollider theWheelColliderOfInterest;
    4.  
    5.     void YourMethod () {
    6.         Debug.Log(theWheelColliderOfInterest.rpm);
    7.     }
    8. }
    Alternatively, you can cast the GameObject's Collider as a WheelCollider:

    Code (CSharp):
    1.  
    2. [RequireComponent(typeof(WheelCollider))]
    3. public class Example : MonoBehaviour {
    4.     void YourMethod () {
    5.         WheelCollider castCollider =  gameObject.collider as WheelCollider;
    6.         Debug.Log(castCollider.rpm);
    7.     }
    8. }
    I recommend the first approach.