Hey, guys. I need help with a problem I’m having with a GameObject array in my horror game. I’ll keep it simple, I have six GameObjects in an array that, once clicked upon, I want to all do the same thing. Can someone please help me, or at least tell me what’s wrong with my code? Here’s the code
public class ActivateGenerators : MonoBehaviour
{
public GameObject Player;
public GameObject Generator;
public GameObject redLight;
public GameObject greenLight;
public GameObject[] GeneratorArray;
void Start()
{
redLight.SetActive(true);
greenLight.SetActive(false);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
if (hit.collider.GetComponent("Generator"))
Destroy (redLight);
greenLight.SetActive(true);
}
{
}
}
}
I think you need to clean up some of your indentation and brackets, particularly after line 21. You have if() clauses that are nested and you have no brackets to control block scope, which makes it misleading as to what is going on.
Indentation in C# does nothing code-wise, it is just to reinforce your own visual notion of what the code flow is. I recommend ALWAYS using brackets with if() clauses, even if you are only doing one thing, in order to cut down on this sort of confusion.
For instance, your code looks like:
if (a)
if (b)
dothing1();
dothing2();
What it is ACTUALLY doing is this:
if (a)
{
if (b)
{
dothing1();
}
}
dothing2();
And I don’t think that is what you want. If you put the brackets in religiously after each if() clause you will begin to see what is going on.
As for the array question, the only array I see in your code sample is GeneratorArray but you are not referencing it anywhere that I can see.
Kurt is correct you have some issues with the brackets. In your post you talked about an array, but you’re not accessing the array in you script.
your line 22, do you have script named Generator on the game object? This If statement will be false if you don’t
I’ve built a script that fixes the brackets and sets the lights on all the objects in the array.
using UnityEngine;
using System.Collections;
public class ActivateGenerators : MonoBehaviour
{
public GameObject Player;
public GameObject Generator;
public GameObject redLight;
public GameObject greenLight;
public GameObject[] GeneratorArray;
void Start()
{
redLight.SetActive(true);
greenLight.SetActive(false);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log("i hit Something");
if (hit.collider.GetComponent("Generator"))
{
Debug.Log("it was a generator!");
for (int i = 0; i < GeneratorArray.Length; i++)
{
Debug.Log("Change states for object " + GeneratorArray[i].name);
Destroy(GeneratorArray[i].GetComponent<ActivateGenerators>().redLight);
GeneratorArray[i].GetComponent<ActivateGenerators>().greenLight.SetActive(true);
}
}
}
}
}
}