Practical C # extension methods in Unity

Source: Internet
Author: User


Unity built-in components are basically not inheritable. Some of the features that are commonly used but are not defined by the existing API can be implemented using the C # Extension class method (note that the extension method does not pass a reference to a value type, so the original object cannot be modified, and passing a large value type can cause performance problems). Here are some of the more practical extension methods, the implementation of these extensions are many use C # delegates, about delegates can refer to here: C # delegate, Lambda and event.
Extended Transform
Each gameobject contains a Transform component (the newly introduced Recttransform inheritance Transform in Ugui), and the Gameobject hierarchy is also owned by Transform.
Summary
(depth first) traverse the Transform level to perform a custom operation on each of the accessed nodes
/summary
param name= "Root" traverses the beginning of the root Transform object/param
This method is called when the Param name= "operate" traverses to each node; Parameter 1: The object currently being accessed; Parameter 2: Residual depth limit including this level/param
param name= "depthlimit" traversal depth limit, negative means no limit, 0 means access to root itself without access to its children, positive values represent the maximum number of child layers visited/param
public static void Traversehierarchy (this Transform root, actiontransform, int operate, int depthlimit =-1)
{
if (operate! = NULL)
{
Operate (root, depthlimit);
if (Depthlimit = = 0) return;
for (int i = root.childcount-1; i = 0; i--)
{
Traversehierarchy (Root. Getchild (i), operate, depthLimit-1);
}
}
}
Summary
(depth first) traverse the Transform hierarchy to perform a custom operation on each accessed node, and if this operation returns a non-null reference, the traversal process is terminated, and the return value is ultimately the return value of the traversal method
/summary
param name= "Root" traverses the beginning of the root Transform object/param
This method is called when the Param name= "operate" traverses to each node; Parameter 1: The object currently being accessed; Parameter 2: The remaining depth limit, including this level; Return value: null means to continue the traversal, and a non-null reference terminates the traversal process, and this return value is ultimately the return value of the traversal method/param
param name= "depthlimit" traversal depth limit, negative means no limit, 0 means access to root itself without access to its children, positive values represent the maximum number of child layers visited/param
Returns a non-null reference or Null/returns returned for the first time operate
public static Object Traversehierarchy (this Transform root, functransform, int, object operate, int depthlimit =-1)
{
if (operate! = NULL)
{
Object obj = Operate (root, depthlimit);
if (obj! = NULL | | depthlimit = = 0) return obj;
for (int i = root.childcount-1; i = 0; i--)
{
obj = Traversehierarchy (root. Getchild (i), operate, depthLimit-1);
if (obj! = null) return obj;
}
}
return null;
}

Both of these extension methods use recursive implementations, all of which can traverse all sub-objects. A typical usage scenario for the first extension method is to change the Layer of all sub-objects, and the second extension method with a return value can terminate the traversal at any time, typically by searching for a specific sub-object and returning its reference.
Extended Monobehaviour
using a co-process in Unity can sometimes make the program more concise. For example, using a co-process can easily delay the execution of some code. The Monobehaviour built-in Invoke supports only string parameters, and the following extension can use delegates.
Summary
Delay invokes the specified method
/summary
param name= The Script object attached to the "Monobehaviour" thread/param
param name= "seconds" delay number of seconds/param
Param name= "method" delay end of call methods/param
public static void Invoke (this monobehaviour monobehaviour, float seconds, Action method)
{
if (Method! = null)
{
Monobehaviour.startcoroutine (Delaycall (seconds, method));
}
}
private static IEnumerator Delaycall (float seconds, Action method)
{
Yield return new waitforseconds (seconds);
Method ();
}
If you need to wait for the UI animation to finish and then open the input, you may be able to use this later.
Extended Camera
If you are doing 2D games, you may need to understand clearly the relationship between your sprite and the size of your screen. The following two extensions make it easy to get the coefficients of conversion between pixels and world units.
Summary
Calculates the size of the world unit (in meters) per pixel on an orthographic camera screen
/summary
param name= "camera" orthogonal camera object/param
Returns per pixel of world unit size/returns
public static float Unitsperpixel (this camera camera)
{
return camera.orthographicsize * 2/screen.height;
}
Summary
Calculates the pixel size of each world unit (units: meters) on an orthographic camera screen
/summary
param name= "camera" orthogonal camera object/param
Returns the pixel size per world unit/returns
public static float Pixelsperunit (this camera camera)
{
return screen.height * 0.5f/camera.orthographicsize;
}

The pixel size of different screens varies greatly, and you may need to convert the pixels to world size to determine the user's operating intentions when dealing with touch-screen input.
Extended Reflection Method
Unity's customizable editors improve efficiency for development, but they often encounter problems with their use. For example, the editor class needs to access the private members of the editing object. The following reflection-related methods can sometimes be used to solve these problems.
Summary
Reflection extension
/summary
public static Class Reflectionextension
{
public static Object Getprivatefield (This object instance, string fieldName)
{
return instance. GetType (). GetField (FieldName, BindingFlags.Instance | BindingFlags.NonPublic). GetValue (instance);
}
public static Object Getprivateproperty (This object instance, string propertyname)
{
return instance. GetType (). GetProperty (PropertyName, BindingFlags.Instance | BindingFlags.NonPublic). GetValue (instance, null);
}
public static void Setprivatefield (This object instance, string FieldName, Object value)
{
Instance. GetType (). GetField (FieldName, BindingFlags.Instance | BindingFlags.NonPublic). SetValue (instance, value);
}
public static void Setprivateproperty (This object instance, string propertyname, Object value)
{
Instance. GetType (). GetProperty (PropertyName, BindingFlags.Instance | BindingFlags.NonPublic). SetValue (instance, value, NULL);
}
public static Object Invokeprivatemethod (This object instance, string methodName, params object[]
Param
{
return instance. GetType (). GetMethod (MethodName, BindingFlags.Instance | BindingFlags.NonPublic). Invoke (instance, param);
}
}
statement: This document comes from the "Dog Planing Learning Network" Community-unity Extreme College, is a self-published Unity3d study articles, if anything violates your relevant interests, please communicate with the official, we will deal with the real-time.

Practical C # extension methods in Unity

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.