I have enemy ships that I want to always look at the player.
if I use:
using UnityEngine;
using System.Collections;
public class LookAt : MonoBehaviour
{
public Transform target;
void Update()
{
if(target != null)
{
transform.LookAt(target);
}
}
}
this works if this script is on a non prefab. But as a prefab I lose the target once it is instantiated.
I’m still very new to this and been searching around. Found a few things I thought would work. But i keep getting errors
I tried adding this:
void Start()
{
GameObject target = GameObject.FindGameObjectWithTag("Player");
//ALSO I've tried FindWithTag ("Player") as well as Find("Player") <---These don't give me erros but they don't do what I want
}
Thanks for any help. I need to pass out before my head explodes
This error happens because the variable type that FindObjectWithTag returns is a GameObject, but the variable you are trying to store it in is declared as a Transform.
You just need to make sure your types match up correctly. In this case, you can either change your variable “target” to be a GameObject, or simple change the code to:
This will return the Transform property of the GameObject so that it matches the variable type of target.
This is a common problem error you will get while programming, and it’s usually just a little typo like in this case. Sometimes, though, it could mean your logic is completely wrong (using the wrong type of object in the wrong way).