- Home /
Need help with transform.LookAt(target)
So basically I am trying to create a homing missile, I am using transform.LookAt(target), but when my player instantiates the missile, the missile does not look at the target. It only works if the missile is already in the scene when the game is started.
This is my code:
using UnityEngine;
using System.Collections;
public class Missile : MonoBehaviour {
public float lifeTime = 15;
public GameObject impactEffect;
public Transform target;
// Use this for initialization
void Start () {
Destroy (gameObject, lifeTime);
}
// Update is called once per frame
void Update () {
transform.LookAt (target);
transform.Translate (Vector3.forward * 30 * Time.deltaTime);
}
}
You have to assign the target when you instantiate it.
$$anonymous$$issile m = Instantiate<$$anonymous$$issile>(missilePrefab);
m.target = myTarget;
Answer by Injourn · Jul 06, 2017 at 09:46 PM
There is a chance that "target" is not defined when the object is instantiated. Try to define "target" to the player by using GameObject.find() under the start function.
void Start(){ target = GameObject.Find("[Name of Object]"); Destroy (gameObject, lifeTime); }
If the Start Function doesn't work, Try using Awake instead.
Seriously, GameObject.Find("[Name of Object]")
? There are plenty of legitimate ways to find a target, this isn't even an accurate way.
A few ideas are:
A Target cone system
Raycasting or Linecasting to find targets
Checking for the nearest enemy from a list of enemies...
I tried your method but it says since "target" is a transform, gameobject.find does not work
Every GameObject has a transform componenet. To access it you just use the name of the object and .transform
In his example it would be
target = GameObject.Find("[Name of Object]").transform;
But GameObject.Find() is basically one of the worst things in the Unity API and should NEVER be used, it is controversial, but there are tons of ways to get references to things, that don't involve iterating every object in existence only to compare an array of characters with another.