Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Unity - Actions Being Called Twice - OnTriggerEnter, OnClick, EVERYTHING?

Discussion in 'Scripting' started by KrakenKoders, May 11, 2022.

  1. KrakenKoders

    KrakenKoders

    Joined:
    Jun 11, 2014
    Posts:
    6
    So I'm creating a Sheep Counter Game and yesterday, when I went to bed everything was working great. Today, when I opened Unity up to do some finishing touches, everything I'm doing is being called twice...

    So when I click the start button it calls the start game twice, then when my sheep hit obstacles it calls OnTriggerEnter twice. Idk what I did wrong or what happened and would prefer to not have to restart the whole project...



    Counter Script
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using TMPro;
    6.  
    7. public class Counter : MonoBehaviour
    8. {
    9.     public TMP_Text savedText;
    10.     public TMP_Text deadText;
    11.     private int savedCount = 0;
    12.     private int deadCount = 0;
    13.  
    14.     private void Start()
    15.     {
    16.         savedCount = 0;
    17.         deadCount = 0;
    18.     }
    19.  
    20.     public void AddSavedSheep()
    21.     {
    22.         savedCount++;
    23.         savedText.text = "Saved: " + savedCount;
    24.     }
    25.     public void AddDeadSheep()
    26.     {
    27.         deadCount++;
    28.         deadText.text = "Dead: " + deadCount;
    29.     }
    30. }
    Sheep Script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SheepControls : MonoBehaviour
    6. {
    7.     private Rigidbody rb;
    8.  
    9.     [Header("Movement")]
    10.     [Tooltip("How fast to move GameObject Forward.")]
    11.     public float forwardSpeed = 4.0f;
    12.     [Tooltip("Apply this much force to Rigidbody.")]
    13.     public float jumpForce = 5.0f;
    14.     private float groundY;
    15.     [Space]
    16.     [SerializeField] private bool jumping;
    17.     [SerializeField] private bool isDestroyed;
    18.     [SerializeField] private bool isSaved;
    19.  
    20.     public ParticleSystem explosionParticles;
    21.     private Counter counter;
    22.     void Start()
    23.     {
    24.         rb = GetComponent<Rigidbody>();
    25.         groundY = (transform.position.y)+0.02f;
    26.         counter = FindObjectOfType<Counter>();
    27.        
    28.     }
    29.     void Update()
    30.     {
    31.         transform.Translate(forwardSpeed * Time.deltaTime * Vector3.forward);
    32.        
    33.         if (Input.GetKeyDown(KeyCode.Space) && !jumping)
    34.         {
    35.             if(transform.position.y < groundY)
    36.             {
    37.                 Jump();
    38.             }
    39.         }
    40.  
    41.         jumping = false;
    42.     }
    43.  
    44.     private void Jump()
    45.     {
    46.         jumping = true;
    47.         rb.AddForce(Vector3.up * jumpForce);
    48.     }
    49.  
    50.     private void OnTriggerEnter(Collider other)
    51.     {
    52.         if (other.CompareTag("ExplosiveWire"))
    53.         {
    54.             if (isDestroyed) return;
    55.             else
    56.             {
    57.                 Debug.Log("Hit Wire");
    58.                 isDestroyed = true;
    59.                 Destroy(gameObject);            
    60.                 Instantiate(explosionParticles, transform.position,
    61.                     explosionParticles.transform.rotation);  
    62.             }
    63.             counter.AddDeadSheep();
    64.         }
    65.  
    66.         if (other.CompareTag("Goal"))
    67.         {
    68.             if (isSaved) return;
    69.             else
    70.             {
    71.                 Debug.Log("Reached Goal");
    72.                 isSaved = true;
    73.                 Destroy(gameObject);
    74.             }
    75.             counter.AddSavedSheep();
    76.         }
    77.     }
    78.  
    79.     private void OnCollisionEnter(Collision collision)
    80.     {
    81.         if (collision.gameObject.CompareTag("Sheep"))
    82.         {
    83.             Physics.IgnoreCollision(this.GetComponent<Collider>(),
    84.                 collision.gameObject.GetComponent<Collider>());
    85.         }
    86.     }
    87. }
    Game Manager Script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class GameManager : MonoBehaviour
    7. {
    8.     public bool isGameActive;
    9.     public GameObject titleScreen;
    10.     public GameObject sheepControllerPrefab;
    11.  
    12.     public void StartGame(int difficulty)
    13.     {
    14.         titleScreen.SetActive(false);
    15.         isGameActive = true;
    16.         InvokeRepeating(nameof(SpawnSheepWave), 2.0f, 2.0f);
    17.     }
    18.  
    19.     public void Restart()
    20.     {
    21.         SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    22.     }
    23.  
    24.     public void SpawnSheepWave()
    25.     {
    26.                 Instantiate(sheepControllerPrefab, transform.position,
    27.                     transform.rotation);
    28.     }
    29. }
    Start Button Script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class DifficultyButton : MonoBehaviour
    7. {
    8.     private Button button;
    9.     private GameManager gameManager;
    10.  
    11.     [Header("Difficulty Level")]
    12.     [Tooltip("The spawn rate will be divided by this number.")]
    13.     public int difficulty;
    14.     void Start()
    15.     {
    16.         gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    17.         button = GetComponent<Button>();
    18.         button.onClick.AddListener(SetDifficulty);
    19.     }
    20.  
    21.     public void SetDifficulty()
    22.     {
    23.         Debug.Log(gameObject.name + " was clicked.");
    24.         gameManager.StartGame(difficulty);
    25.     }
    26. }
    So, it's actually adding the score twice, so originally I thought maybe I need to do an isDestroyed or isSaved check and added that to the script but nothing seems to keep it from adding the score twice, or thinking I clicked the start button twice.




    I feel like my code is fine, I just don't know what is going on with it and why it is calling everything twice. Do you think there is a solution, or that I might just have to recreate the game in a new project?

    Would trying to disable the box collider when it enters the trigger maybe fix the problem?

    There is only one BoxCollider on the sheep, and the one BoxCollider on the fence, and one BoxCollider on the goal. They all have rigid bodies and the calls are being made correctly, they just happen two times at once.

    Thanks for any help you guys can provide!

    I also tried moving the increment step before or after the if statements to see if it would do anything different but I get the same results.


    Code (CSharp):
    1.     private void OnTriggerEnter(Collider other)
    2.     {
    3.         if (other.CompareTag("ExplosiveWire"))
    4.         {
    5.             if (isDestroyed) return;
    6.             else
    7.             {
    8.                 Debug.Log("Hit Wire");
    9.                 isDestroyed = true;
    10.                 Destroy(gameObject);            
    11.                 Instantiate(explosionParticles, transform.position,
    12.                     explosionParticles.transform.rotation);
    13.                 counter.AddDeadSheep();
    14.             }
    15.         }
    16.  
    17.         if (other.CompareTag("Goal"))
    18.         {
    19.             if (isSaved) return;
    20.             else
    21.             {
    22.                 Debug.Log("Reached Goal");
    23.                 isSaved = true;
    24.                 Destroy(gameObject);
    25.                 counter.AddSavedSheep();
    26.             }
    27.         }
    28.     }


    I don't know if it's just a bug and I need to create a new project, a new sheep prefab, or where I'm messing things up. :(

    Thanks in advance for any help!
     
  2. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,303
    You are subscribing to this event in code
    Code (CSharp):
    1. button = GetComponent<Button>();
    2.         button.onClick.AddListener(SetDifficulty);
    you are also subscribing to this event via the inspector.

    So you are subscribing the same method twice
     
    Last edited: May 11, 2022
    KrakenKoders likes this.
  3. KrakenKoders

    KrakenKoders

    Joined:
    Jun 11, 2014
    Posts:
    6
    OMG, I'm so stupid! Thank you so much, I was like what the crap am I doing here!