Useful tools and handy functions to use for Unity projects.
git clone https://github.com/BrandonBartram98/Unity-ToolsAndHelpers
- Clone project- Import scripts into Unity project
Useful functions for optimization and some that are just reguarly used.
// Non-Allocating WaitForSeconds
// Reduce garbage collection by reusing WaitForSeconds if same wait time exists
private static readonly Dictionary<float, WaitForSeconds> WaitDictionary = new Dictionary<float, WaitForSeconds>();
public static WaitForSeconds GetWait(float time)
{
if (WaitDictionary.TryGetValue(time, out var wait)) return wait;
WaitDictionary[time] = new WaitForSeconds(time);
return WaitDictionary[time];
}
Scripts for converting latitude + longitudes into Unity meters and getting bearings between them.
public float GetBearing(float lat1, float lon1, float lat2, float lon2)
{
double 蠁1 = lat1 * Math.PI / 180; // 蠁, 位 in radians
double 蠁2 = lat2 * Math.PI / 180;
double 位1 = lon1 * Math.PI / 180;
double 位2 = lon2 * Math.PI / 180;
// where 蠁1,位1 is the start point, 蠁2,位2 the end point (螖位 is the difference in longitude)
double y = Math.Sin(位2 - 位1) * Math.Cos(蠁2);
double x = Math.Cos(蠁1) * Math.Sin(蠁2) -
Math.Sin(蠁1) * Math.Cos(蠁2) * Math.Cos(位2 - 位1);
double 胃 = Math.Atan2(y, x);
double brng = (胃 * 180 / Math.PI + 360) % 360; // in degrees
return (float)brng;
}
public float GetDistance(float lat1, float lon1, float lat2, float lon2)
{
// 蠁 is latitude, 位 is longitude, R is earth鈥檚 radius (mean radius = 6,371km)
double R = 6371e3; // metres
double 蠁1 = lat1 * Math.PI / 180; // 蠁, 位 in radians
double 蠁2 = lat2 * Math.PI / 180;
double 螖蠁 = (lat2 - lat1) * Math.PI / 180;
double 螖位 = (lon2 - lon1) * Math.PI / 180;
double a = Math.Sin(螖蠁 / 2) * Math.Sin(螖蠁 / 2) +
Math.Cos(蠁1) * Math.Cos(蠁2) *
Math.Sin(螖位 / 2) * Math.Sin(螖位 / 2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
double d = R * c; // in metres
return (float)d;
}
Useful Virtual Reality scripts.
[Header("XR Rig")]
[SerializeField] private Transform _xrRig;
[SerializeField] private Transform _rigOffset;
[SerializeField] private Transform _rigCamera;
[Header("Transforms")]
[SerializeField] private Transform _desiredTransform;
// Set the player position and rotation, useful to force rotation after loading scene
public void SetPlayerPositionAndRotation()
{
Vector3 newPos = new Vector3(_desiredTransform.position.x, _xrRig.position.y, _desiredTransform.position.z);
_xrRig.SetPositionAndRotation(newPos, _desiredTransform.rotation);
_rigOffset.localRotation = Quaternion.identity;
_rigOffset.localRotation = Quaternion.Inverse(Quaternion.Euler(0, _rigCamera.eulerAngles.y, 0)) * _xrRig.rotation;
}
A prefab + scripts for a Onscreen or VR/AR keyboard.
git clone https://github.com/BrandonBartram98/Unity-ToolsAndHelpers