First game object has a script to find second game object using FindGameObjectWithTag() function. The function’s called in Awake() function.
Second game object has a script to deactivate it using SetActive(false). It is called in Start() function. And second game object is active when scene first opened.
Second game object should be inactive initially in the scene, active when first object is triggered.
I use the script to deactivate it because FindGameObjectWithTag() function can only find active game objects.
This method is working in editor perfectly. But when I built the game it seems the game object cannot be found with tag. How can I fix this issue? I don’t want to make the GameObject variable public and manually select the object because I used this method in multiple occasions.
Thanks for the advices.
Edit:
The code below solved the issue.
Instead of the script in second object:
void Start()
{
gameObject.SetActive(false);
}
wrote this
void Start()
{
StartCoroutine(DeactivateAfterFrame());
}
IEnumerator DeactivateAfterFrame()
{
yield return null; // Wait for the next frame
gameObject.SetActive(false);
}
If these objects both live in the same scene, this is 100% what you should be doing. Direct references is by far the best way to reference and communicate between components.
That’s The Unity Way ™… do it… embrace it. Love it.
Your choices are:
do it the Unity way and have it work 100%
do it crazy wild GetComponent / FindType way in code
Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.
Here’s the bare minimum of stuff you absolutely MUST keep track of if you insist on using these crazy Ninja methods:
what you’re looking for:
→ one particular thing?
→ many things?
where it might be located (what GameObject?)
where the Get/Find command will look:
→ on one GameObject? Which one? Do you have a reference to it?
→ on every GameObject?
→ on a subset of GameObjects?
what criteria must be met for something to be found (enabled, named, etc.)
If you are missing knowledge about even ONE of the things above, your call is likely to FAIL.
This sort of coding is to be avoided at all costs unless you know exactly what you are doing.
Botched attempts at using Get- and Find- are responsible for more crashes than useful code, IMNSHO.
If you run into an issue with any of these calls, start with the documentation to understand why.
There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.
In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.
It is ALWAYS better to go The Unity Way™ and make dedicated public fields and drag in the references you want.