简体   繁体   中英

Getting a reference to Rigidbody

I am trying to understand why I see different coders get a reference to a Rigidbody in two different ways.

One way I have seen is:

public class PlayerController : MonoBehaviour {
    Rigidboody rb;

    //then in the start or awake function do:
    void Awake() {
      rb = Getcomponet<Rigidbody>();
    }
}

But then I have seen other people doing:

public class PlayerController : MonoBehaviour {
    [SerializeField] Rigidboody rb;

    void Start() {
    }

Then they would drag the Rigidbody component in to the SerializedField in the inspector.

I know both ways work, but what is the difference between them?

As a general rule, use Getcomponet<T>(); when you have a hard dependency on the component T (for example, by using the attribute [RequireComponent(typeof(T))] in you Script) or when your script can fairly assume that a suitable reference will be there in your game object, without need to drag an instance in the Editor manually.

Use a public property when the component your script depends on is much more specific/useful to this Script than to the rest of the scripts of its GameObject, or when your GameObject might have multiple instances of that component and you will specify which one by dragging in the Editor.

There is no noticable difference in performance. Use the first method if the RigidBody component is on the same GameObject as the script, since it will make it way more diverse. Use the second method if the RigidBody component is on a different GameObject (for some reason). This will negate the need for a Find operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM