Beruflich Dokumente
Kultur Dokumente
com
The problem
Let’s imagine you have a game object with a rigid body you
want to suddenly stop. You might want to do that for a number
of reasons, such as pausing your game or stopping the time.
A possible first approach is to set the relevant properties of
the rigid body (velocity, angular momentum, etc…) to zero, an
then set the property isKinematic to true. As a result your
game object will not be controlled by PhysX any more. This is
a possible way of doing it:
rigidbody2D = GetComponent<Rigidbody2D>();
// Freezes is
public void Freeze () {
rigidbody2D.velocity = Vector2.zero;
rigidbody2D.angularVelocity = 0;
rigidbody2D.isKinematic = true;
rigidbody2D.velocity = 0;
rigidbody2D.angularVelocity = 0;
rigidbody2D.isKinematic = true;
rigidbody2D.Freeze();
// Equivalent to
Rigidbody2DExtension.Freeze(rigidbody2D);
Both the class and the methods can have the name you like.
If you are using Visual Studio or any other sufficiently
advanced IDE, you’ll see that Freeze is marked as an
extension method:
Handling nulls
if (rigidbody2D == null)
return false;
rigidbody2D.velocity = 0;
rigidbody2D.angularVelocity = 0;
rigidbody2D.isKinematic = true;
return true;
Let’s improve our code by saving the state of the rigid body
so that it can be restored later:
state.velocity = rigidbody2D.velocity;
state.angularVelocity = rigidbody2D.angularVelocity;
return state;
Adding references
if (state == null)
state.velocity = rigidbody2D.velocity;
state.angularVelocity = rigidbody2D.angularVelocity;
return state;
state = rigidbody2D.GetState(state)
Other uses
return string.IsNullOrEmpty(value);
// Old version
string.IsNullOrEmpty(myString);
// New version
myString.IsNullOrEmpty();
T result = gameObject.GetComponent<T>();
if(result == null)
result = gameObject.AddComponent<T>();
return result;
return gameObject.GetComponent<T>()
?? gameObject.AddComponent<T>();
position.x = x;
transform.position = position;
return position;
// ...
// Old version
position.x = 10;
transform.position = position;
// New version
transform.ChangeX(10);
return v;
v.x = x; v.y = y;
return v;
v.x = x; v.z = z;
return v;
// ...
v.xz(5f,10f)
Conclusion
Other resources
PicosRapture: A very beefy set of method
extensions specifically designed for Unity;
For the past three years I've been dedicating more and more
of my time to the creation of quality tutorials, mainly about
game development and machine learning. If you think these
posts have either helped or inspired you, please consider
supporting this blog.