SetActive(false) in Start does not seem to work
Hi,
I have a simple script attached to the canvas, which is trying to hide an UI object (child of the canvas) in the Start function of the script.
I know the object is linked correctly because when I deactivate it before going into run time, I can activate it with the button which has the callback to set it active.
Is it a possible issue that when the canvas is created, the gameobject "Gerer" does not yet exist, so I would need to set up a coroutine ? This would be very surprising to me (I expect all objects are created before scrips are executed, but this is the only explanation I found.
Any ideas welcome !
public class MainScreenManager : MonoBehaviour
{
[SerializeField] GameObject uiGerer;
void Start()
{
uiGerer.SetActive(false);
}
public void Gerer()
{
uiGerer.SetActive(true);
}
}
Answer by Grumphh · Sep 19, 2020 at 05:14 PM
@WeirdBeardDev Thanks a lot for your reply ! It helped me find out what was the issue.
The code actually does work... The issue is that I had simplified it before posting it and the problem came from something I removed.
The complete code looked something like that:
public class MainScreenManager : MonoBehaviour
{
[SerializeField] GameObject uiGerer, uiAcheter;
void Start()
{
uiAcheter.SetActive(false);
uiGerer.SetActive(false);
}
public void Gerer()
{
uiGerer.SetActive(true);
}
}
Now, uiAcheter was not initialized, and gave a null reference exception. What surprised me is that when the exception was thrown, it looks like the execution of the rest of Start was stopped, and so uiGerer.SetActive was not called.
If I replace the two lines of Start by
if (uiAcheter)
uiAcheter.SetActive(false);
if (uiGerer)
uiGerer.SetActive(false);
Then it works fine.
I guess this teaches you good habits to test for null references even though you plan to link the objects in the editor...
Defensive program$$anonymous$$g is always good. Glad everything worked out.
Answer by WeirdBeardDev · Sep 19, 2020 at 03:44 PM
All objects are already created by the time Start() is called. See Order of Execution of Event Functions for details on when the MB events are called. Based on your description I'm not sure why the gameObject is not hiding. Here are some simple double-checks, make sure you are referencing the gameObject in the scene (Hierarchy) and not the Project. Make sure there are no other objects that change uiGerer's active status. For example, if another Start() method sets it to true, that would be an issue as by default the Start() methods are called non-deterministically.
Barring all that a simple fix is to the the gameObject off in the Editor, then it starts off. This will fix the problem, however, it won't help fix the solution.
Your answer
Follow this Question
Related Questions
UI Text: Words at end of line jumping to next line 0 Answers
ui Text not responding to collider 1 Answer
Image UI not enabling C# SOLVED 1 Answer