GameObject instanciating only once: Runtime Error
So, guys, I´m realy new to Unity and I´m trying to make a spawn system with random enemies and food for the player in a 2D plane.
I have followed some instrutions and created my Spawn system, below.
using UnityEngine;
using System.Collections;
using UnityEditor;
public class Respawn : MonoBehaviour {
public GameObject Player;
public string AssetName;
public Transform[] spawnPoints;
public float spawnTime = 3f;
public int maxSpawn = 3;
public int count=0;
private SpriteRenderer spriteRenderer;
private GameObject SpawnType;
void Awake()
{
}
void Start()
{
string assetPath = "Assets/Prefabs/" + AssetName + ".prefab";
SpawnType = GameObject.Instantiate(AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject))) as GameObject;
spriteRenderer = GetComponent<SpriteRenderer> ();
InvokeRepeating ("Spawn",spawnTime,spawnTime);
}
//Update is called every frame
void Update ()
{
}
void Spawn(){
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Vector3 posicaoAleatoria = Random.insideUnitSphere*100;
posicaoAleatoria.z = 0;
this.transform.position = posicaoAleatoria;
if (maxSpawn >= count)
{
if (SpawnType != null)
{
Instantiate(SpawnType,
new Vector3(spawnPoints[spawnPointIndex].position.x + posicaoAleatoria.x,
spawnPoints[spawnPointIndex].position.y + posicaoAleatoria.y, 0),
spawnPoints[spawnPointIndex].rotation);
count++;
}
}
}
}
I load a prefab from my assets based on the name. I now have two Spawn, one for enemies and other for food. The enemy Spawn is working every time, However, the food Spawn drops only one instance of the food model and I get this error message:
NullReferenceException: Object reference not set to an instance of an object Respawn.Spawn () (at Assets/Scripts/Respawn.cs:41)
With the debug I see the error in the first call, but the object is created in the game goes to next update, after that there is no more food instaciated.
Both Food and Enemy prefabs are 99% the same, right now only the render model is diferent. The null GameObject check I set has no effect, using the debug I get
Any thoughts?
For instantiating, why don't you simply use Instantiate()? make a public variable prefab, and assign Your prefab in the inspector. Then you can simply call this code
Instantiate(prefab, position, rotation);
Answer by Tourist · Nov 04, 2016 at 08:51 AM
One of your transform in your 'spawnPoints' array is null.
Check it inside the inspector of your component.
If none is null, I would recommend to set the variable as a private one and check which classes are modifying it.
Note : Unity serializes private field with [SerializeField] attribute set before the declaration of the variable : [SerializeField] private Transform[] spawnPoints;
Yes, the problem was with spawnPoints references.
It was my old implementation based on a tutorial. I have to set the transform the same way the gameobject.
Thank you.