3
\$\begingroup\$

I have some understanding of c# and I am new to unity. I am currently making a 3D project which use the Rigidbody component on the ball object. When I use following code:

public class Ball : MonoBehaviour 
{
    public float launchSpeed;

    private Rigidbody rigidbody;

    // Use this for initialization
    void Start() 
    {
        rigidbody = GetComponent<Rigidbody>();
        rigidbody.velocity = new Vector3(0, 1, launchSpeed);
    }

    // Update is called once per frame
    void Update() 
    {

    }
}

I get the compiler warning:

'Ball.rigidbody' hides inherited member 'Component.Rigidbody'. Use a new keyword if hiding was intended

I understand the idea behind using new and override in c#, but I just don't understand why is the rigidbody hidden?

I am using Unity 5.2.0f3, and MS Visual Studio Community 2015.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It was an old version of Unity API where you used to be able to access GameObject.rigidbody through the property by default. Now this possibility is considered obsolete, but it is partially preserved for backward compatibility (it called legacy API). Therefore, the compiler says about ambiguity. To resolve the problem, call your variable different from 'rigidbody'.

More info here:

Removed in version 5.2.0p1 Property rigidbody has been deprecated. Use GetComponent() instead. (UnityUpgradable)

Please note: despite the fact that the official documentation says that you should use GetComponent(), you should use a caching to store a reference to the component instead of calling GetComponent everywhere, because it affects bad on a performance:

private Rigidbody rBody;

private void Awake()
{
    rBody = GetComponent<Rigidbody>();
}

public void Test(Vector3 force)
{
    rBody.AddForce(force);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .