Hello!
I have 3 scripts:
AAMLauncher.cs - creates air-to-air missiles (AAM), attached to Player
AimingCamera.cs - find enemy targets, attached to aiming camera and AAM prefab
HomingMissile.cs - homing AAM to the enemy target, , attached to AAM prefab
How can I send GameObject (enemy target) from AimingCamera.cs to HomingMissile.cs?
AAMLauncher.cs:
using UnityEngine;
public class AAMLauncher : MonoBehaviour
{
public Rigidbody AAM;
public Transform AAMPoint;
public int AAMSpeed = 100;
public float LaunchDelay = 2f;
public float Damage = 10f;
public string[] targetTags = { "Ground", "Building", "Soldier", "Tank", "APC", "NSTV", "Helicopter" };
private float CurDelay = 0f;
public void AAMLaunch()
{
if (CurDelay <= 0f)
{
CurDelay = LaunchDelay;
Rigidbody AAMInstance = Instantiate(AAM, AAMPoint.transform.position, AAMPoint.transform.rotation) as Rigidbody;
}
}
void FixedUpdate()
{
if (Input.GetMouseButton(0)) AAMLaunch();
if (CurDelay > 0f) CurDelay -= Time.deltaTime;
}
}
AimingCamera.cs:
using UnityEngine;
public class AimingCamera : MonoBehaviour
{
public int AngularVelocity = 180;
private float X, Y, Z;
private float eulerX = 0, eulerY = 0;
private Vector3 AimingPoint;
public GameObject AimTarget;
void Update()
{
X = Input.GetAxis("Mouse X") * AngularVelocity * Time.deltaTime;
Y = -Input.GetAxis("Mouse Y") * AngularVelocity * Time.deltaTime;
eulerX = (transform.rotation.eulerAngles.x + Y) % 360;
eulerY = (transform.rotation.eulerAngles.y + X) % 360;
transform.rotation = Quaternion.Euler(eulerX, eulerY, 0);
RaycastHit hit;
AimingPoint = new Vector3(X, Y, Z);
if (Physics.Raycast(AimingPoint, transform.rotation * Vector3.forward, out hit))
{
AimTarget = hit.collider.gameObject;
}
}
}
HomingMissile.cs:
using UnityEngine;
public class HomingMissile : MonoBehaviour
{
public GameObject AimTarget;
public GameObject AAMExplosionPrefab;
public float AAMSpeed = 20;
public float AAMTurnSpeed = 90;
public float AAMExplosionTime = 20;
private Transform _thisTransform;
public void Awake()
{
_thisTransform = transform;
}
void Update()
{
AAMExplosionTime -= Time.deltaTime;
if (AAMExplosionTime <= 0)
{
Explode();
return;
}
Vector3 movement = _thisTransform.forward * AAMSpeed * Time.deltaTime;
if (AimTarget != null)
{
Vector3 direction = AimTarget.transform.position - _thisTransform.position;
float maxAngle = AAMTurnSpeed * Time.deltaTime;
float angle = Vector3.Angle(_thisTransform.forward, direction);
if (angle <= maxAngle) _thisTransform.forward = direction.normalized;
else _thisTransform.forward = Vector3.Slerp(_thisTransform.forward, direction.normalized, maxAngle / angle);
float distanceToTarget = direction.magnitude;
if (distanceToTarget < movement.magnitude)
{
Explode();
return;
}
}
_thisTransform.position += movement;
}
public void Explode()
{
if (AAMExplosionPrefab != null) Instantiate(AAMExplosionPrefab, _thisTransform.position, _thisTransform.rotation);
Destroy(gameObject);
}
public void OnCollisionEnter()
{
Explode();
}
}
AAM (Clone) inspector:
