I am trying to attach a camera (so that it follows the player) to a player using an int that is set when the player is spawned into the scene. i.e when the player prefab is spawned in it has a script attached that denotes its player number. I cannot figure out how to use this int as the target for my camera to follow. Any help would be greatly appreciated, I am still very much learning all of this. Thanks in advance.
Script on spawned-in player object.
public class CarInputHandler : MonoBehaviour
{
public int playerNumber = 1;
//Components
TopDownCarController topDownCarController;
//CarSFXHandler carSFXHandler;
void Awake()
{
topDownCarController = GetComponent<TopDownCarController>();
//carSFXHandler = GetComponent<CarSFXHandler>();
}
void Update()
{
Vector2 inputVector = Vector2.zero;
switch (playerNumber)
{
case 1:
//Get input from unity
inputVector.x = Input.GetAxis("Horizontal_P1");
inputVector.y = Input.GetAxis("Vertical_P1");
break;
case 2:
//Get input from unity
inputVector.x = Input.GetAxis("Horizontal_P2");
inputVector.y = Input.GetAxis("Vertical_P2");
break;
case 3:
//Get input from unity
inputVector.x = Input.GetAxis("Horizontal_P3");
inputVector.y = Input.GetAxis("Vertical_P3");
break;
case 4:
//Get input from unity
inputVector.x = Input.GetAxis("Horizontal_P4");
inputVector.y = Input.GetAxis("Vertical_P4");
break;
}
//send input to the CarController
topDownCarController.SetInputVector(inputVector);
}
}
My camera Follow script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public Vector3 offset;
CarInputHandler[] carInputHandlerArray;
public CarInputHandler carInputHandler;
public int playerNumber = 0;
private void Awake()
{
StartCoroutine(CameraDelayCo());
}
//allow player to spawn in scene before player finding player object/components/scripts
IEnumerator CameraDelayCo()
{
yield return new WaitForSeconds(1);
carInputHandlerArray = FindObjectsOfType<CarInputHandler>();
carInputHandler = GetComponent<CarInputHandler>();
if (carInputHandler.playerNumber == 1)
{
target = carInputHandler.transform;
}
}
private void FixedUpdate()
{
if (target == null)
{
return;
}
else
{
transform.position = target.position + offset;
}
}
}