Hello! I got two Scripts: 1 Enemy_mob script, with the Array on it, to search for new enemies on the fixed Update(). My Goal is to fill the enemy Array in the Start () of Script 2:
and Script 2, where I actually want to fill the monsterArray
private MonsterScript opponent;
private Transform enemy;
void Start () {
opponent.monsterArray[] += this.gameObject; //put this gameobj. in the monsterArray of MonsterScript
enemy = GameObject.FindWithTag ("Enemy").transform;
opponent = enemy.GetComponent<MonsterScript>();
}
If new Monster spawn, it will check in it’s Start() to get put into monsterArray, so it will get a Focus if it is in nearest Range. Untill now the monsterArray is empty
public class EnemyMobScript : MonoBehaviour
{
private MonsterScript opponent;
private Transform enemy;
void Start ()
{
opponent.monsterArray[] += this.gameObject; //put this gameobj. in the monsterArray of MonsterScript
enemy = GameObject.FindWithTag ("Enemy").transform;
opponent = enemy.GetComponent<MonsterScript>();
}
}
The first problem is that in EnemyMobScript the opponent variable is never initialized when you try to access it like so
opponent.monsterArray[] += this.gameObject; //put this gameobj. in the monsterArray of MonsterScript
I am surprised that you are not getting an error. But it should look more like
public class EnemyMobScript : MonoBehaviour
{
private MonsterScript opponent;
private Transform enemy;
void Start ()
{
enemy = GameObject.FindWithTag ("Enemy").transform; // find the first Enemy GameObject
if ((enemy != null) && (enemy.GetComponent<MonsterScript>() != null))
{
opponent = enemy.GetComponent<MonsterScript>(); // get the MonsterScript attached to the Enemy GameObject
opponent.monsterArray[] += this.gameObject; // put this gameobj. in the monsterArray of MonsterScript
}
}
}
Unless you only have one Enemy in the game you will most likely always be getting the same Enemy with
enemy = GameObject.FindWithTag ("Enemy").transform; // find the first Enemy GameObject
which may be OK but you may still need to worry about circular reference.