Search Unity

Question Changing Variable From OnTriggerenter

Discussion in 'Getting Started' started by iamthebubb, Jan 20, 2023.

  1. iamthebubb

    iamthebubb

    Joined:
    Jul 21, 2016
    Posts:
    73
    Hey I just wanted some clarification on this problem

    I have a script attached to an instatiated prefab enemy. I am trying to change a variable once the trigger is triggered, lets say

    Code (CSharp):
    1. public int maxEnemyAttack;
    2.  
    3. void Start()
    4. {
    5.    maxEnemyAttack = 0;
    6. }
    7.  
    8. private void OnTriggerEnter(Collider other)
    9. {
    10.    maxEnemyAttack++;
    11. }
    12.  
    But the maxEnemyAttack++ only seems to effect the current enemy and when the next enemy enters, the value will start at zero again, can someone explain what is happening? And how to solve this issue?

    Thank you
     
  2. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    490
    The code behaves exactly with the programming logic. You create a prefab with a script, you create a copy of it. Each copy has its own maxEnemyAttack.

    The simplest solution to do this.
    Code (CSharp):
    1. //public int maxEnemyAttack;
    2. public static int maxEnemyAttack;
    The longer solution is to create a separate EnemyManager class that holds the counter and adds more enemies by the Instantiate. This second class doesn't need to have this static value.
    Code (CSharp):
    1. private void OnTriggerEnter(Collider other)
    2. {
    3.    enemyManager.AddEnemy();
    4. }
     
  3. iamthebubb

    iamthebubb

    Joined:
    Jul 21, 2016
    Posts:
    73
    Thanks I will try these later on. I did think of having another script to handle the variable but seemed like overkill

    Thank you