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

Question Problems with the Transform.Find

Discussion in 'Scripting' started by ThickyVEVO, Sep 26, 2022.

  1. ThickyVEVO

    ThickyVEVO

    Joined:
    May 28, 2020
    Posts:
    16
    I'm trying to implement a dynamic recoil script but it requires me to call the transform of a camera. The "Transform.Find" is what I need but it seems that the GameObject isn't being properly recognized and I assume it's because of how I wrote it.

    Code (CSharp):
    1. Recoil_Script = transform.Find("CameraRot/CameraRecoil").GetComponent<Recoil>();



    When I actually start the game in unity it comes up with NullReferenceException stating that it's not set to an instance of an object, so I assumed I just called it improperly. I looked over the documentation for Transform.Find and it didn't seem to enlighten me of my woes and I couldn't find any solid workaround so I come here to see if I can find a solution.

    The full scripts may have more information that I may not have provided here, so the full two scripts will be listed below with hopefully more enlightening details.

    Code (CSharp):
    1. {
    2.     [Header("References")]
    3.     [SerializeField] GunData gunData;
    4.     [SerializeField] private Transform muzzle;
    5.  
    6.     [Header("Shot")]
    7.     public AudioSource source1;
    8.     public AudioClip shot;
    9.  
    10.     [Header("Reload")]
    11.     public AudioSource source2;
    12.     public AudioClip reload;
    13.  
    14.     float timeSinceLastShot;
    15.  
    16.     private Recoil Recoil_Script;
    17.  
    18.     void Start()
    19.     {
    20.         Recoil_Script = transform.Find("CameraRot/CameraRecoil").GetComponent<Recoil>();
    21.  
    22.         PlayerShot.shootInput += Shoot;
    23.         PlayerShot.reloadInput += StartReload;
    24.     }
    25.  
    26.     public void StartReload()
    27.     {
    28.         if (!gunData.reloading)
    29.         {
    30.             StartCoroutine(Reload());
    31.         }
    32.     }
    33.  
    34.     private IEnumerator Reload()
    35.     {
    36.         gunData.reloading = true;
    37.  
    38.         source2.PlayOneShot(reload, 0.25f);
    39.  
    40.  
    41.         yield return new WaitForSeconds(gunData.reloadTime);
    42.  
    43.         gunData.currentAmmo = gunData.magSize;
    44.  
    45.         gunData.reloading = false;
    46.     }
    47.  
    48.     private bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1f / (gunData.fireRate / 60f);
    49.  
    50.     public void Shoot()
    51.     {
    52.         if (gunData.currentAmmo > 0)
    53.         {
    54.             if (CanShoot())
    55.             {
    56.                 Debug.Log("BANG!");
    57.  
    58.                 Recoil_Script.RecoilFire();
    59.  
    60.                 source1.PlayOneShot(shot, 0.25f);
    61.                 if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hitInfo, gunData.maxDistance))
    62.                 {
    63.                     Debug.Log(hitInfo.transform.name);
    64.  
    65.                     IDamagable damagable = hitInfo.transform.GetComponent<IDamagable>();
    66.                     damagable?.Damage(gunData.damage);
    67.                 }
    68.  
    69.                 gunData.currentAmmo--;
    70.                 timeSinceLastShot = 0;
    71.                 OnGunShoot();
    72.             }
    73.         }
    74.     }
    75.  
    76.     void Update()
    77.     {
    78.         timeSinceLastShot += Time.deltaTime;
    79.     }
    80.  
    81.     private void OnGunShoot()
    82.     {
    83.  
    84.     }
    85.  
    86. }
    Code (CSharp):
    1. {
    2.  
    3.     //Rotation
    4.     private Vector3 currentRotation;
    5.     private Vector3 targetRotation;
    6.  
    7.     //Hip Recoil
    8.     [SerializeField] private float recoilX;
    9.     [SerializeField] private float recoilY;
    10.     [SerializeField] private float recoilZ;
    11.  
    12.     //Settings
    13.  
    14.     [SerializeField] private float snap;
    15.     [SerializeField] private float returnSpeed;
    16.  
    17.     void Start()
    18.     {
    19.        
    20.     }
    21.  
    22.  
    23.     void Update()
    24.     {
    25.         targetRotation = Vector3.Lerp(targetRotation, Vector3.zero, returnSpeed * Time.deltaTime);
    26.         currentRotation = Vector3.Slerp(currentRotation, targetRotation, snap * Time.fixedDeltaTime);
    27.         transform.localRotation = Quaternion.Euler(currentRotation);
    28.     }
    29.  
    30.     public void RecoilFire()
    31.     {
    32.         targetRotation += new Vector3(recoilX, Random.Range(-recoilY, recoilY), Random.Range(-recoilZ, recoilZ));
    33.     }
    34. }
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    Just make a public field and drag a reference in... get rid of all that silly search code, act like a Unity developer!

    If that's not it then start here because the answer is ALWAYS the same and best of all...

    .... you NEVER have to post for NullReferenceErrors!!!

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

    ThickyVEVO

    Joined:
    May 28, 2020
    Posts:
    16
    That seems like it should work, but alas even after trying both making the field public as well as [SerializeField] and dragging in the camera it needs, it still appears to be null. I looked over your whole thought process and it seems like it functions for almost all NullReferenceErrors, I just can't seem to get it to function with this one. I thought I knew why the line was Null, but appears that was wrong. Any good ways to debug this?
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,003
    Your code isn't still trying to find the object in Start, is it?
     
    Bunny83 likes this.
  5. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,571
    Like Spiney said, are you sure you removed / commented out that transform.Find line? Assigning something through the inspector wouldn't help much, if you're still overwriting the value manually.

    Also note: if the player is a prefab, things can get tricky. Though as long as the structure is all inside a single prefab, you can have referenced inside the prefab itself and those would be fixed when the object is instantiated.

    Anyways, just to make this clear, the "Gun" script you've posted is attached to the "Player" object, right? And that recoil script is actually attached to the object "CameraRecoil"? If those two things are true, your code should work just fine, even though it's not a good idea to do it this way :)

    If you don't want / can't assign the reference through the inspector (which you should be able when you make that reference public) you can also simply use
    GetComponentInChildren<Recoil>()
    instead. It would search on the player for that component and if not found it would traverse all the children of the player and return the first component of that type it can find, or null if no such component was found.
     
  6. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,204
    If you click the error message, it will ping the object that has the error in the hierarchy window.

    A very common mistake is to have two copies of a script in a scene, but forget about one of them. So you try to fix the problem in the copy that you're looking at, while the problem is in the other one. You can find all the instances of the Gun script you have by searching for
    t:gun
    in the hierarchy.
     
  7. ThickyVEVO

    ThickyVEVO

    Joined:
    May 28, 2020
    Posts:
    16
    Problem was solved, thanks!
     

    Attached Files:

    Last edited: Sep 26, 2022