Search Unity

Question Can't stop enemy spawn on Game Over

Discussion in 'Editor & General Support' started by daniduckart, Mar 21, 2023.

  1. daniduckart

    daniduckart

    Joined:
    Feb 11, 2023
    Posts:
    11
    I mistyped in my title. It's not the enemy spawn it's the enemy script (I'm just too use to typing enemy and spawn together).

    I'm not sure what I'm doing wrong here. The game runs fine when I don't have a game over, but once I add that script it keeps giving me a Missing Reference Exception for both my camera rotation and my enemy script. It seems like the script is still still looking for my player, and I can't figure out how to get it to stop. I've tried both "if" and "while" statements, but when I use these it's as though my "isGameActive" script is false (no matter how I change it) and will break the enemy script or the camera code. They seem to be the same problem so I'm just including the enemy script below along with my other script if it's useful. TIA for any advice you can give.

    The bit of code that's causing the Missing Reference Exception is: Vector3 lookDirection = (player.transform.position - transform.position).normalized;

    "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object."

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Enemy : MonoBehaviour
    6. {
    7.     public float speed = 1.0f;
    8.     private Rigidbody enemyRb;
    9.     private GameObject player;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         enemyRb = GetComponent<Rigidbody>();
    15.         player = GameObject.Find("Player");
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         Vector3 lookDirection = (player.transform.position - transform.position).normalized;
    22.  
    23.         enemyRb.AddForce(lookDirection * speed);
    24.  
    25.         if (transform.position.y < -7)
    26.         {
    27.             Destroy(gameObject);
    28.         }  
    29.     }
    30. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.InputSystem;
    5. using TMPro;
    6. using UnityEngine.SceneManagement;
    7. using UnityEngine.UI;
    8.  
    9.  
    10. public class Playercontroller : MonoBehaviour
    11. {
    12.     // Create public variables for player speed, and for the Text UI game objects
    13.     private float speed = 1;
    14.     public TextMeshProUGUI countText;
    15.     public GameObject winTextObject;
    16.  
    17.     public float count = 0;
    18.     private Rigidbody playerRb;
    19.     private GameObject focalPoint;
    20.     public GameObject Player;
    21.     private GameManager gameManager;
    22.     public bool isGameActive;
    23.  
    24.     public float yFall = -57;
    25.  
    26.  
    27.  
    28.     // Start is called before the first frame update
    29.     void Start()
    30.     {
    31.         gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
    32.         playerRb = GetComponent<Rigidbody>();
    33.         focalPoint = GameObject.Find("Focal Point");
    34.         //set count to zero
    35.         count = 0;
    36.  
    37.         SetCountText();
    38.  
    39.         // Set the text property of the Win Text UI to an empty string, making the 'You Win' (game over message) blan
    40.         winTextObject.SetActive(false);
    41.      
    42.     }
    43.     void Update()
    44.     {
    45.         float forwardInput = Input.GetAxis("Vertical");
    46.         playerRb.AddForce(focalPoint.transform.forward * speed * forwardInput);
    47.  
    48.      
    49.         if (transform.position.y < yFall)
    50.         {
    51.             Destroy(gameObject);
    52.         }
    53.     }
    54.  
    55.     void SetCountText()
    56.     {
    57.         countText.text = "Count: " + count.ToString();
    58.  
    59.         if (count >= 16)
    60.         {
    61.             // Set the text value of your 'winText'
    62.             winTextObject.SetActive(true);
    63.         }
    64.  
    65.     }
    66.     private void OnTriggerEnter(Collider other)
    67.     {
    68.  
    69.  
    70.         if (other.gameObject.CompareTag("PickUp"))
    71.  
    72.         {
    73.             other.gameObject.SetActive(false);
    74.             count = count + 1;
    75.  
    76.             SetCountText();
    77.         }
    78.     }
    79.  
    80. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5. using UnityEngine.SceneManagement;
    6. using UnityEngine.UI;
    7.  
    8.  
    9. public class GameManager : MonoBehaviour
    10.  
    11. {
    12.     public TextMeshProUGUI gameOverText;
    13.     public GameObject titleScreen;
    14.     public GameObject bumpers;
    15.     public Button restartButton;
    16.     public bool isGameActive;
    17.     private Playercontroller playerControllerScript;
    18.     public GameObject player;
    19.     // Start is called before the first frame update
    20.     void Start()
    21.     {
    22.         playerControllerScript = GameObject.Find("Player").GetComponent<Playercontroller>();
    23.     }
    24.  
    25.     // Update is called once per frame
    26.     void Update()
    27.     {
    28.          restartButton.onClick.AddListener(RestartGame);
    29.     }
    30.  
    31.     public void StartGame(int difficulty)
    32.     {
    33.         if (difficulty == 1)
    34.         {
    35.             bumpers.gameObject.SetActive(true);
    36.         }
    37.  
    38.         isGameActive = true;
    39.  
    40.         titleScreen.gameObject.SetActive(false);
    41.     }
    42.     public void GameOver(int PlayerController)
    43.     {
    44.      
    45.         gameOverText.gameObject.SetActive(true);
    46.         isGameActive = false;
    47.         restartButton.gameObject.SetActive(true);
    48.  
    49.  
    50.     }
    51.  
    52.     public void RestartGame()
    53.     {
    54.         SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    55.  
    56.     }
    57.  
    58.  
    59.  
    60. }
     
    Last edited: Mar 21, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Nothing matters above until you fix the MissingReferenceException.

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that

    Once that is fixed, if your problem still exists, then it is ...

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    When in doubt, print it out!(tm)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
  3. daniduckart

    daniduckart

    Joined:
    Feb 11, 2023
    Posts:
    11
    As far as I know it's the player that's null.
    If I check if the different scripts are being run with debug.log in the start function the enemy script repeatedly tells me it's working and the rotate camera says it's not, even though both work until the player object is destroyed. And that, as far as I know, is because they keep looking for the player object that was destroyed. I don't know how to fix it.

    I appreciate the guide, but I am not experienced enough to properly troubleshoot this. I've used the code I've learned in classes as a template and spent hours trying to rearrange the code in a way that makes sense and searching the internet for a solution before I asked here. None of this is making sense to me.

    If you have any insight it would be greatly appreciated.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    If you follow the link there are the most-common ways for something to be set.

    If you're following a tutorial go back and look for how they did it.

    If you're winging it on your own, GREAT! Go back to this link (part of the link above), and see the mindset you must develop to identify issues in your code:

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.
     
  5. daniduckart

    daniduckart

    Joined:
    Feb 11, 2023
    Posts:
    11
    Edit: I think I got it figured out, but Unity crashed twice when I ran the script. Are they related or is this just a weird unity thing?
     
    Last edited: Mar 22, 2023
  6. daniduckart

    daniduckart

    Joined:
    Feb 11, 2023
    Posts:
    11
    Thanks for the help, Kurt!

    For anyone searching this post at a later date part of the problem is I wasn't calling the player correctly. It was a case sensitivity issue. I still have a button problem with the restart game, but I think it's a problem I can solve.

    I had to use the bit of code below to fix it and moved the RestartGame() & GameOver() to the Playercontroller script (not sure if I had to do it, but I couldn't get the script to call on it otherwise). Also removing int PlayerController from GameOver().

    Code (CSharp):
    1.  if (transform.position.y < yFall)
    2.         {
    3.             Destroy(Player);
    4.             Player = null;
    5.             Debug.Log(Player == null);
    6.             if (Player == null)
    7.             {
    8.                 isGameActive = false;
    9.                 GameOver();
    10.             }
     
    Last edited: Mar 22, 2023