Findgameobjectswithtag



Unity findgameobjectswithtag

Finding and referencing a game object properly in Unity3D is one of the most asked questions for those who are new to Unity3D. In this article, I will write about referencing game objects, finding them according to their names, tags, and types. But let me give you the answer to the question at the title briefly.

In Unity3D, we can find game objects according to their names, tags, and types. For these purposes, we use the following methods respectively: GameObject.Find( ), GameObject.FindWithTag( ) and Object.FindObjectOfType(). These methods will return only one game object. Additionally, it is also possible to find all the game objects that have the same tag or are in the same type, using GameObject.FindGameObjectsWithTag( ) and Object.FindObjectsOfType( ). These methods will return arrays of game objects.

Findgameobjectswithtag Getcomponent

In this article. Static member 'member' cannot be accessed with an instance reference; qualify it with a type name instead. Only a class name can be used to qualify a static variable; an instance name cannot be a qualifier. For more information, see Static Classes and Static Class Members. The following sample generates CS0176. UnityEngine Module GameObject Class CreatePrimitive Method GetComponent Method GetComponent Method GetComponentFastPath Method GetComponentByName Method GetComponent Method GetComponentInChildren Method GetComponentInChildren Method GetComponentInChildren Method GetComponentInChildren Method GetComponentInParent Method GetComponentInParent. Watch All C# Tutorials Here: 10 Games & Apps With Unity & C#: - ( Click On Show More ) -. Tags must be declared in the tag manager before using them. A UnityException is thrown if the tag does not exist or an empty string or null is passed as the tag. Note: This method returns the first GameObject it finds with the specified tag. If a scene contains multiple active GameObjects with the specified tag, there is no guarantee this method will return a specific GameObject.

Contents

  • Referencing game objects in Unity3D

Referencing game objects in Unity3D

What is referencing?

Most of the time, we want to access other game objects and their components. Hence, we can gather information about them when it is required, send information to them, control their behaviors, or execute a method that is in a script that is attached to them. In these cases, we need an address(or let’s say a phone number) of the game object and thus, we can dial whenever we want. This is called referencing.

While developing games in Unity3D, we always reference other game objects or components. Therefore, this is a fundamental topic you should understand before you go further.

How to create references to game objects or components

First of all, we have to declare variables that will store the address of the game objects or components. And hence, whenever we would like to access the properties of these game objects or components, we use these variables.

In the code above, we declared two variables in type GameObject but we have not assigned any object them yet. You may consider this as if we are reserving empty rows in an address book that we will fill them out later.

To reference these variables, we have a couple of options. We can search the game object that we want to assign using built-in methods that are included in Unity. We will see this option in later sections of this article. Another option is to assign relevant game objects directly in the Unity editor. But to do this we have to declare the objects either public or private with [SerializeField] attribute.

In the code above, the first variable is declared as private(you can put the private keyword in front of it as well if you want), the second variable is declared as public and the third variable is declared as private with [SerializeField] attribute. [SerializeField] attribute makes this variable visible in the editor but still inaccessible from other scripts.

Now, you can drag and drop the game objects, that you would like to assign, to the slots that are visible in the inspector.

Findgameobjectswithtag

If you would like to create references to the components that are associated with the game objects, you need to declare variables that are in the type of that component.

How to find game objects by their names

As I mentioned above, we can create references to game objects and components by searching and finding them using built-in methods in Unity. This is useful especially when you want to stay the variable private or when you want to access an object that is created during runtime.

In order to search for a game object that has a specific name in the scene, we have to use the method GameObject.Find( ). It takes a string parameter. And this parameter is the name of the game object that we want to find.

In the code above, we created a reference for the game object that has the name “Sphere”.

If you would like to access a component that is attached to this game object, you should create a reference for that component. For instance, the following creates a reference for a rigidbody component that is attached to this game object, and hence you can access the properties of this component.

Finding a game object that has a specific tag

In addition to finding an object by its name, we can also find it by its tag which we are able to determine objects in the scene.

To find a game object that has a specific tag, we use the method GameObject.FindWithTag( ). This method takes a string parameter and searches for it (There is one more method that does the same job. You can also use GameObject.FindGameObjectWithTag( ) for the same purpose).

A tag can be used either for only one object or multiple objects. If there is more than one object that has the same tag, this method returns only one of them.

Getting the array of all game objects that have the same tag

If there are multiple objects that have the same tag and we want to get them all, we need to use the method GameObject.FindGameObjectsWithTag( ). Likewise, this method also takes a string parameter and returns an array of all game objects. Therefore, we have to declare an array that will store the game objects.

The following returns and assigns all objects that have the tag “Cube”.

Finding a game object that matches a specific type

We can also search and find a game object that matches a specific type. In other words, for instance, we can get a game object or component that has a specific component. To do this, we use the method Object.FindObjectOfType( ). This method also returns only one of the objects.

The following one finds a light component and creates a reference to it.

Findgameobjectswithtag multiple tags

Getting the array of all game objects that match a specific type

Unity Gameobject Findgameobjectswithtag

If there are multiple game objects that match a specific type, we can find all of them and create references in an array. For this purpose, we use the method Object.FindObjectsOfType( ). This is an example of how we use it:

How to find a child game object

In order to find a child object and create a reference to that child object we can use the method Transform.Find( ). This method takes a string parameter and returns the child game object that the name matches this parameter.

Unity

Assume that there is a game object in the scene that has a tag “Player”. And also assume that this player object has a child game object which has the name “Gun”. If we want to create a reference for the “Gun” object, we may do this as the following:

This is useful especially if there are multiple objects that has the same name under different objects.

Further remarks

In this article, we see different ways of how we reference game objects in Unity3D. Here, I need to warn you that searching and finding methods are extremely slow and you should avoid using them in Update, FixedUpdate, or LateUpdate methods, if possible. We generally use them in Start or Awake methods. You may also consider creating references in Singleton’s to improve performances. We have various tutorials about the Unity3D Engine that you can see in this link.

We already discussedGame Objects andComponents as twoof the fundamental building blocks of the Unity Engine. Today, we’ll discusstheir programmatic representation.

This is Unity for Software Engineers,a series for folks familiar with software development best practices seeking anaccelerated introduction to Unity as an engine and editor. More is coming overthe next few weeks, so consider subscribing forupdates.

Findgameobjectswithtag

The Unity Engine runtime is primarily written in C++, and much of the Engine’sprimitives (such as the game objects and their components) live in C++ land.You’ll also know that the Unity Engine API is in C#. The API gives you accessto all of Unity’s native objects in a way that—save for a few pitfallswe’ll discuss today—feels like intuitive, idiomatic C#.

UnityEngine.Object

At the top of the Unity Object hierarchy sits UnityEngine.Object. For themost part provides a name string, an int GetInstanceID() method, and a bunchof equality comparers.

The class also provides a static void Destroy(Object obj) method (and someoverloads) that destroys a UnityEngine.Object and any of its subclasses. Whenan Object is destroyed, the native part of the object is freed from memory,and the smaller managed part will be garbage collected at some point afterthere are no more references to it.

Because your valid reference to a UnityEngine.Object can point to a destroyednative object, UnityEngine.Object overrides C#‘s operator and operator!=to make a destroyed Object appear null. Simply accessing methods on adestroyed object will return NullReferenceException, albeit with a friendliererror message that tells you which object you were trying to access.

GameObject

A GameObject derives from Object and represents anything in your scene.

Let’s start at a high-level: A GameObject inherits a name and instance ID fromits parent. Otherwise, conceptually, a GameObject

  • has a list of Components on it,
  • has a tag string for organizational purposes, and
  • belongs to a layer.

A GameObject’s state

  • is the product of all of its Components’ state, and
  • whether an object is active or not.

Let’s dig a bit deeper. When starting, most of the interesting stuff in aGameObject is in its Components. A GameObject has at least one Component:its Transform. ATransform describes the position and rotation of the GameObject. A Transformincludes helper properties that show an object’s absolute world position androtation, as well as the position and rotation relative to its parent. In theEditor, the Transform position and rotation are set from the parent relativevariants.

Since every GameObject has a Transform (and also, given that a Transform isfrequently needed/accessed), the GameObject directly exposes aTransform transform public property.

You can access individual components from T GetComponent<T>(), or lists ofcomponents from T[] GetComponents<T>(), etc. These methods search through allcomponents on a GameObject and return ones with a compatible type (or null, ifnone exist in the singular case). Since these methods search through componentsand check type compatibility, it is often recommended to cache this lookup.

If you are building/extending a GameObject by hand, you can always useT AddComponent<T>(). In most cases, however, you’re better off using theEditor.

Individual Objects (a Component or ScriptableObject) might refer to otherGameObjects in a few ways:

  • By reference. By exposing a GameObjectserialized field that youthen set from the inspector.

    We have discussed serialization extensively throughout the series:as a fundamental conceptand in our tour of the Editor, whendescribing the Inspector,and the practice of usingthe Inspector as an injection framework.

  • Using tags. Every Game Object can have a tag string. You can findobjects in the scene using that tag through the static functionsGameObject.FindGameObjectsWithTag and GameObject.FindGameObjectWithTag.A GameObject also exposes a public bool CompareTag(string tag) method.

    This is a quick-and-dirty way to get the job done, but is still a popularway. A common use of this in the wild is to have a 'Player' tag to findthe Player. Ideally, these methods should not be called every frame, so ifyou have to use them, consider caching the result.

  • Using layers. A layer is an int between 0 and 31. Every Game Object isin exactly one layer.

    While you can’t directly look up all objects in a layer, if you already havea reference to a GameObject (e.g., in a collision event), you can check aGameObject against aLayerMask. ALayerMask is typically used in functions like Physics.Raycast(). Thisallows you to find objects with colliders intersecting with a given ray.Passing a LayerMask to Physics.Raycast() will only return objects withinthe specified set of layers.

    Inside the Unity Engine, Cameras make heavy use of layers. E.g., you canhave one camera that renders “everything but UI”, and overlay another camerafor an in-game HUD, etc.

  • Using indirect references. There are many reasons why the methods abovemight be insufficient: you might not want to use tags to avoid depending oncopy-pasted strings, and layers might not fit your use case. If referencinga fellow object in-scene is not an option (e.g., you’re dealing with adynamic set of objects or don’t have access to the current scene objects inthe context you need this reference, etc.), then you might want to lookfurther.

    For this, an increasingly popular concept is runtime sets ScriptableObjects. You can read more about this in Unity’s how-to article onarchitecting your game with ScriptableObjects,based on the talk by RyanHipple. If you have an hour to spare, you might want to watch the wholething.

A GameObject also exposes a BroadcastMessage and SendMessage functions thatpropagate messages (described in the Component section) toall components in or under it.

Component

Unity defines the behaviors of game objects through the composition of theseComponent classes. This is a core tenet of what game engines refer to as anEntity Component System (ECS). TheRipple blog has an applied overview ofECS, and Robert Nystrom’s Game Programming Patternsdescribes entity component systems in detail.Confusingly, Unity refers to their next-generation high-performance gameprogramming paradigm asECS, which isalso ECS-based but takes things to the next level with data-oriented design.

From the outside looking in, both Unity’s MonoBehaviour-based paradigm andUnity ECS are entity component systems, though how you use them differsubstantially.

Every behavior on a GameObject is driven through its Components.User-implemented Components will usually extend the MonoBehaviour subclass(more on that later).

A Component inherits a name and instance ID from its parent. Otherwise,conceptually, a Component

  • always belongs to a single GameObject, exposed as a publicGameObject gameObject property, and
  • can receive messages, driving much of its behavior.

The state of a component on an active GameObject lies entirely in itsimplementation.

In addition to its GameObject, a component exposes shorthand properties andmethods such as Transform transform, T GetComponent<T>(), etc. These aresimply convenience shorthands for accessing those same methods on thecorresponding gameObject.

The most important functionality of a Component is driven through UnityMessages (also sometimes called Unity Event Functions when referring tobuilt-in messages). These are effectively callbacks functions triggered by theEngine in certain situations. Every Component will receive a Awake(),Start(), Update() and other messages, for example. The Unity Docs on theOrder of Execution ofthese messages is a convenient resource.

To have your component receive a particular message, simply add aprivate void method with the appropriate message name. The runtime will usereflection to call these messages, when applicable. This is why you don’t see anoverride directive on these messages. Messages like Update, LateUpdate,and FixedUpdate are inspected once per type, so don’t worry about reflectionbeing used in every frame. See more details in the”10000 Update() calls”Unity blog post for more information.

A Behaviour is a type of component that can be enabled or disabled. Whena Behaviour is disabled, Start, Update, FixedUpdate, LateUpdate,OnEnable, and OnDisable messages are not called.

A MonoBehaviour is a Behaviour that also enables usingCoroutines.

A Note on Inactive Objects and Disabled Components

A GameObject in a loaded scene will exist in memory until the object isDestroyed explicitly or the scene is unloaded. A GameObject can be set toinactive, which will cause it to stop receiving Update (and related) events.

When an object is created, the messages called on a component depend onif: (1) the GameObject is active, and (2) the component is enabled:

GameObject is activeGameObject is inactive
Component is EnabledAwake, OnEnable, StartComponent implicitly disabled
Component is DisabledAwakeAwake

When an object is set to active or a Behaviour is set to enabled:

  • OnEnable will be called.
  • If Start has never been called on this Behaviour, it will be calledexactly once.

Takeaways

Some takeaways of all this:

  1. A Unity object might appear to become null when destroyed. nullchecking does more than you think.
  2. As a result, null-coalescing operators (??, ??=) and null-conditionaloperators (?., ?[]) don’t work as expected.
  3. Yes, your Unity Messages can be private!
  4. Don’t create abstract classes that unnecessarily declare Update or othermessages to make overriding easier; that’ll result in the engine alwayscalling these events.
  5. Disabling an Object or Component is a great way to limit its game logic orsave on CPU-bound effort, but these objects still have a memory overhead.