Hi,
We have an event system that spawns Goblins via a GoblinManager like this:
using UnityEngine;
using System.Collections;
public class EventGoblinWave : EventT {
private GoblinManager mManager;
public EventGoblinWave(GoblinManager aManager) : base("Goblin Wave")
{
mManager = aManager;
//spawn 3 goblins here
for (int i = 0; i < 3; i++)
{
mManager.SpawnGoblin(new Vector3(5, 47, -7));
}
}
public void Update()
{
base.Update();
}
}
now we want to spawn some from an object that is on the scene via the same GoblinManager and we do it like this:
using UnityEngine;
using System.Collections;
public class GoblinHut : MonoBehaviour
{
public int HitPoints;
private GoblinManager mManager;
private MainGameLoop mMainGameLoop;
private float mSpawnTimer;
// Use this for initialization
void Start () {
HitPoints = 200;
mSpawnTimer = -1;
mMainGameLoop = GameObject.Find("MainGameLoop").GetComponent("MainGameLoop") as MainGameLoop;
mManager = mMainGameLoop.GetGoblinManager();
}
// Update is called once per frame
void Update ()
{
if (mManager == null)
{
mManager = mMainGameLoop.GetGoblinManager();
}
if (mSpawnTimer >= 2)
{
mManager.SpawnGoblin(transform.position);
mSpawnTimer = 0;
}
else
{
mSpawnTimer += Time.deltaTime;
}
}
public void GetHit(int aHitPointLoss)
{
if (HitPoints > 0)
{
HitPoints -= aHitPointLoss;
}
}
}
when we spawn the object from the GoblinHut via the GoblinManager we get a NullReferenceException when the GoblinManager check if the goblin spawned is dead. It seems it’s because the Start() has not been called when called from the GoblinHut. The thing I don’t understand is that Start() is called when the event spawn them.
Here is the GoblinManager class:
using UnityEngine;
using System.Collections;
public class GoblinManager : MonoBehaviour {
private ArrayList mGoblins;
public GameObject GoblinPrefab;
private Object mMainLoop;
public void SetMainLoop(Object aMainLoop)
{
mMainLoop = aMainLoop;
}
// Use this for initialization
void Start ()
{
mGoblins = new ArrayList();
}
public void SpawnGoblin(Vector3 aPos)
{
GameObject newGoblin = Instantiate(GoblinPrefab, aPos, Quaternion.identity) as GameObject;
newGoblin.active = true;
if (newGoblin != null)
{
mGoblins.Add(newGoblin);
}
}
// Update is called once per frame
public void Update ()
{
for (int i = 0; i < mGoblins.Count; i++)
{
GameObject obj = (GameObject)mGoblins*;*
-
if (obj.active)* -
{* -
EnemyGoblin goblin = obj.GetComponent<EnemyGoblin>();* -
if (goblin != null)* -
{* -
if (goblin.IsDead())* -
{*
_ Destroy((Object)mGoblins*);_
_ mGoblins.RemoveAt(i);_
_ break;_
_ }_
_ }_
_ }_
_ }_
_ }_
_}*_
Thanks for you help