Skip to content

Commit 9fc5896

Browse files
committed
UnityHelper
1 parent bdb7eb0 commit 9fc5896

File tree

5 files changed

+838
-1
lines changed

5 files changed

+838
-1
lines changed

Examples/UnityHelperExamples.cs

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
using UnityEngine;
2+
3+
#pragma warning disable 219 // We don't care about: warning CS0219: The variable `[...]' is assigned but its value is never used
4+
namespace UnityUtilities.Examples
5+
{
6+
public class UnityHelperExamples : MonoBehaviour
7+
{
8+
[SerializeField] Transform someEnemyTransform;
9+
[SerializeField] Transform enemyIndicator;
10+
[SerializeField] GameObject prefab;
11+
[SerializeField] LayerMask someLayerMask;
12+
[SerializeField] CharacterController playerCharacterController;
13+
14+
void Awake()
15+
{
16+
TransformVectorColorExamples();
17+
Vector2RotationExamples();
18+
GameObjectExamples();
19+
RectExamples();
20+
PlayerPrefsExample();
21+
CapsuleCastExample();
22+
OtherExamples();
23+
}
24+
25+
void TransformVectorColorExamples()
26+
{
27+
/* Set the transform.position.x to 5 and z to 3. Keeps y.
28+
* Equivalent to:
29+
* var position = transform.position;
30+
* position.x = 5;
31+
* position.z = 3;
32+
* transform.position = position;
33+
*/
34+
transform.SetPosition(x: 5, z: 3);
35+
36+
// Same as above; only sets transform.localEulerAngles.y.
37+
// There are extension methods for all position/rotation/scales.
38+
transform.SetLocalEulerAngles(y: 180);
39+
40+
// Similar methods are available for Vector2/3/4 and Color:
41+
// Gets the transform.position, but with y set to 0.
42+
Vector3 floorPosition = transform.position.Change3(y: 0);
43+
44+
// Gets the material color, but sets the color.a value to 0.5.
45+
Color halfTransparentColor = GetComponent<Renderer>().sharedMaterial.color.ChangeAlpha(0.5f);
46+
47+
// Sets the position/rotation of enemyIndicator to someEnemyTransform.position/rotation
48+
enemyIndicator.CopyPositionAndRotatationFrom(someEnemyTransform);
49+
}
50+
51+
void Vector2RotationExamples()
52+
{
53+
// Create a length 1 Vector2 pointing 40 degrees away from (1.0, 0.0)
54+
var vector = UnityHelper.CreateVector2AngleDeg(20f);
55+
Debug.Log(vector); // => (0.9, 0.3)
56+
57+
// Rotate the vector 70 degrees
58+
vector = vector.RotateDeg(70f);
59+
Debug.Log(vector); // => (0.0, 1.0)
60+
61+
// Output the current vector rotation
62+
Debug.Log(vector.GetAngleDeg()); // => 90
63+
}
64+
65+
void GameObjectExamples()
66+
{
67+
// Assigns layer 4 to this GameObject and all its children recursively
68+
gameObject.AssignLayerToHierarchy(4);
69+
70+
// Create an instance of a prefab. When the prefab is named "Original", the instance will
71+
// be named "Original(Copy)"
72+
GameObject copiedGameObject = Instantiate(prefab);
73+
74+
// Return the name without "(Copy)"
75+
Debug.Log(copiedGameObject.GetNameWithoutClone()); // => Original
76+
77+
// Change the name back to "Original"
78+
copiedGameObject.StripCloneFromName();
79+
}
80+
81+
void RectExamples()
82+
{
83+
// Make a rect from (10|20) to (60|120)
84+
Rect rect = new Rect(10, 20, 50, 100);
85+
86+
// Gets a random position for an enemy in the rect, leaving a 5 unit border
87+
Vector2 enemySpawnPosition = rect.RandomPosition(-5);
88+
89+
// Gets a random sub rect of size 10|10 in which we could spawn multiple enemies
90+
Rect enemySpawnSubrect = rect.RandomSubRect(10, 10);
91+
92+
Vector2 enemyPosition = new Vector2(0, 500);
93+
94+
// Clamp an enemy position to the rect
95+
enemyPosition = rect.Clamp2(enemyPosition);
96+
Debug.Log(enemyPosition); // Output: (10.0, 120.0)
97+
98+
// Create a rect that is 10 units bigger to each side
99+
Rect biggerRect = rect.Extend(10);
100+
101+
// Get the corner points
102+
Vector2[] cornerPoints = rect.GetCornerPoints();
103+
}
104+
105+
void PlayerPrefsExample()
106+
{
107+
// Gets a PlayerPrefs key "FirstStart" or return true if not set
108+
bool isFirstStart = UnityHelper.PlayerPrefsGetBool("FirstStart", true);
109+
110+
// Set the key FirstStart to false
111+
UnityHelper.PlayerPrefsSetBool("FirstStart", false);
112+
}
113+
114+
void CapsuleCastExample()
115+
{
116+
Vector3 point1;
117+
Vector3 point2;
118+
float radius;
119+
Vector3 origin = playerCharacterController.transform.position;
120+
121+
// Get the data for the capsule cast from the current player position
122+
UnityHelper.GetCapsuleCastData(playerCharacterController, origin, out point1, out point2, out radius);
123+
124+
// Cast 2 units forwards
125+
bool hitSomething = Physics.CapsuleCast(point1, point2, radius, Vector3.forward, 2f);
126+
}
127+
128+
void OtherExamples()
129+
{
130+
// Does the layer mask contain layer 4?
131+
bool containsLayer4 = someLayerMask.ContainsLayer(4);
132+
133+
// Get the bounds of all colliders in the level to clamp the camera later on
134+
Collider[] allColliders = FindObjectsOfType<Collider>();
135+
Bounds levelBounds = UnityHelper.CombineColliderBounds(allColliders);
136+
137+
// Find out how much the perspective camera can see at 10 unit away
138+
Vector2 viewportSizeAtDistance = Camera.main.CalculateViewportWorldSizeAtDistance(10);
139+
}
140+
}
141+
}
142+
#pragma warning restore 168

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ If you find any bugs or have suggestions, please add an [Issue](https://github.c
1515
* [Range](https://github.com/TobiasWehrum/unity-utilities/tree/master/Range): Editable data types that take an `int`/`float` range. Used for things like "Spawn 2 to 4 enemies."
1616
* [RollingArray](https://github.com/TobiasWehrum/unity-utilities/tree/master/RollingArray): Collection that keeps the last x elements that are added to it.
1717
* [Singleton](https://github.com/TobiasWehrum/unity-utilities/tree/master/Singleton): Allows easy and convenient creation of a Singleton. Optionally makes a Singleton persist between scenes while ensuring that only one exists.
18+
* [UnityHelper](https://github.com/TobiasWehrum/unity-utilities/tree/master/UnityHelper): Contains a plethora of useful extensions and helpers for Transform, GameObject, Vector2/3/4, Rect and more.
1819

1920
## Usage
2021

@@ -27,6 +28,7 @@ You can also just use selected scripts, but you should check the "Dependencies"
2728
The class documentation is available [here](http://tobiaswehrum.github.io/UnityUtilities/html/annotated.html).
2829

2930
## Changelog
31+
* 2016-06-08: Added [UnityHelper](https://github.com/TobiasWehrum/unity-utilities/tree/master/UnityHelper).
3032
* 2016-06-05: Added [EditorHelper](https://github.com/TobiasWehrum/unity-utilities/tree/master/EditorHelper) and [RollingArray](https://github.com/TobiasWehrum/unity-utilities/tree/master/RollingArray). Added `[Tooltip]` for `NoiseOutputValue` and edited the existing `PropertyDrawer` to use tooltips.
3133
* 2016-05-15: Added [LINQExtensions](https://github.com/TobiasWehrum/unity-utilities/tree/master/LINQExtensions) and [RandomBag](https://github.com/TobiasWehrum/unity-utilities/tree/master/RandomBag).
3234
* 2016-05-09: Added the [class documentation website](http://tobiaswehrum.github.io/UnityUtilities/html/annotated.html).

Singleton/SingletonMonoBehaviour.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public static TSubclass InstanceOptional
5959
/// <param name="optional">If this is set to false, and error message will be shown if there is no instance found.</param>
6060
static void UpdateInstance(bool optional)
6161
{
62-
var instances = (TSubclass[]) FindObjectsOfType(typeof (TSubclass));
62+
var instances = FindObjectsOfType<TSubclass>();
6363
if (instances.Length == 1)
6464
{
6565
instance = instances[0];

UnityHelper/README.md

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# UnityHelper
2+
3+
The UnityHelper contains a plethora of useful extensions and helpers for Transform, GameObject, Vector2/3/4, Rect and more.
4+
5+
## Examples
6+
7+
### Transform/Vector/Color
8+
9+
```C#
10+
/* Set the transform.position.x to 5 and z to 3. Keeps y.
11+
* Equivalent to:
12+
* var position = transform.position;
13+
* position.x = 5;
14+
* position.z = 3;
15+
* transform.position = position;
16+
*/
17+
transform.SetPosition(x: 5, z: 3);
18+
19+
// Same as above; only sets transform.localEulerAngles.y.
20+
// There are extension methods for all position/rotation/scales.
21+
transform.SetLocalEulerAngles(y: 180);
22+
23+
// Similar methods are available for Vector2/3/4 and Color:
24+
// Gets the transform.position, but with y set to 0.
25+
Vector3 floorPosition = transform.position.Change3(y: 0);
26+
27+
// Gets the material color, but sets the color.a value to 0.5.
28+
Color halfTransparentColor = GetComponent<Renderer>().sharedMaterial.color.ChangeAlpha(0.5f);
29+
30+
// Sets the position/rotation of enemyIndicator to someEnemyTransform.position/rotation
31+
enemyIndicator.CopyPositionAndRotatationFrom(someEnemyTransform);
32+
```
33+
34+
### Vector2 Rotation
35+
36+
```C#
37+
// Create a length 1 Vector2 pointing 40 degrees away from (1.0, 0.0)
38+
var vector = UnityHelper.CreateVector2AngleDeg(20f);
39+
Debug.Log(vector); // => (0.9, 0.3)
40+
41+
// Rotate the vector 70 degrees
42+
vector = vector.RotateDeg(70f);
43+
Debug.Log(vector); // => (0.0, 1.0)
44+
45+
// Output the current vector rotation
46+
Debug.Log(vector.GetAngleDeg()); // => 90
47+
```
48+
49+
### GameObject
50+
51+
```C#
52+
// Assigns layer 4 to this GameObject and all its children recursively
53+
gameObject.AssignLayerToHierarchy(4);
54+
55+
// Create an instance of a prefab. When the prefab is named "Original", the instance will
56+
// be named "Original(Copy)"
57+
GameObject copiedGameObject = Instantiate(prefab);
58+
59+
// Return the name without "(Copy)"
60+
Debug.Log(copiedGameObject.GetNameWithoutClone()); // => Original
61+
62+
// Change the name back to "Original"
63+
copiedGameObject.StripCloneFromName();
64+
```
65+
66+
### Rect
67+
68+
```C#
69+
// Make a rect from (10|20) to (60|120)
70+
Rect rect = new Rect(10, 20, 50, 100);
71+
72+
// Gets a random position for an enemy in the rect, leaving a 5 unit border
73+
Vector2 enemySpawnPosition = rect.RandomPosition(-5);
74+
75+
// Gets a random sub rect of size 10|10 in which we could spawn multiple enemies
76+
Rect enemySpawnSubrect = rect.RandomSubRect(10, 10);
77+
78+
Vector2 enemyPosition = new Vector2(0, 500);
79+
80+
// Clamp an enemy position to the rect
81+
enemyPosition = rect.Clamp2(enemyPosition);
82+
Debug.Log(enemyPosition); // Output: (10.0, 120.0)
83+
84+
// Create a rect that is 10 units bigger to each side
85+
Rect biggerRect = rect.Extend(10);
86+
87+
// Get the corner points
88+
Vector2[] cornerPoints = rect.GetCornerPoints();
89+
```
90+
91+
### PlayerPrefs: Bool
92+
93+
```C#
94+
// Gets a PlayerPrefs key "FirstStart" or return true if not set
95+
bool isFirstStart = UnityHelper.PlayerPrefsGetBool("FirstStart", true);
96+
97+
// Set the key FirstStart to false
98+
UnityHelper.PlayerPrefsSetBool("FirstStart", false);
99+
```
100+
101+
### Check if a layer is included in a LayerMask
102+
103+
```C#
104+
// Does the layer mask contain layer 4?
105+
bool containsLayer4 = someLayerMask.ContainsLayer(4);
106+
```
107+
108+
### Find out how big the level bounds are
109+
110+
```C#
111+
// Get the bounds of all colliders in the level to clamp the camera later on
112+
Collider[] allColliders = FindObjectsOfType<Collider>();
113+
Bounds levelBounds = UnityHelper.CombineColliderBounds(allColliders);
114+
```
115+
116+
### Calculate Camera viewport world size at distance
117+
118+
```C#
119+
// Find out how much the perspective camera can see at 10 unit away
120+
Vector2 viewportSizeAtDistance = Camera.main.CalculateViewportWorldSizeAtDistance(10);
121+
```
122+
123+
### CharacterController: CapsuleCast
124+
125+
```C#
126+
Vector3 point1;
127+
Vector3 point2;
128+
float radius;
129+
Vector3 origin = playerCharacterController.transform.position;
130+
131+
// Get the data for the capsule cast from the current player position
132+
UnityHelper.GetCapsuleCastData(playerCharacterController, origin, out point1, out point2, out radius);
133+
134+
// Cast 2 units forwards
135+
bool hitSomething = Physics.CapsuleCast(point1, point2, radius, Vector3.forward, 2f);
136+
```
137+
138+
## Dependencies
139+
140+
None.

0 commit comments

Comments
 (0)