I have an enemy with two colliders (a box and a sphere), both with IsTrigger
activated. The actual enemy's GameObject is an Empty and under that is my mesh and another Empty Object to instantiate shots (so Empty "ufo" > ufo mesh, Empty "SpawnShot").
Now, I want the enemy to start shooting once he enters an area that has a box collider (also a trigger with the IsTrigger
option activated) and has the tag Boundary
.
The code attached to my enemy looks like this:
//Public variables
public float speed, frequency, magnitude;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
//Private variables
private float nextFire;
private bool startFire = false;
private Vector3 pos;
void Start ()
{
pos = transform.position;
}
void Update ()
{
//Sine movement
pos += transform.forward * Time.deltaTime * -speed;
transform.position = pos + transform.up * Mathf.Sin (Time.time * frequency) * magnitude;
//Fire
if (startFire && Time.time > nextFire) {
nextFire = Time.time + fireRate;
Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
}
}
void OnTriggerEnter (Collider other)
{
Debug.Log ("hello im the ufo trigger");
if (other.gameObject.CompareTag ("Boundary")) {
startFire = true;
Debug.Log ("Boundary and boolean is " + startFire);
}
}
I tested it without boolean to see if it was a problem with the shooting itself, but that works. I've tested the lines with Debugs and the only thing that does not debug is inside the if statement inside the OnTriggerEnter
function. So it does trigger, but it does not go in the if statement.
I checked 100 times if everything is tagged and if the trigger option is activated and it is. I don't know what is wrong!
PS: The ufo moves and all, the only thing that is not working is the fire.
EDIT: so I just added another if statement and this one does work (??) and I changed the function like this:
void OnTriggerEnter (Collider other)
{
Debug.Log ("hello im the" + other.gameObject.name + "-" +
other.gameObject.tag + "trigger");
if (other.gameObject.name == "Boundary") {
startFire = true;
Debug.Log ("Boundary and boolean is " + startFire);
}
if (other.gameObject.CompareTag ("player_shot")) {
Destroy(this.gameObject);
}
}
It's still not working, even with comparing it with the name instead that the tag. And when my player fires, the enemy is destroyed, so the colliders are working but not the first if statement