UTools is a lightweight Unity plugin that provides essential tools and patterns for game development. It includes dependency injection, a message center, GameObject/Component finders, and various utility functions to streamline your Unity development workflow.UTools has no third-party dependencies.
- Lightweight dependency injection system
- Supports method and field injection
- Supports MonoBehaviour class injection
- Project-wide dependency injection support
- Automatic dependency resolution
- Singleton management
- Event-driven communication system
- Type-safe message passing
- Subscribe/unsubscribe mechanism
- Global and scoped event handling
- Hierarchy-based object finding
- Attribute-based object finding
- Automatic Resource loading
- Component caching for performance improvement
- Type-safe component access
- Common Unity operations
- Download the UTools package from the Release page
- Import UTools.unitypackage into your Unity project
- Start using it!
-
Write a class that inherits from
UDIInstallerBase
and implement theRegisterGlobalServices()
andRegisterSceneServices()
methods for global and scene-specific injection, respectively.using UTools; public class _TestInstaller : UDIInstallerBase { // Register as global services protected override void RegisterGlobalServices() { Container.Register<NormalClass>(); Container.Register<MonoBehaviourClass>(); } // Register as scene-specific services protected override void RegisterSceneServices() { Container.Register<NormalClass>(); Container.Register<MonoBehaviourClass>(); } }
For globally registered services, the injected classes remain after loading a new scene and will not be destroyed.
If a MonoBehaviour class already exists in the scene, it will be automatically found and registered. Otherwise, a new object with the same name will be created and the class will be attached.
-
Use the [Inject] attribute to inject services into any class.
using UTools; public class TestInjection : MonoBehaviour { [Inject] NormalClass normalClass; [Inject] MonoBehaviourClass monoBehaviourClass; void Start() { normalClass.DoSomthing(); monoBehaviourClass.DoSomthing(); } }
-
You can also use the
[Inject]
attribute on any method, and dependencies will be injected as parameters into the class.public class TestServiceA { [Inject] public void InjectServiceB(TestServiceB testServiceB) { testServiceB.SayHello(); } }
Note that in the above example,
TestServiceB
will be automatically registered without needing to use theContainer.Register()
method.
// Subscribe to a message
UMessageCenter.Instance.Subscribe<MyCustomMessage>(msg =>
{
txtSubscriber1.text = txtSubscriber2.text = txtSubscriber3.text = msg.ToString();
});
// Publish a message
btnPublisher.onClick.AddListener(() =>
{
UMessageCenter.Instance.Publish(new MyCustomMessage { Name = "MyCustomMessage" });
});
Write a class that inherits from UBehaviour
and use the [Child]
attribute to specify child objects. The script will automatically find and cache the object at game start. Child objects can be GameObjects or Components.
If the Child attribute does not pass any parameters, it will look for a child object with the same name as the variable.
using UTools;
public class TestBehaviour : UBehaviour
{
[Child]
public GameObject childObject;
[Child]
public TextMeshProUGUI text;
}
If parameters are passed, the variable name is ignored, and the specified child object name is directly searched.
[Child("someObject")]
public GameObject childObject;
Use the [Resource] attribute to specify the resource path. The script will automatically find and cache the resource at game start.
// Find the testPrefab resource under the Resources folder and load it as a GameObject
[Resource]
public GameObject testPrefab;
// Find the Resources/Prefabs/TestPrefab resource and load it as a GameObject
[Resource("Prefabs/TestPrefab")]
public GameObject testPrefab;
Utility classes are encapsulated in a pure static class, and all methods are extension methods. You can call them by adding a .
after the corresponding type instance.
- Map: Maps a value from one range to another, ensuring the value is within the original range.
-
IsNullOrEmpty: Checks if the string is null or empty.
-
IsNotNullOrEmpty: Checks if the string is not null and not empty.
-
CheckUserName: Checks if the input string consists only of letters, digits, and underscores.
-
TrimLength: Trims the string to a specified length, appending an ellipsis if truncated.
-
CheckStrChinese: Checks if the input string consists only of Chinese characters.
-
ToBase64String: Converts the string to a Base64 string.
- ToTimeString: Converts an integer (seconds) to a time string, with optional Chinese format and custom time format.
- Tohhmmss: Converts a
TimeSpan
to a formatted string, with optional Chinese format. - CalculateTimeSpan: Calculates the
TimeSpan
between two time strings.
- FindChild: Finds a child
GameObject
by name, with options for searching all descendants and performing a fuzzy search. - GetAllChildren: Retrieves all children and descendants of a
GameObject
, including deactivated ones. - ExistsChild: Checks if a child
GameObject
with the specified name exists. - ShowOneChild: Shows only one specified child
GameObject
by name or index. - HideOneChild: Hides one specified child
GameObject
by name or index. - ToggleAllChildren: Toggles the visibility of all children
GameObjects
. - ToggleMesh: Toggles the visibility of
MeshRenderers
andSkinnedMeshRenderers
. - CloneMesh: Clones the mesh of the
GameObject
, optionally applying a new material and name. - CombineMesh: Combines the meshes of all child
GameObjects
into a single mesh. - GetMeshFilterBounds: Calculates the bounds of a
MeshFilter
attached to theTransform
, optionally including all childTransforms
. - FindNearestObject: Finds the nearest
GameObject
with a component of typeT
. - IsActiveAndMeshEnabled: Checks if a
GameObject
is active and itsMeshRenderer
is enabled. - HasComponent: Checks if a
GameObject
has a specific component. - EnsureComponent: Ensures that a
GameObject
has a specific component, adding it if necessary. - GetComponentInSelfThenParent: Gets a component from the
GameObject
or its parent. - FindChildByName: Finds a child
Transform
by name.
- ConvertColorToColor32: Converts a
Color
to aColor32
. - ConvertColor32ToColor: Converts a
Color32
to aColor
.
- ToggleAsCanvasGroup: Toggles the visibility of a
RectTransform
as aCanvasGroup
, with options for tweening and interactivity. - ToggleAsCanvasGroupAuto: Automatically toggles the visibility of a
RectTransform
as aCanvasGroup
, with options for tweening. - Show (Transform): Shows or hides a
Transform
by setting its local scale. - Show (RectTransform): Shows or hides a
RectTransform
by setting its local scale. - ToSprite: Converts a
Texture2D
to aSprite
. - ToTexture2D (Sprite): Converts a
Sprite
to aTexture2D
. - ToTexture2D (string): Converts a Base64 string to a
Texture2D
. - ToBase64: Converts a
Texture2D
to a Base64 string. - ToTexture2D (Texture): Converts a
Texture
to aTexture2D
. - DecodeBase64Image: Decodes a Base64 string to a
Texture2D
. - TweenColor: Tweens the color of a UI
Image
. - MoveOutOfScreen: Moves a UI element out of the screen in a specified direction, with options for tweening.