accessing another game objects properties

am a beginner in unity and am doing a side scroller game demo. i want to access player’s x transform position in order to make my camera along with the player in the x direction. my basic script is below, but i dont know where the problem is. need help

using UnityEngine;
using System.Collections;

public class camera_mov : MonoBehaviour {

public GameObject target_object;
float cameraTransform;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () 
{ 
	cameraTransform = player.transform.position.x;
	transform.Translate(cameraTransform, 0, 0);
}

}

this is the error message i get.

Assets/scripts/camera_mov.cs(17,35): error CS0103: The name `player’ does not exist in the current context

i have connected the player in the inspector with the target_object.

1 Answer

1

If this script is attached to the camera, you don’t need the

float cameraTransform

You don’t have a reference to Player, I think what you mean is the target_object. If it helps, rename the target_object variable to player.

You cannot directly modify a transform. Instead you should do this:

cameraTransform.position = new Vector3(target_object.transform.position.x, transform.position.y, transform.position.z);

This assigns the camera transform a new position using the target_transforms x position and the cameras current y and z position. All this is constantly happening as you have it in the Update() function.

The script attached to the camera would essentially look like this:

using UnityEngine;
using System.Collections;

public class camera_move : MonoBehaviour{
 public GameObject player;

 void Update(){
  transform.position = new Vector3(player.transform.position.x, transform.position.y, transform.position.z);
 }
}

Remember to assign the player GameObject to the public variable Player in the Inspector.

Hope this helps.

thanks for the reply, but am not getting the idea. cameraTransform = player.transform.position.x; transform.Translate(cameraTransform, 0, 0); transform.position = new Vector3(player.transform.position.x, transform.position.y, transform.position.z); wat is difference between these two. sorry iam not arguing, i got confused. i want some explanations. could you help me.