Home > database >  Unity - Actions Being Called Twice - OnTriggerEnter, OnClick, EVERYTHING?
Unity - Actions Being Called Twice - OnTriggerEnter, OnClick, EVERYTHING?

Time:05-12

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...

Console Log

Counter Script

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class Counter : MonoBehaviour
{
    public TMP_Text savedText;
    public TMP_Text deadText;
    private int savedCount = 0;
    private int deadCount = 0;

    private void Start()
    {
        savedCount = 0;
        deadCount = 0;
    }

    public void AddSavedSheep()
    {
        savedCount  ;
        savedText.text = "Saved: "   savedCount;
    }
    public void AddDeadSheep()
    {
        deadCount  ;
        deadText.text = "Dead: "   deadCount;
    }
}

Sheep Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SheepControls : MonoBehaviour
{
    private Rigidbody rb;

    [Header("Movement")]
    [Tooltip("How fast to move GameObject Forward.")]
    public float forwardSpeed = 4.0f;
    [Tooltip("Apply this much force to Rigidbody.")]
    public float jumpForce = 5.0f;
    private float groundY;
    [Space]
    [SerializeField] private bool jumping;
    [SerializeField] private bool isDestroyed;
    [SerializeField] private bool isSaved;

    public ParticleSystem explosionParticles;
    private Counter counter;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        groundY = (transform.position.y) 0.02f;
        counter = FindObjectOfType<Counter>();
        
    }
    void Update()
    {
        transform.Translate(forwardSpeed * Time.deltaTime * Vector3.forward);
        
        if (Input.GetKeyDown(KeyCode.Space) && !jumping)
        {
            if(transform.position.y < groundY)
            {
                Jump();
            }
        }

        jumping = false;
    }

    private void Jump()
    {
        jumping = true;
        rb.AddForce(Vector3.up * jumpForce);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("ExplosiveWire"))
        {
            if (isDestroyed) return;
            else
            {
                Debug.Log("Hit Wire");
                isDestroyed = true;
                Destroy(gameObject);             
                Instantiate(explosionParticles, transform.position,
                    explosionParticles.transform.rotation);    
            }
            counter.AddDeadSheep();
        }

        if (other.CompareTag("Goal"))
        {
            if (isSaved) return;
            else
            {
                Debug.Log("Reached Goal");
                isSaved = true;
                Destroy(gameObject);
            }
            counter.AddSavedSheep();
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Sheep"))
        {
            Physics.IgnoreCollision(this.GetComponent<Collider>(),
                collision.gameObject.GetComponent<Collider>());
        }
    }
}

GameManager Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public bool isGameActive;
    public GameObject titleScreen;
    public GameObject sheepControllerPrefab;

    public void StartGame(int difficulty)
    {
        titleScreen.SetActive(false);
        isGameActive = true;
        InvokeRepeating(nameof(SpawnSheepWave), 2.0f, 2.0f);
    }

    public void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    public void SpawnSheepWave()
    {
                Instantiate(sheepControllerPrefab, transform.position, 
                    transform.rotation);
    }
}

Start Button Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DifficultyButton : MonoBehaviour
{
    private Button button;
    private GameManager gameManager;

    [Header("Difficulty Level")]
    [Tooltip("The spawn rate will be divided by this number.")]
    public int difficulty;
    void Start()
    {
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
        button = GetComponent<Button>();
        button.onClick.AddListener(SetDifficulty);
    }

    public void SetDifficulty()
    {
        Debug.Log(gameObject.name   " was clicked.");
        gameManager.StartGame(difficulty);
    }
}

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.

Double increment of the score

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.

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("ExplosiveWire"))
        {
            if (isDestroyed) return;
            else
            {
                Debug.Log("Hit Wire");
                isDestroyed = true;
                Destroy(gameObject);             
                Instantiate(explosionParticles, transform.position,
                    explosionParticles.transform.rotation);
                counter.AddDeadSheep();
            } 
        }

        if (other.CompareTag("Goal"))
        {
            if (isSaved) return;
            else
            {
                Debug.Log("Reached Goal");
                isSaved = true;
                Destroy(gameObject);
                counter.AddSavedSheep();
            }
        }
    }

[Edit] Added Image of scripts attached to game objects. Scripts Attached to Game Objects

CodePudding user response:

Each click you call start on your difficulty button. Which has already run. So you will get 2. See the choices in your start button inspector

  • Related