Guided missiles are being implemented.
When referring to error message when the following script is assigned to missile object
NullReferenceException: Object reference not set to an instance of an object
HMissilemovement2+c__Iterator0.MoveNext () (at Assets/Scripts/Training_HomingMissile/HMissilemovement2.cs:62)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
HMissilemovement2:Update() (at Assets/Scripts/Training_HomingMissile/HMissilemovement2.cs:30)
" closest.transform.position = transform.position; "
I think we need to fix this, what if there is?
Here is the Code, please.
Thank you.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HMissilemovement2 : MonoBehaviour
{
Transform m_tfTarget = null;
GameObject closest = null;
Vector3 dir = new Vector3();
public float rotSpeed =180f;
void start()
{
if (closest == null) {
FindClosestEnemy ();
} else if (closest != null)
return;
}
/*
void FixedUpdate()
{
FindClosestEnemy ();
}
*/
void Update()
{
StartCoroutine (LaunchDelay ());
}
public GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag ("Enemy");
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
IEnumerator LaunchDelay()
{
FindClosestEnemy ();
if(closest == null)
{
// Debug.Log ("closest is null");
closest.transform.position = transform.position; /* Here please */
}
else if(closest != null)
{
// Debug.Log ("closest could be");
m_tfTarget = closest.transform;
dir = m_tfTarget.position - transform.position;
dir.Normalize ();
Vector3 pos = transform.position;
float zAngle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg - 90;
Quaternion desiredRot = Quaternion.Euler (0, 0, zAngle);
transform.rotation = Quaternion.RotateTowards (transform.rotation, desiredRot, rotSpeed * Time.deltaTime);
}
yield return new WaitForSeconds (0.5f);
Destroy (gameObject);
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.CompareTag("Enemy"))
{
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
}