Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

problem with lag

Discussion in 'Getting Started' started by Lenticularic, Nov 17, 2020.

  1. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    So Im making so that when the player shoots the enemies do as well, but b/c all of the rays being casted it lags, here's the code, how do I make it so that it can check for distance and if it's too far than it wont shoot the ray

    code;

    using UnityEngine;

    public class EnemyShoot : MonoBehaviour
    {

    public float damage = 1f;
    public float range = 100f;

    public GameObject FpCam;
    public ParticleSystem muzzle;

    private Transform Thing;
    private Transform player;

    public float distanceAway = 500f;

    void Update()
    {
    if (Input.GetButtonDown("Fire1")) {
    Shoot();
    //make it so that when the players position is farther from distanceAway it wont shoot
    }
    }

    void Awake() {
    Thing = this.transform;
    player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    void Shoot () {

    muzzle.Play();
    FindObjectOfType<AudioManager>().Play("Shoot");

    RaycastHit hit;
    if (Physics.Raycast(FpCam.transform.position, FpCam.transform.forward, out hit, range)) {
    Debug.Log(hit.transform.name);

    PlayerTarg target = hit.transform.GetComponent<PlayerTarg>();
    if (target != null) {
    target.PlayerDMG(damage);
    }
    }
    }
    }
     
  2. Unity-Harkness

    Unity-Harkness

    Unity Technologies

    Joined:
    May 8, 2019
    Posts:
    5
    Lenticularic and Joe-Censored like this.