Function call only works on one specific game object
I've been building a game that has a region attached to an enemy prefab instance that, when a player enters the region, the object fires at them. The issue is, however, whenever there are two or more instances of the enemy, when the player enters the second enemy's region, the first one fires. So, I am wondering what the problem may be.
Here is my scripts responsible for the above interaction:
using UnityEngine;
using System.Collections;
public class RegionFire : MonoBehaviour {
public Fire FireScript;
public GameObject ScriptHolder;
void Awake() {
ScriptHolder = GameObject.FindGameObjectWithTag ("ScriptHolder");
FireScript = ScriptHolder.GetComponent<Fire> ();
}
void OnTriggerEnter2D(Collider2D other){
if (other.gameObject.CompareTag ("enemyRegion")) {
FireScript.InRegion = true;
Debug.Log("RegionFireCollide");
}
}
}
using UnityEngine;
using System.Collections;
public class Fire : MonoBehaviour {
public bool InRegion;
public GameObject bullet;
private GameObject enemy;
public Transform cannon;
public float speed;
public float interval;
// Use this for initialization
void Start ()
{
interval = 0;
InRegion = false;
}
// Update is called once per frame
void Update () {
if (InRegion == true && interval <= 0) {
SpawningClones ();
}
if (interval <= 1 && interval >= 0) {
interval -= Time.deltaTime;
}
}
void SpawningClones (){
GameObject bulletInstance = Instantiate (bullet, cannon.position, cannon.rotation) as GameObject;
bulletInstance.GetComponent<Rigidbody2D>().AddForce (cannon.forward * speed, ForceMode2D.Impulse);
interval = 1;
}
}
Please note that I will not be able to get back to this until tomorrow, so keep that in mind when replying.
Answer by vintar · Jan 15, 2016 at 10:09 PM
GameObject.FindGameObjectWithTag ("ScriptHolder"); will return the first object it finds with that tag. You would have to get all objects with that tag with something like :
public GameObject[] ScriptHolders;
void Awake()
{
ScriptHolders = GameObject.FindGameObjectsWithTag("ScriptHolder");
}
But you should probably just have the OnTriggerEnter2D in Fire class.
Your answer

Follow this Question
Related Questions
Replicate entire script series, all entailed objects and variables 0 Answers
Player movement help 1 Answer
change a created transform in a script from another one 1 Answer
Help with this code 1 Answer