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

Time:03-07

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.

CodePudding user response:

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);
    }
}

CodePudding user response:

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.

  • Related