- Home /
Question by
WesterlyCarrot9 · Jul 22, 2018 at 10:33 AM ·
c#updateshootingboolean
How to make this code fire projectile once during the Update function? I know Update means every frame.
I use the code below for the enemy to fire at the player. I can make it fire only once using a key but how can it fire only once without a key? Where should a boolean be placed?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireAtPlayer : MonoBehaviour {
bool p_detected;
public Transform target;
public UnityEngine.AI.NavMeshAgent agent;
public Rigidbody projectile;
public Transform spawn;
public int speed;
// Use this for initialization
void Start () {
speed = 60;
}
// Update is called once per frame
void Update () {
p_detected = GetComponentInChildren<PlayerDetection>().player_detected;
if (p_detected)
{
target = GameObject.FindGameObjectWithTag("Player").transform;
GetComponent<walking>().enabled = false;
agent.isStopped = true;
transform.LookAt(target);
StartCoroutine(shooting());
}
if (!p_detected)
{
target = null;
GetComponent<walking>().enabled = true;
agent.isStopped = false;
}
}
IEnumerator shooting()
{
yield return new WaitForSeconds(3);
var clone = Instantiate(projectile, spawn.position, transform.rotation);
var direction = (target.transform.position - clone.transform.position).normalized;
clone.velocity = direction * speed;
}
}
Comment
Best Answer
Answer by hexagonius · Jul 22, 2018 at 10:50 AM
Just count the time and check if you passed a whole second. This can be done by either accumulating Time.deltaTime and see when it passed 1, or by saving Time.time once and subtracting that from Time.time each frame to see when that difference is 1.
If the corresponding condition is met, reset.
I actually found some examples on Google and implemented it perfectly in my script. Thanks!
Your answer
Follow this Question
Related Questions
Change Bool When Audio Clip Ends C# 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers