- Home /
weird problem with scripting
so i have prefab called "enemy" and in that enemy have a script named "enemyBlue_script". and also i have 1 another script called rulebase and it attached to gameobject " game_controller" . in that rulebase script i have some method , one of them is fire() method. and i tried to call it in the enemyBlue_script in the update() function. when i run the game the enemy can firing but the other enemy can't. when the enemy which can fire has destroyed then the other enemy can fire.
this is my script
rulebase script
using UnityEngine;
using System.Collections;
public class Rulebase : MonoBehaviour {
public float fireRate = 5F;
public GameObject shot;
private float nextFire = 0.0F;
public void Fire(Transform shotSpawn){
if (Time.time > nextFire) {
nextFire = Time.time +fireRate; //Increment nextFire time with the current system time + fireRate
Instantiate (shot, shotSpawn.position, shotSpawn.rotation); //Instantiate fire shot
}
}
}
and this is enemyBlue_script which called the fire function from the rulebase script
using UnityEngine;
using System.Collections;
public class EnemyBlue_Script : MonoBehaviour
{
public Transform shotSpawn;
void Update(){
Rules.Fire (shotSpawn);
}
the result of that script is something like this
as you can see the other enemy wont fire. thanks for the help
Answer by Bunny83 · Nov 25, 2016 at 10:41 AM
Well, of course when you only have one "Rulebase" instance in your scene and every enemy is using the same script, you only have one "nextFire" timeout variable. All enemies are calling the Fire method but the timeout prevents that anything happens.
Once the timout is reached the first enemy that calls Fire this frame will actually shoot one bullet. However it also updates the nextFire variable so the next enemy is blocked again.
Why don't you handle the shooting of an enemy on the enemy object? Wouldn't that make more sense?
@bunny83 : yes, normally i would put the shooting in the enemy gameobject. but in this case i want to try to make 1 script that contains all the enemy actions. then when the enemy instantiate they can chose one or two action from the rulebase script.
so, can you fix the script up there please ? what do i have to add in the script to work? thanks for respons