I have a script called NPC that includes a method that should be called only once when my game object is triggered but it happens twice, and I suspect that my another script(Player) that is in the same game object and inherits the same class as NPC, run the codes even though it is not active. Does this even possible?
two scripts as components of same game object.
These are my scripts on the inspector which are SetActive false as default, and only one of them will be enabled = true when my game begins.
public virtual void OnTriggerEnter(Collider other)
{
IInteractable interactable = other.GetComponent<IInteractable>();
if (interactable != null && other.gameObject.CompareTag(gameObject.tag) )
{
if (other.gameObject.CompareTag("blue"))
{
blueBrickList.Add(other.gameObject);
}
else if (other.gameObject.CompareTag("green"))
{
greenBrickList.Add(other.gameObject);
}
else if (other.gameObject.CompareTag("red"))
{
redBrickList.Add(other.gameObject);
}
interactable.Interact();
Debug.Log("interacted");
}
}
and here is my base abstract class' OnTriggerEnter method.
Below here is what I have in both NPC and Player scripts.
public override void OnTriggerEnter(Collider other)
{
StackParent = stackParent;
RefObject = refObject;
base.OnTriggerEnter(other);
}
As I said before, only one of the scripts is enabled true when the game begins. So Why is it typing "interacted" twice in a row and also running Interact method twice as well. Am I missing something? I don't even know if I explain it well. Please help me :/
CodePudding user response:
Yes unity does not care whether the component is disabled or not, if the component implements the OnTriggerEnter
then unity will call it when trigger conditions matched. You can either change your design to prevent it or just add an if condition at the beginning of the method like
private void OnTriggerEnter(Collider other)
{
if (!enabled) return;
}
Additionally, components' checkboxes are for below functions only:
- Start()
- Update()
- FixedUpdate()
- LateUpdate()
- OnGUI()
- OnDisable()
- OnEnable()
from unity's documentation you can check more details.