Problem with camera follow

Hi. I’m trying to make a camera follow script (2d topdown) that will get my character automatically since my game is proceduraly generated. I have been using GameObject.Find but my problem is for this I need my variable to be a GameObject, but for the rest of the script it needs to be a Position.

using UnityEngine;
using System.Collections;

public class camerafollow : MonoBehaviour {

    public GameObject myTarget;
   
    //Start is called on load
    void Start() {
        myTarget = GameObject.Find("paladin-inventory(Clone");
   
    }
    // Update is called once per frame
    void Update () {
        if (myTarget != null) {
       
        Vector3 targPos = myTarget.position;
        targPos.z = transform.position.z;
        transform.position = targPos;
           
        }

New to coding and this is giving me bit of a problem

on line 17, instead of “myTarget.position;” try “myTarget.transform.position;”

Thanks for the reply, this fixed the error but still does not cause camera to follow. Help is appreciated (although that was very helpful)

That looks like it should follow the player on the x and y axis… are you sure “myTarget” isn’t always null? The “Start()” function only ever gets called once just before the first time “Update()” is called, so if it’s unable to find the player then, it will never find the player.

Make sure that “myTarget” is being correctly found, otherwise your code will not run.

If myTarget exists in the editor, it should be finding it with the correct name applied, if it’s generated through a script it sounds like it might be a script execution order issue. (That it gets generated after your code tries to find it.)

I’m noticing that “paladin-inventory(Clone” is missing a bracket inside the string, I don’t know what you have your names set up as, but it seems likely that typo is causing a name mismatch. :slight_smile: