#findgameobjectwithtag in if statement
1 messages · Page 1 of 1 (latest)
You don't
Don't use Find methods!
Find methods in Unity are an often-tempting solution to referencing a scene object. However, there is always a better solution.
Whenever you call a Find method, Unity must traverse your entire scene hierarchy and check every single object until it finds a match; and the methods which return arrays will always traverse the entire hierarchy regardless.
This is inefficient! It means that the more objects you add to your scene, the slower these methods become; and it gets even worse if you are calling them multiple times.
A non-exhaustive list of Find methods to avoid:
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
To read about a better solution, type []getareference or []getref
so im checking if a gameobject with the ui tag is active or not
how do i do that
Read the bot response
im sorry do i type that here 😅
You can type it here, or #bot, doesn't matter which
How to get a reference
"How do I access a variable from another script?" is usually one of the first questions we ask when learning Unity. Whether you are C# beginner or a C# professional, understanding the way Unity does things differently can be confusing.
🌳 If the objects are already present in the scene hierarchy...
... then you can use the SerializeField attribute on a field, and assign it by dragging the object which has the script you want to access onto the field slot. This also works if the two scripts are on the same object.
[SerializeField] private SomeScript someScript;
If the objects are instantiated prefabs...
... then you can use a form of injection after you call Instantiate:
SomeScript.cs
public GameManager TheManager { get; set; }
GameManager.cs
var clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().TheManager = this;
how do i use this in an if statement tho
yeah i can use use getcomponent and stuff but how do i check if an object with a specific component is active or not
There are two ways of checking a GameObject's state:
activeSelfwill tell you whether the object itself is set active (likeSetActive(true)would do).activeInHierarchywill tell you whether the object itself, as well as all of its parents are enabled.
Both of those are documented quite well by the way; I would strongly recommend you consult the Unity docs for questions like this.
https://docs.unity3d.com/ScriptReference/GameObject.html
nvm i solved it