I am kind of new to Unity. I am trying to follow a game tutorial on YouTube, but the guy uses UnityScript instead of C#. I won’t be using UnityScript/JavaScript on my games so I have been trying to translate his tutorial as a go from JavaScript to C#. I hit a roadblock from a small scrip that he made to control the camera so that it can follow the ship:
His script. written in javaScript/UnityScript:
var Target : Transform;
var Distance : float = 14;
var CameraY : float = 12;
function Update() {
transform.position.z = Target.position.z -Distance;
transform.position.x = Target.position.x+7;
}
function LateUpdate() {
GetComponent.<Camera>().main.transform.position.y = CameraY;
}
Here is my attempt at translating it to C#:
using UnityEngine;
using System.Collections;
public class CameraScript : MonoBehaviour {
Transform Target;
float Distance = 15.0f;
float CameraY = 10.0f;
// Update is called once per frame
void Update () {
transform.position.z = Target.position.z - Distance;
transform.position.x = Target.position.x + 5;
}
void LateUpdate()
{
GetComponent<Camera>().transform.position.y = CameraY;
}
}
I keep getting an error at the “transform.position.z” and “transform.position.x” that says: "Cannot modify the return value of ‘Transform.position’ because it is not a variable’
my attempt at the LateUpdate function is all kinds of jacked up.
If your only roadblock is changing transform.position, in C# of Unity Transform.Position only takes in a Vector3. you cannot edit the individual values. What you want is to create a Vector3, manipulate it as if it is transform.position, and re-apply it to transform.position.
Oh and use code tags for displaying your code in your post, like this:
I think that’s what you’re looking for. I’m also sure that’s correct, but not 100% since I wrote this while at work without access to unity API or an IDE.
This is my final code, which didn’t show any errors. Could you please check it out and tell me whether it will perform the same as the original UnityScript version? can I make the code better? I will post both the original code and mine for your convenience:
Original UnityScript Code:
var Target : Transform;
var Distance : float = 14;
var CameraY : float = 12;
function Update() {
transform.position.z = Target.position.z -Distance;
transform.position.x = Target.position.x+7;
}
function LateUpdate() {
GetComponent.<Camera>().main.transform.position.y = CameraY;
}
Main improvement I would suggest is making tempCamera and tempPosition local variables instead of class variables. Like this. This is better practice and closer to the original.
The other subtle change you have introduced is that the access modifiers to Target, Distance and CameraY have changed. In UnityScript they default to public, in C# they default to private. The main effect of this change is the variables will not be configurable from the inspector. The best practice is actually to tag them with [SerialiseField].