hi everyone! I am new to C# and Unity and would like to ask different ways on writing this code:
public GameObject player;
public Vector3 offset1st = new Vector3(0, 5, -7);
public Vector3 offset3rd = new Vector3(0, 0, -7);
private bool CamSwitch;
void Start()
{
player = GameObject.Find("Vehicle");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)) {
CamSwitch = !CamSwitch;
}
}
void LateUpdate()
{
if (CamSwitch)
{
transform.position = player.transform.position + offset3rd;
}
else if (!CamSwitch)
{
transform.position = player.transform.position + offset1st;
}
}
I successfully made this simple code working toggling between Cameraâs first and third person view on a driving game. Just wondering if there are better ways to write this.
Well there are few issues with it. The most noticeable is that LateUpdate will execute one of two position changes even when nothing has changed. You probably need a private bool to represent itâs current position.
I canât actually tell but it appears that having possibly set the player object (itâs public BTW) you actually want the Vehicle game object. If you can assign that rather than Find it you would be slightly better off.
And the formulas you have in LateUpdate are âidenticalâ save the offset used. That can easily be a single line with a ternary operator to determine which offset to use.
In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.
If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way⢠success of accessing things in your game.
âStop playing âWhereâs GameWaldoâ and drag it in already!â