- Home /
C# For loop in button to set gameObjects in array to active
I have multiple buttons in my scene which, when selected using oculus touch controllers with NewtonVR, the player teleports to and the button is set to inactive. When they then move to another button, I want the button to be set to active, but it doesn't work. The array contains the buttons which are all assigned in the inspector. Here is my code:
public class PlayerMoveTo : MonoBehaviour {
public GameObject player;
GameObject parent;
public GameObject[] previousLocation;
private void Start()
{
previousLocation = new GameObject[7];
}
public void MoveTo()
{
parent = transform.parent.gameObject;
player.transform.position = parent.transform.position;
gameObject.SetActive(false);
foreach (GameObject i in previousLocation)
{
i.SetActive(true);
}
}
}
I originally had a series of if/else if doing the same thing minus the array but that's poor coding standard and annoying to add more buttons. I also tried for(int i = 0; i < previousLocation.Length; i++) but this didn't work either. What am I missing?
Answer by sisse008 · Jan 09, 2018 at 02:47 PM
im not exactly sure i understand what you are trying to do but this might be an easy fix.
gameObject.SetActive(false);
kills the gameobject which is holding this script. which mean that all the components which the gameobject holds (including this script) stop running.
theres nothing wrong with your loop, but the script stops running before you get to it.
Thank you! $$anonymous$$oving gameObject.SetActive(false) below the loop fixed it.
Your answer
Follow this Question
Related Questions
Null reference when editing an array in a for loop 1 Answer
How would I find the name of all game objects in a c# List 1 Answer
foreach a array inside a generic list 1 Answer
C# Killfeed issues 0 Answers
Values in Array Automatically Revert 1 Answer