When my player dies and respawns, I'm trying to have my camera look at the newly-instantiated player. Here's the code
public class CameraController : MonoBehaviour
{
void Update()
{
var target = GameObject.FindGameObjectWithTag("Player");
Transform target;
transform.LookAt(target);
}
}
I'm trying to do it without a public "drag-and-drop" Transform variable.
I didn't have any problems with just my base player, but when I tried to respawn it with Instantiate(), the camera cannot detect the copies.
CodePudding user response:
well remove that Transform target;
and rather use
transform.LookAt(target.transform);
... in general for performance sake you should avoid using any of the Find
variations in Update
but do it Once in e.g. Start
and reuse the reference
public class CameraController : MonoBehaviour
{
private Transform target;
private void Start()
{
target = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
transform.LookAt(target);
}
}
CodePudding user response:
I've found a solution. To any other people looking for something similar:
public class CameraController : MonoBehaviour
{
Transform target;
void Update()
{
GameObject target1 = GameObject.FindGameObjectWithTag("Player");
target = target1.transform;
transform.LookAt(target);
}
}
CodePudding user response:
The initial problem you're having is you are finding the GameObject of the player which is the type 'var' will be set to. After that, it's being overwritten when you set target to be of type Transform with a null value. Getting the Transform component of the Player and setting target to equal that will solve your issue.
Performance-wise however:
You want to avoid searching for gameobjects in an Update(), instead find what you're searching for one time and cache it. Finding a gameobject is an expensive action and having it inside of Update() will perform that action every cycle.
A more CPU-friendly way to handle it would look like:
Transform target;
public void findTarget(string targetToFind)
{
// potentially do some error handling here in case the gameobject hasn't loaded in yet
target = GameObject.FindGameObjectWithTag(targetToFind).transform;
}
void Update()
{
transform.LookAt(target);
}
How I would have this work is upon character respawn, call the findTarget method on the script passing it the player tag. It also makes the method more generalized so you can do additional camera shift tricks if you desire to have the camera move to a different target for a cinematic event or something similar.