Define a unified object search interface in Unity.

Source: Internet
Author: User

Define a unified object search interface in Unity.

We often need to search for objects in Unity in various ways. For example, search by name, tag, layer, or search for objects whose names start with xxx.

This article describes how to search for objects using a unified interface.


1. Define a unified search interface

/// <Summary> /// game object search interface /// </summary> public interface IGameObjectFinder {// <summary> /// search /// </summary> /// <param name = "root"> Start position of the Search/root node </param> /// <param name = "findResult"> result of the search </ param> void Find (Transform root, list <Transform> findResult );}

2. Define a method to use the above search interface
Public class Finder {// <summary> /// find the Transform that matches the specified Finder under the specified root node and keep it in findResult. /// </summary> /// <param name = "root"> </param> /// <param name = "findResult"> </param> /// <param name = "finder"> </ param> public static void Find (Transform root, list <Transform> findResult, IGameObjectFinder finder) {if (root = null) {throw new Exception ("root can not be null, it defines the starting point of the find path ");} if (findResult = null) {throw new Exception (" findResult can not be null, it used to collect the find result ");} if (finder = null) {throw new Exception (" finder can not be null, it defines how to find transform ");} finder. find (root, findResult );}}

As you can see, step 2 simply calls the interface of step 1 for search. But 1 is only an interface. What is the purpose? Next, let's take a look.
3. Implement an interface for finding a component
/// <Summary> /// search by component /// </summary> /// <typeparam name = "T"> </typeparam> public class GameObjectFinderByComponent <T>: IGameObjectFinder where T: Component {public void Find (Transform root, List <Transform> findResult) {foreach (var componentsInChild in root. getComponentsInChildren <T> () {findResult. add (componentsInChild. transform );}}}

You can see that you only need to implement IGameObjectFinder. So how should I call it at this time? For example, you want to find the Rigid Body component under the transform and save it to the result. As long as: Finder. Find (transform, result, new GameObjectFinderByComponent <Rigidbody> (); what? It seems a little complicated. Isn't it okay to use GetComponentsInChildren directly? Do not rush. Let's continue to look at other search requirements. For example, I want to find an object named xxx.
4. Implement an iterative search. First, you need to search for all nodes with a name under a specified node (regardless of the depth), which needs to be traversed. Then, we can first Abstract An traversal interface. To ensure unified search, we still inherit from IGameObjectFinder.
/// <Summary> /// iterative search /// </summary> public class metadata: IGameObjectFinder {private IGameObjectFinderForIteration finderForIteration; public metadata (IGameObjectFinderForIteration finderForIteration) {this. finderForIteration = finderForIteration;} public void Find (Transform root, List <Transform> findResult) {for (int I = 0, childCount = root. childCount; I <childCount; I ++) {Transform t = root. getChild (I); if (finderForIteration. isVaild (t) {findResult. add (t) ;}find (t, findResult );}}}
This Code indicates that each subnode under the Start Node is used to determine whether it meets the requirements through the IGameObjectFinderForIteration interface. If yes, it is added to the result list. Search for other subnodes under this subnode. (This search does not include the first Start Node)
The IGameObjectFinderForIteration interface is also simple:
/// <Summary> /// iterative search judgment /// </summary> public interface IGameObjectFinderForIteration {// <summary> /// specify whether the node is valid /// </summary> /// <param name = "node"> </param> // <returns> </returns> bool isVaild (Transform node );}
All right, this means that if we want to find all the sub-nodes under a root node (both direct and indirect), we only need to implement an IGameObjectFinderForIteration. So OK. See how to search by name.
/// <Summary> /// search by NAME for iterative traversal /// </summary> public class FinderForIterationByName: IGameObjectFinderForIteration {protected readonly string name; public FinderForIterationByName (string NAME) {NAME = name;} public bool isVaild (Transform getChild) {return getChild. gameObject. name. equals (NAME );}}

It is easy to use. Add an object named "abc" under the transform node and save it in the result list. As long as this is the case: Finder. Find (transform, result, new GameObjectFinderByIteration (new FinderForIterationByName ("abc ")));

5. What is the purpose? A lot of people may not understand what the use is, through the above abstraction. You can Find that all searches are unified into: Finder. Find (transform, result, objectFinderImpl); 1. The code is unified, no matter how complicated your search conditions are. It facilitates code management, maintenance, and expansion. 2. configurable: You can simply associate numbers with different searchers, and then pass the included parameters to a specific searcher to search by using different searchers in the configuration text. This is very useful when you are a beginner, because planning may sometimes put a xxx finger on what icon and button. Then you can submit the search to the planner for configuration ~ 3. If you haven't understood what the use is, ignore it. You will be back one day.









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.