Help with js conversion to c#
So, I need some help with a js to a c# conversion and some errors, the error I get is that the transform.position doesn't work neither do GetComponent. Heres the full script:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour
{
Transform Player;
float DistanceFromPlayer = 5;
float StaticCameraY = 3;
void Update()
{
transform.position.z = Player.position.z - DistanceFromPlayer; // Error in c# not js
transform.position.x = Player.position.x + 6; // Error in c# not js
}
void LateUpdate()
{
GetComponent.< Camera > ().main.transform.position.y = StaticCameraY; // error in c# but not js
}
}
I'm pretty new to scripting so if you could describe what you're doing that would be appreciated.
The correct version in c# due to using structs(Vector3). A reference is necessary to modify the struct, this will copy the current values and allow you to modify only what is needed:
using UnityEngine;
using System.Collections;
public class FollowCamera : MonoBehaviour
{
Transform Player;
float DistanceFromPlayer = 5;
float StaticCameraY = 3;
void Update()
{
Vector3 tempPos = transform.position; // Get a copy of the Vector3 struct.
// make modifications
tempPos.z = Player.position.z - DistanceFromPlayer;
tempPos.x = Player.position.x + 6;
// Re-apply the struct
transform.position = tempPos;
}
void LateUpdate()
{
Camera c = GetComponent.< Camera > ().main; // get a reference to the camera first to reuse getting the position and setting it later.
Vector3 tempPos = c.transform.position;
tempPos.y = StaticCameraY;
c.transform.position = tempPos;
}
}
Answer by aditya · Oct 25, 2016 at 09:06 AM
This is because in c# you can't directly change an element of transfor.position, what you had to do is save this position in a temporary local vector3 and change the element of this vector3 and assign it back to your position ... i don't know about JS but in c# GetComponent works like this
Getcomponent<YOUR CLASS>();
GetComponent<YOUR CLASS>().classMember;
but in your code as you are trying to modify the position of MAIN camera then there is nothing to do with Getcomponent here, simply call
Camera.main.transform.position
Accept if it Helps ^^
Fixed the script, but thank you for makking me understand what the problem was, really helpful!
Your answer
Follow this Question
Related Questions
How To refer to other Object's Components ? 0 Answers
Scroll-view Database 0 Answers
Opening and closing a Gate on Input.GetButtonDown 0 Answers
Issues Cycling Through Weapons-C# 2 Answers