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;
}
}
}
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 typeText
and was associatedshot
to some component. Most likely it is either of these two fields that should be null.– Pedro Paulo