- Home /
Question by
TheJakanator · May 01, 2020 at 06:22 AM ·
scripting problemarrayarrays
Trying to disable all gameobjects in an array except one, why doesnt this work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weaponsManager : MonoBehaviour
{
public GameObject[] weapons;
public int selected;
public int slots;
void Update()
{
for (int i = 0; i < weapons.Length; i++) //The "iBall" for-loop Goes through all of the Array.
{
if (i == selected) //If "iBall" for-loop calls the current object, skip it.
{
weapons[selected].gameObject.SetActive(true);
}
else //If "iBall" for-loop is anything but the current gameobject, deactivate it.
{
weapons[selected].gameObject.SetActive(false);
}
}
}
}
Comment
Answer by noyco · May 01, 2020 at 06:52 AM
I think you have to change:
weapons[selected].gameObject.SetActive(true);
To
weapons[i].gameObject.SetActive(true);
Answer by yummy81 · May 01, 2020 at 08:27 AM
I'm curious why you put weaponsManager into the array, but if it's for some excercise or testing purposes then play with the code I wrote. I introduced activateAll bool, which if false deactivates all the gameobjects in the array except the one the script is on, and to the contrary, if true activates all the gameobjects in the array, still not touching weaponsManager. I used Linq extension methods. Enjoy:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class weaponsManager : MonoBehaviour
{
public GameObject[] weapons;
public bool activateAll;
void Update() => weapons.Except(new GameObject[]{gameObject}).ToList().ForEach(g=>g.SetActive(activateAll));
}