The Object you want to instantiate is null.
I'm creating a simple game where all the player has to do is avoid red squares. It's a 2d game and I'm still very new to unity and c# so I'm not completely sure what I'm doing. I keep running into this problem on my enemy spawn script "The Object you want to instantiate is null."
public float maxTime = 1;
private float timer = 0;
private GameObject badGuy;
public float height = 12;
public object GameObject;
private GameObject newbadGuy;
void Start()
{
GameObject newbadGuy = Instantiate(badGuy);
newbadGuy.transform.position = transform.position + new Vector3(0, Random.Range(-height, height), 12);
}
void Update()
{
if (newbadGuy != null && timer > maxTime)
{
GameObject newbadGuy = Instantiate(badGuy);
newbadGuy.transform.position = transform.position + new Vector3(0, Random.Range(-height, height), 12);
Destroy(newbadGuy, 5);
timer = 0;
}
timer += Time.deltaTime;
}
This problem is making the enemy unable to spawn or destroy new enemies.
This code contains multiple problems. The very first of them is this one:
private GameObject newbadGuy;
void Start()
{
GameObject newbadGuy = Instantiate(badGuy);
}
You have defined GameObject newbadGuy
not once but twice. And this alone made sure that private GameObject newbadGuy;
stayed always null forever.
Answer by andrew-lukasik · Jul 24, 2021 at 09:13 PM
using System.Collections;
using UnityEngine;
public class MySpawner : MonoBehaviour
{
[SerializeField] GameObject _prefab = null;
[SerializeField] float _tick = 1f;// seconds
[SerializeField] float _height = 12f;
[Header("Read Only")]
[SerializeField] GameObject _instance = null;
void Start ()
{
StartCoroutine( nameof(SpawnRoutine) );
}
IEnumerator SpawnRoutine ()
{
var delay = new WaitForSeconds( _tick );
while( true )
{
if( _instance==null )
{
Vector3 spawnPoint = transform.position + new Vector3( 0 , Random.Range(-_height, _height) , 12 );
_instance = Instantiate( _prefab , spawnPoint , Quaternion.identity );
Destroy( _instance , 5 );
}
yield return delay;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613040746im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Help with 2D platformer (score),For my 2D game sometimes coins get added twice to the score?! 0 Answers
crouch attack collider 2d question 1 Answer
Dialogue script shows previous sentences after a while 0 Answers
Selecting a game object in Unity 2d 3 Answers
NullreferenceException dealing damage to a child of the enemy 0 Answers