Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c# - Unity only allow shoot when visible

Well this is my Enemy Script:

 public class Enemy : MonoBehaviour
{
    public GameObject explosion;
    public float speed;
    public float shotDelay;
    public GameObject enemyBomb;
    public bool canShot;
    public int pointValue = 30;


    IEnumerator Start()
    {
        GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
        if (canShot == false) yield break;

        while (true)
        {
            for (int i = 0; i < transform.childCount; i++)
            {
                Instantiate(enemyBomb, transform.position, transform.rotation);
            }
            yield return new WaitForSeconds(shotDelay);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {

        FindObjectOfType<Score>().AddPoint(pointValue);
        Instantiate(explosion, transform.position, transform.rotation);
        Destroy(gameObject);

    }
    private void OnBecameInvisible()
    {
        Destroy(gameObject);
    }
}

The problem is, that the enemy shoots before he is visible so there is no chance to fight him. Is there a way how to check if the Enemy is visible or not?

question from:https://stackoverflow.com/questions/65920630/unity-only-allow-shoot-when-visible

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

maybe you should try to add a trigger - so when the enemy touches the trigger that's set around the player vision something (let's say isvisible = true) should be set to true and every time the enemy wants to shoot it checks if (isvisible == true){//shoot}. And when the enemy goes out of the trigger OnTriggerExit2D(Collider2D collision) it sets isvisible = false

I hope it will work for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...