How do i find a transform by tag?

I am trying to create a script that watches a player based on tag. I can’t just use the player object as a transfrom as it spawn as a clone.

this is what i tried, but it doesn’t work…

using UnityEngine;
using System.Collections;

public class Watcher : MonoBehaviour {

    // Use this for initialization
    private Transform target = GameObject.FindWithTag("Player");

    void Update(){
        transform.LookAt(target);
    }
}

Don’t run code outside functions, only declare variables. Do Find inside Start or Awake.

–Eric

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObject : MonoBehaviour {

    private GameObject target;

    private void Start()
    {
        target = GameObject.FindWithTag("Player");
    }

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target.transform);
    }
}

You could also change the target variable to type Transform:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObject : MonoBehaviour {

    private Transform target;

    private void Start()
    {
        target = GameObject.FindWithTag("Player").transform;
    }

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target);
    }
}
5 Likes

Actually…no. You can’t put those lines in start. Then they become local variables instead of global variables, so you’re not going to be able to access them in Update.

You’ll need to declare the variables as global outside any methods. (after the public class is normally a good spot).
Then you’ll do your GameObject.FindWithTag inside start, assigning the values to the variables you declared. Then you update can access them.

2 Likes