Basically, I am making a game where you run over chicken with a car, I have everything done, EXCEPT, the spawning script.
To spawn chickens I use this script:
using UnityEngine;
using System.Collections;
public class Spawener_Chicken : MonoBehaviour
{
public GameObject Chicken;
public int xPos;
public int zPos;
public int enemyCount;
public int enemyLimit = 100;
void Start()
{
StartCoroutine(EnemySpawn());
}
void Update()
{
}
IEnumerator EnemySpawn()
{
while (enemyCount < enemyLimit)
{
xPos = Random.Range(-30, 30);
zPos = Random.Range(-22, 22);
Instantiate(Chicken, new Vector3(xPos, 1, zPos), Quaternion.identity);
yield return new WaitForSeconds(0.1f);
enemyCount += 1;
}
while (enemyCount >= enemyLimit)
{
StartCoroutine(EnemySpawn());
}
}
}
After spawning some, Unity starts giving out errors and pausing the game.
This Is the error:
NullReferenceException: Object reference not set to an instance of an object
chicken.OnTriggerEnter (UnityEngine.Collider hit) (at Assets/scripts/chicken.cs:60)
And This is the Chicken code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class chicken : MonoBehaviour
{
private NavMeshAgent NMA;
public int testint1 = 99;
public int testint2;
private GameObject Visuals;
private GameObject ParticleSys;
public GameObject NumberBoy;
public Spawener_Chicken SpawnerCode;
void Start()
{
StartCoroutine(wait());
}
void RealStart()
{
NumberBoy = GameObject.Find("/Car/Spawner for enemys");
SpawnerCode = NumberBoy.GetComponent();
InvokeRepeating("ChangeDestination", 0, 5);
NMA = GetComponent();
Visuals = this.gameObject.transform.GetChild(0).gameObject;
ParticleSys = this.gameObject.transform.GetChild(1).gameObject;
}
IEnumerator wait()
{
yield return new WaitForSeconds(1);
RealStart();
}
public Vector3 RandomNavmeshLocation(float radius)
{
Vector3 randomDirection = Random.insideUnitSphere * radius;
randomDirection += transform.position;
NavMeshHit hit;
Vector3 finalPosition = Vector3.zero;
if (NavMesh.SamplePosition(randomDirection, out hit, radius, 99999999))
{
finalPosition = hit.position;
}
return finalPosition;
}
void ChangeDestination()
{
// Debug.Log("Changed destination");
NMA.SetDestination(RandomNavmeshLocation(testint1));
}
private void OnTriggerEnter(Collider hit)
{
if (hit.gameObject.tag == "Car")
{
testint1 = 0;
Visuals.SetActive(false);
ParticleSys.SetActive(true);
SpawnerCode.enemyCount--;
// Debug.Log(gameObject.name + ": THat GUY JUST HIT ME!");
Destroy(gameObject, 2);
}
if (hit.gameObject.tag == "Destroying Wall")
{
SpawnerCode.enemyCount--;
Destroy(gameObject, 0);
}
}
}
↧