- Home /
Problem is not reproducible or outdated
Array of bool doesn't change in other script
the code is :
using UnityEngine;
using UnityEngine.UI;
public class InventorySlot : MonoBehaviour { // Scrpit A
public bool[] buttonState = new bool[2];
void Update ()
{
if (Input.GetKeyDown (KeyCode.Alpha1) || Input.mouseScrollDelta.y > 0)
{
buttonState [0] = true;
buttonState [1] = false;
}
if (Input.GetKeyDown (KeyCode.Alpha2) || Input.mouseScrollDelta.y < 0)
{
buttonState [0] = false;
buttonState [1] = true;
}
public bool ButtonIsActive (int index)
{
return buttonState[index]; // true or false from the update funaction
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System.Collections;
using UnityEngine;
public class CollectShiled : MonoBehaviour { // Scrpit B
public InventorySlot inventory; // I put it in the incpector
void Update ()
{
if (Input.GetKeyDown ("space") && inventory.ButtonIsActive(index)) // index =1 or 0
{
// Do something
}
}
the problem is in the script A always return true !
public bool ButtonIsActive (int index)
{
return buttonState[index];
}
$$anonymous$$ight not be relevant but where's the variable index stored in your CollectShiled class? There seem to be some code missing as that wouldn't compile as is.
Yes , variable index in CollectShiled class , but i removed unnecessary part to make it more clear if you want to see full code i will send it
int index = Shiled.index; // where index is 1 or 0
Answer by $$anonymous$$ · Sep 08, 2018 at 11:51 AM
If you want it to be only true if the key is held down you have to Input.GetKey Instead and create an else statement that sets the bools to false.
I want to this ButtonIsActive() to return the current value of buttonState[] but it's always return true !
So it does return true no matter what key you pressed? Have you tried Debug.Log the mouse.Scrolldata?
It's work correctly when i print the value from the script A and the mouse.scroll work correctly but when i call the function ButtonIsActive() from script B it's return true always . I think the problem in the array do you have any idea ?
I tried it on my pc and it works perfectly fine for me. If I press Alpha1 the element 0 gets true and element 1 gets false. If I press Alpha2 the element 1 gets false and element 1 gets true. I made a Debug if I press space and the current index is true, and it works.
What does the scene look like? Are the two scripts on the same gameobject? $$anonymous$$aybe you acess a disabled inventorySlot script and because of that the buttonState never changes? Or does maybe another script change the buttonState? I dont really see another reason why it should only return true...