https://github.com/beatthat/safe-refs
Use safe refs to hold references to Unity components that may be destroyed. An instance of SafeRef<MyComponent>.value will be null if the component or it's GameObject has been destroyed.
https://github.com/beatthat/safe-refs
defensive-programming null-check package unity unity3d utility
Last synced: 8 months ago
JSON representation
Use safe refs to hold references to Unity components that may be destroyed. An instance of SafeRef<MyComponent>.value will be null if the component or it's GameObject has been destroyed.
- Host: GitHub
- URL: https://github.com/beatthat/safe-refs
- Owner: beatthat
- License: mit
- Created: 2017-09-09T19:06:40.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2020-02-19T06:02:23.000Z (about 6 years ago)
- Last Synced: 2025-05-15T08:40:36.592Z (11 months ago)
- Topics: defensive-programming, null-check, package, unity, unity3d, utility
- Language: C#
- Homepage:
- Size: 80.1 KB
- Stars: 1
- Watchers: 1
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
When components keep references to other components, it's easy to end up with null pointer problems. SafeRefs are a simple way to always know whether a component reference is valid.
## Install
From your unity project folder:
npm init --force # only if you don't yet have a package.json file
npm install --save beatthat/safe-refs
The package and all its dependencies will be installed under Assets/Plugins/packages.
In case it helps, a quick video of the above: https://youtu.be/Uss_yOiLNw8
## Usage
An instance of SafeRef.value will be null if the component or its GameObject has been destroyed.
```csharp
MyComponent someComponent = GetComponentsInChildren();
var ref = new SafeRef(someComponent);
// ref.value will return someComponent
Destroy(someComponent.gameObject);
// ref.value will return null
```
...SafeRefs are structs to handle them accordingly
```csharp
public class HandlesStructCorrectly
{
public void SetComponent(MyComponent c) {
m_ref = new SafeRef(c);
}
private SafeRef m_ref;
}
public class HandlesStructIncorrectly
{
public void SetComponent(MyComponent c) {
var ref = m_ref; // ref is a copy of m_ref, no longer a reference to the same thing
ref.value = c; // m_ref has not changed
// the example above is contrived
// but just to illustrate the point
// that you need to be careful
// to avoid editing copies of struct
}
private SafeRef m_ref;
}
```