- Home /
How to disable an array of projectors
So I have difficulties in understanding how does all the array things work. I am trying to disable a bunch of projectors with the same tag whenever I click the mouse. The code that I used gives me this error: 'enabled' is not a member of 'UnityEngine.Projector[]'. Any help would be appreciated.
Here is the code
private var allProj : Projector[];
private var buildingProjections : GameObject[];
function Start () {
buildingProjections = GameObject.FindGameObjectsWithTag("BuildingProjections");
for(var i : int = 0; i < buildingProjections.Length; i++)
allProj[i] = buildingProjections[i].GetComponent(Projector);
}
function Update () {
if (Input.GetButtonDown("Shoot"))
{
for(var go : Projector in allProj)
{
allProj.enabled = false;
}
}
}
I tried changing this line:
for(var go : Projector in allProj)
{
allProj.enabled = false;
}
to this:
for(var i : int = 0; i < allProj.Length; i++){
allProj[i].enabled = false;
}
but then it just gave me an error when I clicked the mouse.
Answer by fafase · Mar 02, 2014 at 08:29 PM
I think your problem comes from the fact you are not initializing your Projector array.
private var allProj : Projector[];
this is just a pointer meant to be used with an array of projector but you still need to tell how big this should be.
private var allProj : Projector[];
private var buildingProjections : GameObject[];
function Start () {
// Here the array is created inside the method and the pointer is pointing at that array
buildingProjections = GameObject.FindGameObjectsWithTag("BuildingProjections");
// Here you need to tell how many spots your array should have:
allProj = new Projector[buildingProjections.Length];
for(var i : int = 0; i < buildingProjections.Length; i++)
allProj[i] = buildingProjections[i].GetComponent(Projector);
}
Answer by MakeCodeNow · Mar 02, 2014 at 06:50 PM
The original problem is that it should have been written like this:
for(var go : Projector in allProj)
{
go.enabled = false;
}
It's also possible that your array has null entries in it, maybe that's the cause of the issue in the last block. In that case you can try this:
for(var go : Projector in allProj)
{
if(go)
{
go.enabled = false;
}
}
Thanks for correcting my code and it does look like my array has null entries. Something is wrong with this line of code
for(var i : int = 0; i < buildingProjections.Length; i++) {
allProj[i] = buildingProjections[i].GetComponent(Projector);
}
because it can not assign any projectors. Any ideas what could be wrong?