0
votes

I’m trying to have my enemies’ ai target my player until the point where an enemy hits him and he dies. After that, I want the enemies to disperse and then target and move to a random spawn point (simply because they are all around the edge of the screen).

Here’s what I have in the update method of the AIDestinationSetter script:

void Update () {

if (GameObject.FindWithTag("Player").GetComponent<PlayerMovement>().canMove)

{

target = GameObject.FindWithTag("Player").transform;

}

else

{

//randomise movement of all enemies - to spawnpoints at this stage

Transform[] spawnPoints = GameObject.FindGameObjectWithTag("WaveSpawner").GetComponent<WaveSpawner>().spawnPoints; //find spawnpoints

//create array of enemies

GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

foreach (GameObject enemy in enemies) //for each enemy in the array

{

enemy.GetComponent<AIDestinationSetter>().target = spawnPoints[Random.Range(0, spawnPoints.Length)];//set aipath destination to a random spawnpoint

Debug.Log(enemy.GetComponent<AIDestinationSetter>().target);

}

}

if (target != null && ai != null) ai.destination = target.position;

}

(canMove is simply a boolean that is set to true at the start of the game and false when an enemy hits the player. It lives within a script called PlayerMovement that is a component of my GambeObject player.)

(spawnPoints is an array of spawn points that lives inside a script called Wavespawner that is a component of my GameObject Wavespawner… Not the best naming convention I know…)

The problem lies somewhere with me trying to reference the PlayerMovement and Wavespawner scripts in my GetComponent methods.Unity is throwing the errors:

error CS0246: The type or namespace name ‘PlayerMovement’ could not be found (are you missing a using directive or an assembly reference?)

error CS0246: The type or namespace name ‘WaveSpawner’ could not be found (are you missing a using directive or an assembly reference?)

Any help with this matter would be really appreciated. I’ve tried to figure this out for hours now and everything I try just breaks it even more.

1

1 Answers

1
votes

TL;DR

The proper way to setup references between objects is in MonoBehaviour.Awake :

you should use Awake to set up references between scripts

Few more tips:

  • make fields out of GetComponent<T>, don't query about them in Update as it's expensive
  • use Debug.Log(...) to write to console
  • use Assert.IsNotNull, Assert.IsTrue etc to check conditions
  • use breakpoints in your debugger

And about your CS0246 error:

Go to your PlayerMovement.cs file:

Take note of its namespace, e.g.:

namespace MyCoolGame
{
    class PlayerMovement {}
}

Then go back to the script you have the error on and put using MyCoolGame; at beginning.

The error should now be fixed.