Search Unity

Using rigidbody.position is much faster than transform.position

Discussion in 'Editor & General Support' started by whynotme, Nov 2, 2013.

  1. whynotme

    whynotme

    Joined:
    Mar 24, 2012
    Posts:
    54
    Hi,

    I just did some tests and find out that set position through rigidbody.position is much faster than transform.position. Here are the results, 10M loops:
    When gameObject has rigidbody:

    transform.position = Vector3.zero; // 5.7s
    thisTransform.position = Vector3.zero; // 4.7s

    rigidbody.position = Vector3.zero; // 2.9s
    thisRigidbody.position = Vector3.zero; // 1.3s


    When gameObject doesn't has rigidbody:

    transform.position = Vector3.zero; // 4.4s
    thisTransform.position = Vector3.zero; // 3.4s

    I don't have any mobile device to test. All are tested on x86 laptop, Unity 4.2.2.
    It seems attach a rigidbody to gameobject and set position from it is much faster than set transform position (1.3s vs 3.4s). Why is there a significant different, and is setting position through rigidbody a good method?

    Here is my code:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Diagnostics;
    5.  
    6. public class test : MonoBehaviour {
    7.    
    8.     Transform thisTransform;
    9.    
    10.     Rigidbody thisRigidbody;
    11.    
    12.     Stopwatch timer = new Stopwatch();
    13.    
    14.     // Use this for initialization
    15.     void Start () {
    16.        
    17.         thisTransform = transform;
    18.        
    19.         thisRigidbody = rigidbody;
    20.        
    21.         timer.Start();
    22.        
    23.         for (int i = 0; i < 10000000; i++) {
    24.             thisRigidbody.position = Vector3.zero;
    25.  
    26.             //rigidbody.position = Vector3.zero;
    27.  
    28.             //transform.position = Vector3.zero;
    29.             //thisTransform.position = Vector3.zero;
    30.         }
    31.        
    32.         timer.Stop();
    33.         print(timer.Elapsed);
    34.     }
    35. }