- Method 1 - GetComponent
- Method 2 - gameObject.transform
- Method 3 - storing gameObject.transform in a variable
Last active
February 18, 2021 18:29
-
-
Save taesiri/84ef01fbfa7851513f50 to your computer and use it in GitHub Desktop.
GetComponent<Transform> vs gameObject.transform vs storing gameObject.transform in a variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, very interesting! What's the outcome of this? Can you share the result?