- Home /
Q: How can I resolve my error and how to optimize this script so the game runs smooth ?
I want to resolve the error I have attached but I don't know how.
Here is the script where the error takes place (This is the line in question:
Vector2 direction = (Vector2)target.position - rb.position;)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Rigidbody2D))]
public class HomingMissile : MonoBehaviour {
public Transform target;
public float delay ;
public float speed = 5f;
public float rotateSpeed = 200f;
public GameObject ExplosionEffect;
private Rigidbody2D rb;
// Use this for initialization
IEnumerator Start () {
yield return new WaitForSeconds(delay);
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
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 ()
{
Destroy(gameObject);
Instantiate(ExplosionEffect, transform.position, transform.rotation);
ScoreScript.scoreValue += 1;
}
}
[1]: /storage/temp/113594-scr1unt.png
Optimization is a vast part refer unity learn for tutorials
Answer by fafase · Mar 24, 2018 at 12:27 PM
Your error is due to the delay you set before getting the Rigidbody.
Your Start method will wait for delay amount of seconds. In the meanwhile, your FixedUpdate is running but the rigidbody reference is null.
I don't know why you are stalling in the Start but either you don't:
void Start()
{
rb = GetComponent<Rigidbody>();
}
or if you have a reason to do so, skip the FixedUpdate until the rigidbody is valid:
void FixedUpdate()
{
if(rb == null) { return; }
}
Answer by mani3307 · Mar 24, 2018 at 11:26 AM
@Vlad_96 I am also a beginner, so I will explain what I know 1.) don't use Start as a coroutine it will only runs once. use void Start() { rb.GetComponent(); } move dealy to a separate coroutine 2.)I think You are getting Null reference exceptions at line 45 because you are using "[RequireComponent(typeof(Rigidbody2D))]" incorrectly. and it is not rigidbody2d to the missile make a prefab of the missile and attach rigidbody2d to it and use it instead 3.)use this code in update Vector2 direction = (Vector2)(target.position - rb.position); direction.Normalize(); as they require to update constantly
Your answer
