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

After a restart, unity throws the error "Object reference not set to an instance of an object".

Discussion in 'Scripting' started by GREDA, Jun 5, 2020.

  1. GREDA

    GREDA

    Joined:
    Jun 5, 2020
    Posts:
    5
    I'm trying to search for objects by tag and check the topmost parent object. The script is working, but it works until I close unity , then you can create a new script , exactly the same.
     

    Attached Files:

  2. GREDA

    GREDA

    Joined:
    Jun 5, 2020
    Posts:
    5
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Shoting : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.     private GameObject[] objs;
    9.     private GameObject gun;
    10.     private Animator anim;
    11.     public GameObject bullet;
    12.     public Transform firepoint;
    13.     void Start()
    14.     {
    15.         objs = GameObject.FindGameObjectsWithTag("Weapon");
    16.          foreach (GameObject guns in objs)
    17.          {
    18.              if(guns.transform.root.name == "Hero")
    19.              {
    20.                  gun = guns;
    21.              }
    22.          }
    23.  
    24.         anim = gun.transform.GetComponent<Animator>();
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.         if (Input.GetButtonDown(("Fire1")))
    31.         {
    32.             shoot();
    33.             anim.SetTrigger("SH");
    34.         }
    35.     }
    36.     void shoot()
    37.     {
    38.         Instantiate(bullet, firepoint.position, firepoint.rotation);
    39.        
    40.     }
    41. }
     
  3. bitlysub2anf

    bitlysub2anf

    Joined:
    May 8, 2020
    Posts:
    71
    I guess this must be a bug if there are no errors. Try reporting the problem in your editor from Help>Report a Bug
    (I may be wrong)
     
  4. GREDA

    GREDA

    Joined:
    Jun 5, 2020
    Posts:
    5
    As far as I understand, the problem is that Unity is not able to find an animator for an object found by name or tag after restarting unity
     
  5. GREDA

    GREDA

    Joined:
    Jun 5, 2020
    Posts:
    5
    OK, void Awake () instead of void Start() solves my problem.
     
  6. bitlysub2anf

    bitlysub2anf

    Joined:
    May 8, 2020
    Posts:
    71
    So, case closed?
     
  7. GREDA

    GREDA

    Joined:
    Jun 5, 2020
    Posts:
    5
    Hm, i think so