Trying to instantiate a prefab to transform.LookAt(target);

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 :confused:

using UnityEngine;

using System.Collections;

 

public class LookAt : MonoBehaviour 

{

 

    public Transform target;

    void Start()
{


     target = GameObject.FindGameObjectWithTag("Player");
}

    

        

        void Update()

        {

            if(target != null)

            {

            transform.LookAt(target);

            }

        }

    }

and in the hierarchy select your player gameobject and in the inspector see the tag option and select the Player tag and you are ready :wink:

Unfortunately I get an error using your modified script.

Assets/_Scripts/LookAt.cs(37,17): error CS0029: Cannot implicitly convert type UnityEngine.GameObject' to UnityEngine.Transform’

37,17 of the script is LINE 19 shown on your code block.
target = GameObject.FindGameObjectWithTag(“Player”);

I do have my player set up with the Tag Player.

Thanks for you help.

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:

target = GameObject.FindGameObjectWithTag("Player").transform;

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).

That did the trick. Thank you. Also thank you for the explanation. That will help me better understand and maybe fix my own errors soon enough. :slight_smile: \

ohh sorry @ensabguine thanks for correcting me