I'm trying to make a script that contains a list of Cameras. The intention is for the player to have a number of Cameras that they can switch back and forth through at will (kind of like Friday night at Freddy's) and later on the player can add more cameras which is why I decided on using a list instead of an Array.
However, when I tried to make a script with that list, I got this error
Argument 1: cannot convert from 'UnityEngine.Camera[]' to 'UnityEngine.Camera' [Assembly-CSharp]
This is the code I wrote:
using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class CameraList : MonoBehaviour {
public List <Camera> _cameras = new List <Camera>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
_cameras.Add(Camera.main);
_cameras.Add(FindObjectsOfType<Camera>());
}
}
CodePudding user response:
Try this
using System.Collections.Generic;
using UnityEngine;
public class CameraList : MonoBehaviour
{
private List<Camera> cameras = new List<Camera>();
private void Start()
{
cameras.Add(Camera.main);
// or to add all cameras in scene
cameras.AddRange(FindObjectsOfType<Camera>());
}
}
Argument 1: cannot convert from 'UnityEngine.Camera[]' to 'UnityEngine.Camera' [Assembly-CSharp]
The reason why you get this error, that is because you are using FindObjectsOfType, this will return array of each found item with given type, you should use cameras.AddRange(FindObjectsOfType<Camera>());
Also your camera should have tag "MainCamera" to use Camera.main. And don't add to list from Update like that.
CodePudding user response:
As a previous answer stated, you want to use:
cameras.AddRange(FindObjectsOfType<Camera>);
This is because .Add
does not take an array (the return value of ‘FindObjectsOfType’) as an argument.
Some tips that may prove useful to you:
Do NOT add to the List cameras
in Update:
For your purpose, because it’s essentially an initialization, this is a logical error. You only want to add the cameras you need once; Add to cameras
in Awake
or Start
instead.
The consequence of skipping this step is, poorer performance and bugs.
Do NOT add Camera.main
to cameras
:
Use only .AddRange
instead.
The consequence of skipping this step is, a logical error where the main-camera is present twice in the List. This is because Camera.main
is also apart of the FindObjectsOfType<Camera>
collection.
Do make List cameras
private:
There isn’t a reason for cameras
to be public.
The consequence of skipping this step is, aside from design principles of OOP, this may lead to bugs where a change in made in the Unity Editor is reflected in the collection. For example, adding the Main Camera from the UnityEditor and then having a duplicate from FindObjectsOfType