'Can I disable the logging of a specific GameObject without modifying its script in Unity?

For example, I have a GameObject A with the following script

public class A: MonoBehaviour
{
    private void Update()
    {
        Debug.Log("Log something");
    }
}

Can I disable the logging of A in another script so that the log of A is not shown in the console? I do not want to modify script A.

public class B: MonoBehaviour
{
    private void Start()
    {
        // Something like this
        FindObjectOfType<A>().DisableLogging();
    }
}

Is this idea viable?

Thank you very much.



Solution 1:[1]

Based on the previous discussions, I think the answer to this problem is no.

Solution 2:[2]

Dependency inject your logging.

public interface ILogger _logger {
   void LogMessage(string message);
}

public class Logger : ILogger {
   public void LogMessage(string message)
   {
      Debug.Log(messsage);
   }
}

public class NoLogging : ILogger {
   public void LogMessage(string message)
   {
      //does nothing
   }
}

public class SomeObject {

  private ILogger _logger;

  public SomeObject(ILogger logger) {
      _logger = logger;
  }

  public void start()
  {
     _logger.log("Whatever");
  }

}

public class Program 
{ 
    public static void Main(string args) 
    {
        SomeObject objA = new SomeObject(new Logger());
        SomeObject objB = new SomeObject(new NoLogging());
    
        objA.Start();
        objB.Start();
    
    }
 }

Now if you have created an instance of SomeObject with a "Logger" in the constructor, it will now log the specific instance's data.

if you create an object with the "NoLogging" instance instance in the constructor, nothing will happen when logging is called.

EDIT: I didn't check this code compiles. So treat it as pseudo code.

Uh, also, if you need to make some logic for when an instances needs to have logging or not, (Or more verbose logging or not) Simply use the factory pattern to generate your "SomeObject"'s based on said logic.

Solution 3:[3]

You can have a private boolean variable for MonoBehaviour A, EnableLogging and check if it's true before it logs anything.

public class A: MonoBehaviour
{
    private bool EnableLogging = true;
    public void SetLogging(bool value) { EnableLogging = value; }

    private void Update()
    {
        if (EnableLogging) { Debug.Log("Log something"); }
    }
}

then from another script

public class B: MonoBehaviour
{
    [SerializeField] private A a;
    private void Start()
    {
        a.SetLogging(false);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yuchen
Solution 2
Solution 3 Mathias