why does attaching a script to unity makes the game go laggy?
I have a script for a homing missile. When you shoot one it finds a game object with an enemy tag, if there's no enemy tag it explodes. When I start unity it works as intended, until I attach a script. When I shoot a missile and there's no enemy tag it goes extremely laggy (like 0,002 fps). If Unity is restarted it works again. Why does this happen?,Ok so, I made a script for a homing missile. When you shoot one it checks if there's any game object with an enemy tag. If you shoot a missile when there's no enemy tag in the scene it explodes. If I play the game without attaching the script it works as intended, if I do it, the game gets extremely laggy (like 0.002 fps) when there's no enemy tag. When unity is restarted it works again, until I attach any script.
If the script is responsible for the issue, how can we help without seeing it?
I'm not sure if the script is the problem since it works perfectly when you restart. But here is it anyway.
Rigidbody2D rb;
Transform target;
public float rotateSpeed = 200f;
IEnumerator WinBlock()
{
GetComponent<Animator>().SetBool("explode", true);
yield return new WaitForSeconds(0.5f);
Destroy(this.gameObject);
}
void Start()
{
if (!(GameObject.FindGameObjectsWithTag("enemy").Length == 0))
{
target = GameObject.FindGameObjectWithTag("enemy").transform;
}
rb = this.gameObject.GetComponent<Rigidbody2D>();
transform.Rotate(0, 0, -90); // this makes the missile spawn horizontally
}
private void FixedUpdate()
{
Vector2 direction = (Vector2)target.transform.position - rb.position;
direction.Normalize();
float rotationDir = Vector3.Cross(direction, transform.up).z;
rb.angularVelocity = -rotateSpeed * rotationDir;
rb.velocity = rb.transform.up * 8;
}
private void Update()
{
//if there's no enemy tag the missile explodes
if (GameObject.FindGameObjectsWithTag("enemy").Length == 0)
{
StartCoroutine(WinBlock());
}
}
Calling FindGameObjectsWithTag
and creating a new coroutine every frame for 0.5 seconds can be the cause of your problem, especially at high FPS.
You should have a custom class listing your enemies and a flag to not call StartCoroutine
if WinBlock
is already running.
Your answer

Follow this Question
Related Questions
Make a rigidbody Jump (global up) 3 Answers
Unity Noob - clicking on video textured object to start the video 0 Answers
C# GetKeyDown not working 3 Answers
Fancy camera animation but still follower player? 0 Answers
Move Foward key W sometimes keeps walking after I let go of W, only happens afew times 1 Answer