fbpx

 

Vector2 assignment ...
 

Vector2 assignment efficiency ?  

   RSS

0

Does anyone have any knowledge regarding the relative efficiency of assigning values to Vector2's

My gut tells me Option02, but I have no real 'proof'
It may only be a minor difference, but vectors get changed/assigned a lot in Updates.

 
// codehimbelonga kdub 2019-09

using UnityEngine;

public class TestBehaviourScript : MonoBehaviour {
Vector2 vector02, vector03;
float minX, maxX;

void Start() {
minX = 1;
maxX = 10; // or whatever
}

void Update() {
DoOption1();
DoOption2();
DoOption3();
}

private void DoOption1() {
Vector2 vector01 = new Vector2(transform.position.x, transform.position.y);
vector01.x = Mathf.Clamp(GetMouseXPositionInWU(), minX, maxX);
transform.position = vector01;
}

private void DoOption2() {
vector02 = transform.position;
vector02.x = Mathf.Clamp(GetMouseXPositionInWU(), minX, maxX);
transform.position = vector02;
}

private void DoOption3() {
vector03 = new Vector2(transform.position.x, transform.position.y);
vector03.x = Mathf.Clamp(GetMouseXPositionInWU(), minX, maxX);
transform.position = vector03;
}

private float GetMouseXPositionInWU() {
// TODO Flesh-Out
return 5f; // or whatever
}
}

Regards,

Topic Tags
1 Answer
0

Though, Option03 can be optimised to :

 

    private void DoOption3() {
vector03 = new Vector2(transform.position.x, transform.position.y) {
x = Mathf.Clamp(GetMouseXPositionInWU(), minX, maxX)
};
transform.position = vector03;
}

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

This post was modified 2 months ago 2 times by kdub (Kerry)
Share:

 

 

Scroll to Top

Please Login or Register