Been trying to get a camera to follow an object but I can’t find the script that calls an objects position. Wondering if anyone knows a way to get a camera to follow an object or call its position.
Sorry if this is a dumb question, new to Unity 5 and C#, Cheers ![]()
Each game object has a transform component. This component contains positional information about the game object. Including the position in the world (world space), rotation in the world and object scale. The position and rotation also have a local space counterpart but at the moment you won`t have to worry about that.
Usually when you want a camera to follow a game object you would attach a script to the camera. Here is a very very simple example:
I haven’t tested this yet but something like this should work.
You need to assign the TargetObject in the inspector.
public class SimpleFollowCamera : MonoBehaviour
{
/// <summary>
/// The object we will follow
/// </summary>
public Transform TargetObject;
/// <summary>
/// The offset (distance) we look at the object from in each axis
/// </summary>
public Vector3 PositionOffset = new Vector3(10, 10, 10);
/// <summary>
/// should we look at the target
/// </summary>
public bool LookAtTarget;
protected Transform myTransform;
public void Start()
{
myTransform = GetComponent<Transform>();
}
/// <summary>
/// Use late update as we will modify the camera position after ALL objects have finished moving
/// including animated objects
/// </summary>
public void LateUpdate()
{
// do we actually have a target?
if(TargetObject)
{
myTransform.position = TargetObject.position + PositionOffset;
if(LookAtTarget)
{
myTransform.LookAt(TargetObject);
}
}
}
}
Thanks, I think I get it now. I’ll try testing it tonight ![]()
Cheers for the reply
Sorry, when you were talking about the targetObject, would that be the name of the Object itself?
Edit*
Is this script for unity 5.3?
Getting a few errors, although its not a direct import of your code so its probably on my end. main errors include ‘LookAtTarget’ do I need to assign it? and a few other Context errors.
Sorry about this, not particularly experienced at C# and Unity
Hey, Yeah you need to select the game object. If you click in the variable in the inspector, you should be able to select a game object.
What is the error for LookAtTarget?
LookAtTarget does not exist in the current context
uhhh