Error "Nullreferenceexception: Object Reference not set to an instance of an Object" in Unity

Asked

Viewed 83 times

0

I’m trying to develop my first game with Unity, a Space Invaders, and I was able to do a lot of things, but when I get to the part of the code to create the enemy’s movement, I’m getting this mistake:

Nullreferenceexception: Object Reference not set to an instance of an Object Enemycontroller.Start () (at Assets/Scripts/Enemycontroller.Cs:32)

I searched hard, but I couldn’t find any answers that could help my case, so I need a light.

The problem is on line 32, this one: InvokeRepeating("MoveEnemy", 0.1f, 0.3f);

Code below:

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

public class EnemyController : MonoBehaviour
{
    private Transform enemyHolder;
    public float speed;

    public GameObject shot;
    public Text winText;
    public float fireRate = 0.997f;

    void Start()
    {
        winText.enabled = false;
        InvokeRepeating("MoveEnemy", 0.1f, 0.3f);
        enemyHolder = GetComponent<Transform> ();
    }

    void MoveEnemy()
    {
        enemyHolder.position += Vector3.right * speed;

        foreach(Transform enemy in enemyHolder)
        {
            if(enemy.position.x < -10.5 || enemy.position.x > 10.5)
            {
                speed = -speed;
                enemyHolder.position += Vector3.down * 0.5f;
                return;
            }

            if(Random.value > fireRate)
            {
                Instantiate(shot, enemy.position, enemy.rotation);
            }

            if(enemy.position.y <= -4)
            {
                GameOver.isPlayerDead = true;
                Time.timeScale = 0;
            }

        }

        if(enemyHolder.childCount == 1)
        {
            CancelInvoke();
            InvokeRepeating("MoveEnemy", 0.1f, 0.25f);
        }
        
        if (enemyHolder.childCount == 0)
        {
            winText.enabled = true;
        }
    }
}
  • 1

    The error message is clear, there is some non-sequential object that you are trying to use, that is, it has some null object. I would say check on the Unity interface if you associated the winText to a component of the type Text and was associated shot to some component. Most likely it is either of these two fields that should be null.

2 answers

-1

I noticed that you are "invoking" Moveenemy() method by Invokerepeat within the Moveenemy() method itself, before that you are canceling a Invoke that until then does not exist, which probably is giving problem in your code. The whole logic of this code is strange.

The user Flávio Mello I present you a logic more consistent with what you need, try to adapt it to your code, but can also take a look at the link below a tutorial of moving enemies in 2D:

https://www.youtube.com/watch?v=XH8cEgIGt08

-1

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

public class Inimigo : MonoBehaviour
{
    public Transform DetectaGround;
    public float distancia = 3f;
    public bool olhandoParaDireita;
    public bool olhandoParaEsquerda;
    public float velocidade = 4f; 
    public float velocidadePerseguicao = 7f;

    public bool spot = false; //booleana para saber se o jogador esta dentro do campo de visão
    public Transform target; //alvo que o inimigo vai perseguir, nesse caso o jogador
    public Transform inicioCP; //inicio do campo de visão 
    public Transform fimCP; //final do campo de visão 

    void Start()
    {
        olhandoParaDireita = true;
    }

    void Update()
    {
        Patrulha();
        Raycasting();
        Persegue();
    }

    public void Patrulha()
    {
        transform.Translate(Vector2.right * velocidade * Time.deltaTime);

        RaycastHit2D groundInfo = Physics2D.Raycast(DetectaGround.position, Vector2.down, distancia);
        if (groundInfo.collider == false)
        {
            if (olhandoParaDireita == true)
            {
                transform.eulerAngles = new Vector3(0, 180, 0);
                olhandoParaDireita = true;
            }
            else
            {
                transform.eulerAngles = new Vector3(0, 180, 0);
                olhandoParaDireita = false;
            }
            
            if (olhandoParaEsquerda == false)
            {
                transform.eulerAngles = new Vector3(0, 180, 0);
                olhandoParaEsquerda = true;
            }
            else
            {
                transform.eulerAngles = new Vector3(0, 180, 0);
                olhandoParaEsquerda = false;
            }   
        }
    }

    public void Raycasting()
    {
        Debug.DrawLine(inicioCP.position, fimCP.position, Color.green);
        spot = Physics2D.Linecast(inicioCP.position, fimCP.position, 1 << LayerMask.NameToLayer("Player"));
    }

    public void Persegue()
    {
        if (spot == true)
        {
            velocidade = velocidadePerseguicao;            
        }

        else if (spot == false)
        {
            velocidade = 4f;
        }
    }
}

Browser other questions tagged

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