Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save taesiri/84ef01fbfa7851513f50 to your computer and use it in GitHub Desktop.
Save taesiri/84ef01fbfa7851513f50 to your computer and use it in GitHub Desktop.
GetComponent<Transform> vs gameObject.transform vs storing gameObject.transform in a variable

Performance Test - Acceesing transfrom of an object in Unity3D

  • Method 1 - GetComponent
  • Method 2 - gameObject.transform
  • Method 3 - storing gameObject.transform in a variable
using UnityEngine;
namespace Assets
{
public class BallScript : MonoBehaviour
{
public int Iteration = 1000;
private int _direction = 1;
private int _lastNumb;
private Transform _t;
private void Start()
{
_t = transform;
_lastNumb = 3;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
_lastNumb = 0;
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
_lastNumb = 1;
}
if (Input.GetKeyDown(KeyCode.Alpha3))
{
_lastNumb = 2;
}
if (_lastNumb == 0)
{
LocalTransformMethod();
}
else if (_lastNumb == 1)
{
TransformMethod();
}
else
{
if (_lastNumb == 2)
{
GetComponentMethod();
}
}
}
private void LocalTransformMethod()
{
for (int i = 0; i < Iteration; i++)
{
_t.position = _t.position + Vector3.up*_direction*Time.deltaTime/Iteration;
if (_t.position.y < -4 || _t.position.y > 6)
_direction *= -1;
}
}
private void TransformMethod()
{
for (int i = 0; i < Iteration; i++)
{
transform.position = transform.position + Vector3.up*_direction*Time.deltaTime/Iteration;
if (transform.position.y < -4 || transform.position.y > 6)
_direction *= -1;
}
}
private void GetComponentMethod()
{
for (int i = 0; i < Iteration; i++)
{
GetComponent<Transform>().position = GetComponent<Transform>().position + Vector3.up*_direction*Time.deltaTime/Iteration;
if (GetComponent<Transform>().position.y < -4 || GetComponent<Transform>().position.y > 6)
_direction *= -1;
}
}
}
}
Copy link

ghost commented Feb 18, 2021

Hi, very interesting! What's the outcome of this? Can you share the result?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment