Hi, I'm new, can you tell me if this code to activate and deactivate a gameobject from code is right?

{
    public GameObject prefabFoglie;

    public void NascondiOggetto()
    {
      
        if (prefabFoglie.activeSelf)
        {
            
            prefabFoglie.SetActive(false);
        }
        else
        {
            prefabFoglie.SetActive(true);

Yes, albeit slightly truncated.

Who TF are these trolls?

Because you are new… Try to include as much of the class as possible unless it is huge in which case you might need to truncate some methods.

“Is right” is an ambiguous concept. Will it work, probably does that mean that it is “right”? Is it great code, no. Why because it is a simple toggle. Simple toggles aren’t going to be examples of great code.

That all said, what you are doing is checking a Boolean property prefabFoglie.activeSelf and setting that property to the opposite. The following should do it.

prefabFoglie.SetActive(!prefabFoglie.activeSelf);

well that’s certainly simpler than what I’ve been doing too… thanks…

If this is a GameObject in the scene, rename that field.

If this is the actual prefab, then you’re only changing that.

More generally…

Instancing and prefabs in Unity and naming your variables:

If you name your public / serialized fields (variables) as simply “thing” then you set yourself up for confusion.

If something is a prefab, name it that, such as public GameObject ThingPrefab; and only drag prefabs into it. Prefabs are “dead things (assets on disk) waiting to be Instantiated.”

If something is already in the scene or you Instantiate<T>() it in code, then store the result in a properly-named variable such as private GameObject ThingInstance;

Naming is hard but important to reduce your own confusion.