Search Unity

Game object destroyed after scene reload

Discussion in 'Scripting' started by FandaSv, Sep 21, 2022.

  1. FandaSv

    FandaSv

    Joined:
    Sep 6, 2022
    Posts:
    1
    Hello, I have a problem, I have it set so that when the player touches an enemy, it loads the menu, but when I play again and load the same scene, the gun does not work and it gives me errors the object type of gun has been destroyed an object type of audio source has been destroyed please help me I don't know what to do :( Thanks in advance for your help :)

    Gun script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Gun : MonoBehaviour {
    6.  
    7.     [Header("References")]
    8.     [SerializeField] private GunData gunData;
    9.     [SerializeField] private Transform muzzle;
    10.  
    11.     public static void Main(){}
    12.  
    13.     public Camera WeaponCam;
    14.  
    15.     Animator weaponAnimator;
    16.  
    17.     float timeSinceLastShot;
    18.  
    19.     public ParticleSystem muzzleFlash;
    20.  
    21.     public AudioSource audio;
    22.  
    23.     private void Start()
    24.     {
    25.         PlayerShoot.shootInput += Shoot;
    26.         PlayerShoot.reloadInput += StartReload;
    27.         weaponAnimator = GameObject.FindGameObjectWithTag("WeaponHolder").GetComponent<Animator>();
    28.         audio = GetComponent<AudioSource>();
    29.     }
    30.  
    31.     public void StartReload() {
    32.             if (!gunData.reloading) {
    33.             StartCoroutine(Reload());
    34.         }
    35.     }
    36.  
    37.     private IEnumerator Reload() {
    38.  
    39.         gunData.reloading = true;
    40.         weaponAnimator.SetBool("reloading", true);
    41.        
    42.         yield return new WaitForSeconds(gunData.reloadTime);
    43.  
    44.         gunData.currentAmmo = gunData.magSize;
    45.  
    46.         gunData.reloading = false;
    47.         weaponAnimator.SetBool("reloading", false);
    48.  
    49.     }
    50.  
    51.     private bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1f / (gunData.fireRate / 60f);
    52.  
    53.     private void Shoot()
    54.     {
    55.  
    56.         if (gunData.currentAmmo > 0)
    57.             audio.PlayOneShot(audio.clip);
    58.  
    59.             if (gunData.currentAmmo > 0)
    60.             muzzleFlash.Play();
    61.  
    62.         if (gunData.currentAmmo > 0)
    63.         {
    64.             if (CanShoot())
    65.             {
    66.                 if (Physics.Raycast(muzzle.position, muzzle.forward, out RaycastHit hitInfo, gunData.maxDistance))
    67.                 {
    68.                     Debug.Log(hitInfo.transform.name);
    69.                 }
    70.  
    71.                 gunData.currentAmmo--;
    72.                 timeSinceLastShot = 0;
    73.                 OnGunShot();
    74.             }
    75.         }
    76.     }
    77.  
    78.     private void Update() {
    79.         timeSinceLastShot += Time.deltaTime;
    80.  
    81.         Debug.DrawRay(muzzle.position, muzzle.forward);
    82.     }
    83.     void OnDisable() { }
    84.  
    85.         private void OnGunShot() {
    86.  
    87.         }
    88.     }
    89.  
    90.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    This sounds like some script is perhaps marked DontDestroyOnLoad() and that script is holding onto references that are NOT marked as such. This means that the non-marked references become invalid yet another script is still keeping them.

    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
    - Identify why it is null
    - Fix that

    Also, what on earth is line 11 doing?

    Also, why is line 21 public when line 28 immediately wipes it out?

    If you copied this from somewhere, it looks like maybe you didn't copy 100% of everything you need.

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!