Hey all!,
I have used object pooling for some missile gameObjects. They are retrieved using an empty ‘missile launcher’ gameObject. But after firing one missile, it follows the target, strikes it, and gets destroyed. I have a line of code only to disable it, but not destroy it. The subsequent calls for retrieving the instance result in a NullReferenceException. I don’t know how it is being destroyed. Here is the code for the missile,
using UnityEngine;
using System.Collections;
public class Missile : MonoBehaviour
{
public float missileVelocity = 300;
public float turnSpeed = 20;
Rigidbody homingMissile;
float fuseDelay;
public Transform target;
Transform _transform;
public void Start()
{
_transform = transform;
homingMissile = _transform.rigidbody;
Debug.Log("Fire");
Fire();
}
void Fire()
{
//yield WaitForSec
var distance = Mathf.Infinity;
foreach(GameObject go in GameObject.FindGameObjectsWithTag("Dangerous"))
{
var diff = (go.transform.position - _transform.position).sqrMagnitude;
if(diff < distance)
{
distance = diff;
target = go.transform;
}
}
}
void Update()
{
if(target == null || homingMissile == null)
return;
homingMissile.velocity = _transform.forward * missileVelocity;
var targetRotation = Quaternion.LookRotation(target.position - _transform.position);
homingMissile.MoveRotation(Quaternion.RotateTowards(_transform.rotation, targetRotation, turnSpeed));
}
void OnCollisionEnter(Collision collision)
{
collision.collider.gameObject.SendMessageUpwards("TakeDamage",20,SendMessageOptions.DontRequireReceiver);
gameObject.SetActive(false);
}
}
the missile launcher,
public GameObject missile;
public float fireRate;
Crosshair crosshair;
private Pool pool;
void Start()
{
pool = GameObject.Find("MissilePool").GetComponent<Pool>();
// crosshair = GetComponent<Crosshair>();
}
// Update is called once per frame
public void Fire ()
{
missile = pool.RetrieveInstance();
Debug.Log(pool.name);
if(missile)
{
missile.transform.position = transform.position;
missile.transform.rotation = transform.rotation;
}
}
and the part of the script which calls the missile launcher.
missileLaunch = GetComponentInChildren<Missilelauncher>();
if(CrossPlatformInput.GetButton("Fire2"))
{
MissileTimer += Time.deltaTime;
if(MissileTimer > fireRate)
{
missileLaunch.Fire();
Debug.Log("Fire");
MissileTimer=0;
}
}
PS - The 'Brake" button is for firing a missile and ‘jump’ for the cannon.
The Missile prefab has a RigidBody on it. Could this be the cause of the problem?