So ive attatched this code to my main camera, and tagged my player with the tag “Player”
private Transform targetedPlayer;
void Start () {
targetedPlayer = GameObject.FindWithTag("Player").transform;
}
void LateUpdate () {
//Moves camera into position at the same time as movement refreshes, and puts the camera back at Z -10
transform.position = targetedPlayer.position + new Vector3(0, 0, -10);
}
The reason as to why this doesnt work is because the script sometimes clones the player position, instead of hooking onto it as shown in the screenshot
it works as intended, but i want my code to be more flexible so that if i want to switch the player character in game in the future, i just have to change the tag instead of the whole name.
the only way you are going to clone the player is to Instantiate it. Nothing about the code copies the player, and when I do this same test, I do not get the same result.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class test : MonoBehaviour {
public Transform player;
void Start() {
player = GameObject.FindWithTag("Player").transform;
}
void Update() {
transform.position = player.position + new Vector3(0, 0, -10);
transform.LookAt(player);
}
}
Clone is added to the end of a name when you call Instantiate. Looks like you are creating your player more then once, or you have more then one player in the scene. This would also explain what Find works (the names are unique) and FindWithTag doesn’t.
Try clicking on the clone in the inspector. It will show you where the clone is in the hierarchy.
Yeah, i think i found the problem and you were about right
In my player script i had this
transform.position = new Vector2(0, 0);
which i basically used for easily moving the player without having to mess around in the editor, although when i removed it the camera started working.
But the wierd part about this is that when i put it back in, and run the script, the camera magically still works
Maybe this has to do with if the camera target function triggering before the position change, leading to the camera hooking onto an old vector2 position, since they are both located in the start function, but in two different scripts, and one of them has to trigger before the other.