Although I’ve already managed to do relatively pretty fancy stuff in procedual programming some simple concepts still elude me.
How do I replace the variable “CameraNumber” with the number “1” under “OnTriggerEnter”?
using UnityEngine;
using System.Collections;
public class CameraCollider : MonoBehaviour {
public Camera Camera1;
private int CameraNumber;
// Use this for initialization
void Start () {
CameraNumber = gameObject.name[13];
}
// Update is called once per frame
void OnTriggerEnter () {
Camera1.enabled = true;
}
}
May not return the number you expect. This will return the ASCII value of the 13th character in the name of this gameobject. So the character if the 13th character in the gameobject name is a “1” then 49 is stored in CameraNumber.
To get back to your main question. You want to access an array of all cameras in scene.I’m not aware of a good way to retrieve all cameras in the scene (GetAllCameras only gets active cameras) so I setup this array manually using the inspector by dragging all cameras into the allCameras entry for this script. You can likely come up with a better solution if needed.
You’re trying to use the text “Camera” and the variable value of 1, and combine them together into the variable name Camera1. You cannot do this in regular, C# programming, as there’s no real link between the sourcecode variable names and the runtime values of those variables.
What you’re trying to do could be done in an interpreted programming language. You could do it with the help of dictionaries - by mapping string-names to camera variables, and you could do it through the dirty, dirty hack of reflection. All of these solutions are far more advanced than simply doing this in some sane way, and are also really, really, really slow.
If you just want to find a camera named “Camera1” or “Camera2” why don’t you just use the GameObject.Find method.
public class CameraCollider : MonoBehaviour {
public Camera CamToToggle;
private int CameraNumber;
// Use this for initialization
void Start ()
{
CameraNumber = 1;
}
// Update is called once per frame
void OnTriggerEnter () {
CamToToggle = GameObject.Find("Camera"+CameraNumber).GetComponent<Camera>();
CamToToggle.enabled = false;
}
}