Right place to put the script

Hi, i have a newbie question, I have a player object that interacts with several objects on the stage, it is better to put the OnTriggerEnter script in each object or handle everything from the player script, with several if statements

Sounds like a candidate for interfaces:

interface IInteractable
{
  void Interact();
}

Interactable objects examples:

public class LightSwitch : MonoBehaviour, IInteractable
{
  bool isOn;

  public void Interact() => isOn = !isOn;
}
public class Horn : MonoBehaviour, IInteractable
{
  public AudioSource honkSFX;

  void Interact() => honkSFX.Play();
}
public class Bomb : MonoBehaviour, IInteractable
{
  public ParticleSystem explodeVFX;
  public AudioSource explodeSFX;

  void Interact()
  {
    explodeVFX.Play();
    explodeSFX.Play();
    Destroy(gameObject, 1f);
  }
}

Player interaction logic example:

public class Player : MonoBehaviour
{
  void OnTriggerEnter(Collider collider)
  {
    if(collider.gameObject.TryGetComponent(out IInteractable interactable))
    {
      interactable.Interact();
    }
  }
}
3 Likes

Just to clarify, you want things to be modular. Meaning each object should handle its own interactions. That way, if your door ever needs to work differently, you wont have to change the completely unrelated player script.

What @Vryken posted is a good example of how specifically these scripts on your objects and the TriggerEnter on your player might look like. The player code is thus extremely simply, and works for any interactable object you might add in the future. You thus never have to touch the player script when you add a new interactable object, even if it did not exist in the game before. That’s the way it should be.
Whether you add or remove a new interactable is usually none of the business of the player script.

3 Likes