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

NullReferenceException: Object reference not set to an instance of an object Enemys.Start () (at Ass

Discussion in 'Scripting' started by Shahar_bar2, Aug 27, 2020.

  1. Shahar_bar2

    Shahar_bar2

    Joined:
    Jun 22, 2020
    Posts:
    6
    Error:
    NullReferenceException: Object reference not set to an instance of an object
    Enemys.Start () (at Assets/Scripts/Enemys.cs:15)


    Enemys Code:


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Enemys : MonoBehaviour
    6. {
    7.     [SerializeField]
    8.     private float _Speed = 4f;
    9.  
    10.     private Player _player;
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.          _player = GameObject.Find("Player").GetComponent<Player>();
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         transform.Translate(new Vector3(0, -1, 0) * _Speed * Time.deltaTime);
    22.  
    23.         if (transform.position.y <= -5.3f)
    24.         {
    25.             float randomX = Random.Range(-11f, 11f);
    26.             transform.position = new Vector3(randomX, 7.1f, 0);
    27.         }
    28.     }
    29.     private void OnTriggerEnter2D(Collider2D other)
    30.     {
    31.         if (other.tag == "Player")
    32.         {
    33.             Destroy(gameObject);
    34.             Player player = other.transform.GetComponent<Player>();
    35.  
    36.             if (player != null)
    37.             {
    38.                 player.Damage();
    39.             }
    40.         }
    41.         if (other.tag == "Laser")
    42.         {
    43.             Destroy(other.gameObject);
    44.             //Add 10 to score
    45.             if(_player != null)
    46.             {
    47.                 _player.Score();
    48.             }
    49.             Destroy(gameObject);
    50.         }
    51.     }
    52. }
    53.  

    Player Code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player : MonoBehaviour
    6. {
    7.     [SerializeField]
    8.     private float _speed = 5f;
    9.     private float _speedMultiplayer = 2;
    10.     [SerializeField]
    11.     private GameObject _laserPrefab;
    12.     [SerializeField]
    13.     private GameObject _tripleShot;
    14.     [SerializeField]
    15.     private float _fireRate = 0.5f;
    16.     private float _nextFire = 0.0f;
    17.     [SerializeField]
    18.     private int _lives = 3;
    19.  
    20.     private bool _isSpeedBoostActive = false;
    21.     private bool _isTripleShotActive = false;
    22.     private bool _isShieldActive = false;
    23.  
    24.     [SerializeField]
    25.     private int _score;
    26.  
    27.  
    28.     [SerializeField]
    29.     private GameObject _ShieldVisualizer;
    30.  
    31.     [SerializeField]
    32.     private SpawnManager _spawnManager;
    33.  
    34.  
    35.     void Start()
    36.     {
    37.      
    38.         transform.position = new Vector3(0, 0, 0);
    39.         _spawnManager = GameObject.Find("Spawn_Managr").GetComponent<SpawnManager>();
    40.         if(_spawnManager == null)
    41.         {
    42.             Debug.LogError("no SpawnManager");
    43.         }
    44.     }
    45.  
    46.  
    47.     void Update()
    48.     {
    49.         CalculateMovment();
    50.         if (Input.GetKeyDown(KeyCode.Space) && Time.time > _nextFire)
    51.           {
    52.                 ShootLaser();
    53.           }
    54.  
    55.     }
    56.  
    57.     void CalculateMovment()
    58.     {
    59.         float horizontalInput = Input.GetAxis("Horizontal");
    60.         float verticalInput = Input.GetAxis("Vertical");
    61.          transform.Translate(new Vector3(horizontalInput, verticalInput, 0) * (_speed*_speedMultiplayer) * Time.deltaTime);
    62.  
    63.         transform.position = new Vector3(Mathf.Clamp(transform.position.x,-10f,10f),transform.position.y, 0);
    64.         transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y,-4.13f,0), 0);
    65.     }
    66.  
    67.  
    68.     void ShootLaser()
    69.     {
    70.         _nextFire = Time.time + _fireRate;
    71.         if (_isTripleShotActive == true)
    72.         {
    73.             Instantiate(_tripleShot, transform.position, Quaternion.identity);
    74.         }
    75.         else
    76.         {
    77.             Instantiate(_laserPrefab, transform.position + new Vector3(0, 1.04f, 0), Quaternion.identity);
    78.         }
    79.        
    80.    
    81.     }
    82.  
    83.  
    84.     public void Damage()
    85.     {
    86.         if(_isShieldActive == true)
    87.         {
    88.             _isShieldActive = false;
    89.             _ShieldVisualizer.SetActive(false);
    90.             return;
    91.         }
    92.  
    93.         _lives = _lives - 1;
    94.         if (_lives< 1)
    95.         {
    96.             _spawnManager.OnPlayerDeath();
    97.             Destroy(gameObject);
    98.         }
    99.     }
    100.  
    101.  
    102.     public void TripleShotActive()
    103.     {
    104.         _isTripleShotActive = true;
    105.  
    106.         StartCoroutine(TripleShotPowerDownRoutine());
    107.     }
    108.  
    109.     public void SpeedBoostActive()
    110.     {
    111.         _isSpeedBoostActive = true;
    112.         _speed *= _speedMultiplayer;
    113.         StartCoroutine(SpeedBoostDownRoutine());
    114.     }
    115.  
    116.     public void ShieldActive()
    117.     {
    118.         _isShieldActive = true;
    119.         _ShieldVisualizer.SetActive(true);
    120.     }
    121.  
    122.  
    123.     IEnumerator TripleShotPowerDownRoutine()
    124.     {
    125.         yield return new WaitForSeconds(5f);
    126.         _isTripleShotActive = false;
    127.     }
    128.  
    129.     IEnumerator SpeedBoostDownRoutine()
    130.     {
    131.         yield return new WaitForSeconds(10f);
    132.         _speed /= _speedMultiplayer;
    133.         _isSpeedBoostActive = false;
    134.     }
    135.  
    136.     //Method to add 10 to score
    137.     public void Score()
    138.     {
    139.         _score = _score + 10;
    140.         Debug.Log("UP Score");
    141.     }
    142.     //Communicate with the UI to update the score
    143. }
    144.  
     
    Last edited: Aug 27, 2020
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    We need the Error as well, your title is cut :)
     
  3. Shahar_bar2

    Shahar_bar2

    Joined:
    Jun 22, 2020
    Posts:
    6
    NullReferenceException: Object reference not set to an instance of an object
    Enemys.Start () (at Assets/Scripts/Enemys.cs:15)
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Does a GameObject with the name "Player" exist? If that cannot be found, then null.GetComponent would cause the exception. You could also just use FindObjectOfType to directly find the Player component you are looking for.

    Instead of having every enemy that spawns use a Find() method (which is slow and should only be used for prototyping), you should approach this differently. The place that spawns Enemies probably knows about the Player. So it could set the reference to the spawned enemy instead of the enemy needing to search the entire scene graph.. again and again for every enemy spawned.
     
  5. Shahar_bar2

    Shahar_bar2

    Joined:
    Jun 22, 2020
    Posts:
    6
    tanks
     
  6. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Code (CSharp):
    1.  _player = GameObject.Find("Player").GetComponent<Player>()
    Either he cannot find the GameObject of "Player" or he Component doesnt exist
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.