- Home /
Variable Switch on Button Press
Hi, i want to make a Camera-Switcher in my Script. But my script is not working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OpenCvSharp;
public class FaceDetector : MonoBehaviour
{
public int Camera;
WebCamTexture _webCamTexture;
// Start is called before the first frame update
void Start()
{
WebCamDevice[] devices = WebCamTexture.devices;
_webCamTexture.Play();
}
// Update is called once per frame
void Update()
{
GetComponent<Renderer>().material.mainTexture = _webCamTexture;
_webCamTexture = new WebCamTexture(devices[Camera].name);
}
}
Assets\Scripts\FaceDetector.cs(23,44): error CS0103: The name 'devices' does not exist in the current context
What am I missing here?
Answer by sacredgeometry · Mar 06 at 12:45 PM
devices[Camera].name should be WebCamTexture.devices[Camera].name
You cant use local variables from an entirely different scope.
So how would you change it. Im new to C#, so I dont know exactly how to do it.
The same way you would in most other languages. Move it to a different level of scope. i.e. make devices a class member instead of a variable defined inside a method.
https://www.geeksforgeeks.org/scope-of-variables-in-c-sharp
That said as its a member on a static class, there really isn't much point doing it as is WebCamTexture.devices any less descriptive than devices?
I would move all of the code in your Update method into a start because there is really no need to do that thousands of times i.e. in every frame.
public class FaceDetector : MonoBehaviour
{
public int Camera;
private WebCamTexture _webCamTexture { get; set; }
void Start()
{
_webCamTexture = new WebCamTexture(WebCamTexture.devices[Camera].name);
GetComponent<Renderer>().material.mainTexture = _webCamTexture;
_webCamTexture.Play();
}
}
Your answer
Follow this Question
Related Questions
how do I fixate a position through script. 1 Answer
Making a gameobject inactive and locating a clone. What's wrong with the script? 1 Answer
How do i give Coordinates (x, y) to an Array 1 Answer
Ways to make OnMouseDown (or a single script) differentiate between different colliders/sprites 1 Answer
c# - List with multiple types - Trading Engine - Stock Simulator 2 Answers