Question by
FreshStart- · Mar 20, 2020 at 07:28 PM ·
2d gamelagspawningdestroy object
Is there a better way to code this because this is causing a major amount of lag
I am new to coding so I found some YouTube videos and typed some code from there. The problem is that the code is spawning too many objects right next to each other and is causing a lot of lag due to an explosion effect I added whenever an enemy comes in contact with anything. Is there a way to reduce the lag? (Also, if someone could tell me why my target and explosion effect are not assigned, even though I assigned them on the enemy character, that would be so helpful)
this is my code
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Homing : MonoBehaviour {
public Transform target;
private Rigidbody2D rb;
public float speed = 4f;
public float rotateSpeed = 200f;
public GameObject explosionEffect;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if(target != null)
{
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, transform.up).z;
rb.angularVelocity = -rotateAmount * rotateSpeed;
rb.velocity = transform.up * speed;
}
}
void OnTriggerEnter2D()
{
Instantiate(explosionEffect, transform.position, transform.rotation);
Destroy(gameObject);
}
}
2020-03-20-2.png
(431.1 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612225357im_/https://answers.unity.com/themes/thub/images/avi.jpg)