'How do I find the location of an object through code
I'm trying to attach the camera to a character's xPos without grouping the camera to the player
Solution 1:[1]
The thing to be careful about is whether you mean you want the camera to be linked to the character's local x-position or if you want the camera to be linked to the character's world x-position. The two will vary based on the transforms of the character's parent GameObjects.
You can either tag the character and find it by doing a lookup in Start() or you can make the character reference a public GameObject targetCharacter in your camera script and set the reference manually in the editor.
Once you determine how you're going to do it:
public class CameraLocator : MonoBehaviour
{
public GameObject targetCharacter;
void Start()
{
if(targetCharacter == null)
{
targetCharacter = GameObject.FindGameObjectWithTag("YourCharacterTag");
if(targetCharacter == null)
{
Debug.LogError("targetCharacter is not set and could not be found!");
}
}
}
void Update()
{
if(targetCharacter != null)
{
var camPosition = this.gameObject.transform.position;
var targetPosition = targetCharacter.transform.position;
camPosition.x = targetPosition.x;
this.gameObject.transform.position = camPosition;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chuck |
