Nullreferenceexception Unity 3D

Asked

Viewed 82 times

1

I started a course where they teach to create a 2D game using Unity3d, I tried to add things to the game but I am failing miserably and so I decided to try a little help.

In this case, I tried to create a powerup where when the Player catches a Buff, the laser speed increases, but in this I’m having the error:

NullReferenceException: Object reference not set to an instance of an object
Powerup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Galaxy Shooter/Scripts/Powerup.cs:54)

Here come the codes:

Player

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

    public bool canTripleShoot = false;
    public bool movSpeedBoost = false;
    public bool shield = false;

    [SerializeField]
    private GameObject _laserPrefabs;

    [SerializeField]
    private GameObject _tripleShootPrefab;

    [SerializeField]
    private GameObject _shieldGameObject;

    [SerializeField]
    private GameObject _explosionPrefab;

    [SerializeField]
    private float _speed = 5.0f;

    [SerializeField]
    private GameObject[] _engines;

    [SerializeField]
    private float _fireRate = 0.25f;

    private float _canFire = 0.0f;
    public int playerHp = 3;
    public int _hitcount = 0;

    private UIManager _uiManager;
    private GameManager _gameManager;
    private SpawnManager _spawnManager;
    private AudioSource _audioSource;



    // Use this for initialization
    void Start () {
        _audioSource = GetComponent<AudioSource>();
        _spawnManager = GameObject.Find("Spawn_Manager").GetComponent<SpawnManager>();
        _uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
        _gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();

        transform.position = new Vector3(0, 0, 0);

        if(_uiManager != null)
        {
            _uiManager.UpdateLives(playerHp);
        }

        if(_spawnManager != null)
        {
            _spawnManager.StartSpawn();
        }

    }

    // Update is called once per frame
    void Update ()
    {
        Movement();
        //ativar ao pressionar espaço ou botão esquerdo do mouse
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0))
        {
            Shoot();
        }

    }

    //renderização e cooldown dos tiros
    private void Shoot()

    {

        if (Time.time > _canFire)
        {
            _audioSource.Play();
            if (canTripleShoot== true)
            {
                Instantiate(_tripleShootPrefab, transform.position, Quaternion.identity);

            }
            else
            {
                Instantiate(_laserPrefabs, transform.position + new Vector3(0, 0.95f, 0), Quaternion.identity);

            }
            _canFire = Time.time + _fireRate;

        }
    }
    //calculo de dano
    public void Damage()
    {
        if(shield == true)
        {          
            shield = false;
            _shieldGameObject.SetActive(false);
            return;
        }

        _hitcount++;

        if(_hitcount == 1)
        {
            _engines[0].SetActive(true);
        }

        if(_hitcount == 2)
        {
            _engines[1].SetActive(true);
        }

        playerHp--;

        _uiManager.UpdateLives(playerHp);

        if(playerHp < 1)
        {
            Instantiate(_explosionPrefab, transform.position, Quaternion.identity);
            _gameManager.gameOver = true;
            _uiManager.ShowTitleScreen();
            Destroy(this.gameObject);
        }

    }

    public void ShieldUp()
    {
        shield = true;
        _shieldGameObject.SetActive(true);


    }
    //controle da velocidade de movimento e teleporte
    private void Movement()
    {
        float controleHorizontal = Input.GetAxis("Horizontal");
        float controleVertical = Input.GetAxis("Vertical");

        //velocidade de movimento
        if(movSpeedBoost == true)
        {
            transform.Translate(Vector3.up * _speed * controleVertical * Time.deltaTime * 2.0f);
            transform.Translate(Vector3.right * _speed * controleHorizontal * Time.deltaTime * 2.0f);
        }else
        {
            transform.Translate(Vector3.up * _speed * controleVertical * Time.deltaTime);
            transform.Translate(Vector3.right * _speed * controleHorizontal * Time.deltaTime);
        }


        //limita jogar até o centro da tela
        if (transform.position.y > 0)
        {
            transform.position = new Vector3(transform.position.x, 0, 0);
        }
        //limita jogar até a borda inferior
        else if (transform.position.y < -4.2f)
        {
            transform.position = new Vector3(transform.position.x, -4.2f, 0);
        }

        //teleporta jogar se sair da tela na horizontal
        else if (transform.position.x < -9.45f)
        {
            transform.position = new Vector3(9.45f, transform.position.y, 0);
        }
        else if (transform.position.x > 9.45f)
        {
            transform.position = new Vector3(-9.45f, transform.position.y, 0);
        }
    }
    //duração triple shot
    public IEnumerator TripleShotPowerDownRoutine()
    {
        yield return new WaitForSeconds(5.0f);
        canTripleShoot = false;
    }
    public void TripleShotPowerUpOn()
    {
        canTripleShoot = true;
        StartCoroutine(TripleShotPowerDownRoutine());

    }

    //duração boost de movimento
    public IEnumerator MovSpeedBoostDownRoutine()
    {
        yield return new WaitForSeconds(5.0f);
        movSpeedBoost = false;
    }
    //ativa boost de movimento e inicia contagem de duração
    public void MovSpeedBoost()
    {
        movSpeedBoost = true;
        StartCoroutine(MovSpeedBoostDownRoutine());
    }


}

Laser

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Laser : MonoBehaviour {
    [SerializeField]
    public float _speed = 10.0f;
    [SerializeField]
    public bool _laserBoost = false;
    // Use this for initialization
    void Start () {
        _laserBoost = false;

        if (_laserBoost == true)
        {
            _speed = 100f;
        }
    }

    // Update is called once per frame
    void Update () {

        //código gigante e dificil de decifrar ~irony
        transform.Translate(Vector3.up * _speed * Time.deltaTime);
        if (transform.position.y > 6f)
        {
            if(transform.parent != null)
            {
                Destroy(transform.parent.gameObject);
            }
            Destroy(gameObject);
        }

    }
    public IEnumerator LaserBoostDuration()
    {
        yield return new WaitForSeconds(10f);
        _laserBoost = false;
    }
    public void LaserBoost()
    {
        _laserBoost = true;
        StartCoroutine(LaserBoostDuration());
    }

}

Powerup

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Powerup : MonoBehaviour
{
    [SerializeField]
    private float _speed = 3.0f;
    [SerializeField]
    private int powerupID;
    [SerializeField]
    private AudioClip _clip;


    // Update is called once per frame
    void Update ()
    {
        //movimenta o powerup para baixo
        transform.Translate(Vector3.down * _speed * Time.deltaTime);
        //destroy o power ao sair da tela
        if (transform.position.y <-7)
        {
            Destroy(this.gameObject);
        }
    }
    private void OnTriggerEnter2D(Collider2D other)
    {

        if(other.tag == "Player")
        {
            //acessa o player
            Player player = other.GetComponent<Player>();

            if(player != null)
            {
                if(powerupID == 0)
                {
                    //ativa tripleshoot
                    player.TripleShotPowerUpOn();
                }
                else if(powerupID == 1)
                {
                    //ativa speedboost
                    player.MovSpeedBoost();
                }
                else if(powerupID == 2)
                {
                    //ativar shield
                    player.ShieldUp();
                }
                else if (powerupID == 3)
                {
                    Laser laser = GameObject.Find("laser").GetComponent<Laser>();
                    laser.LaserBoost();
                }


            }


            //detroy powerup
            AudioSource.PlayClipAtPoint(_clip, transform.position);
            Destroy(this.gameObject);
        }
    }
}

The error is pointing to

laser.LaserBoost();
  • Where is the error?.

  • I’m sorry, I’m missing information. But the error is here: Nullreferenceexception: Object Reference not set to an instance of an Object Powerup.Ontriggerenter2d (Unityengine.Collider2d other) (at Assets/Galaxy Shooter/Scripts/Powerup.Cs:54)

  • We have no way of knowing which line is 54.

  • within the "Else if (powerupID == 3)" line 54 is the "laser.Laserboost();"

  • 2

    GetComponent<Laser>() is not generating an object, now you have to see why.

1 answer

0

okay, let’s go there :

Laser laser = GameObject.Find("laser").GetComponent(); // aki o seu gameObject tem o nome "lazer"  sempre??
laser.LaserBoost();//isso aki da erro se o laser estiver null, que provavelmente é o caso

possible solution:

//assim vc vai saber onde ta dando ruim, isso não mudando a estrutura do codigo!!
GameObject laserGO = GameObject.Find("laser");
if(laserGO != null){
    Laser laser = laserGO.GetComponent()

    if(laser !- null){
        laser.LaserBoost();
    }
}

///So it would be better >>

at Powerup >>

    if (powerupID == 3)
{
    if(_laserRef != null)
    {
        player._laserRef.LaserBoost();
    }
}

in player >>

public Lazer _laserRef;

private void Shoot()
{
    if (Time.time > _canFire)
    {
        _audioSource.Play();
        if (canTripleShoot== true)
        {
            Instantiate(_tripleShootPrefab, transform.position, Quaternion.identity);

        }
        else
        {

            _laserRef = Instantiate(_laserPrefabs, transform.position + new Vector3(0, 0.95f, 0), Quaternion.identity);

        }
        _canFire = Time.time + _fireRate;

        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.