Question by
Aurieen · Nov 21, 2020 at 12:09 PM ·
c#scripting probleminstantiatebooleanbool
How to change the Bool for only a single prefab GameObject creating with Instantiate?
Hi, newbie here. My aim is to turn the color of each created object first to white then to black. My problem is that I couldn't figure out how to assign and / or check the bool for each created object. It's my code here :`
public class GameManager : MonoBehaviour
{
[SerializeField]
GameObject ballPreF;
[SerializeField]
Transform ballPanel;
//bool checkPBall = true;
GameObject[] ballsArray = new GameObject[10]; //This number is increasing
GameObject selectedBall;
void Start()
{
BallCreator();
}
public void BallCreator()
{
for (int i = 0; i < 10; i++)
{
GameObject ball = Instantiate(ballPreF, ballPanel);
ball.transform.GetComponent<Button>().onClick.AddListener(() => ClickedB());
ballsArray[i] = ball;
}
}
void ClickedB()
{
selectedBall = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject;
bool checkPBall = true;
if (checkPBall == true)
{
selectedBall.transform.GetComponent<Image>().color = new Color(255, 255, 255);
checkPBall = false;
//Debug.Log(checkPBall);
}
else if (checkPBall == false) //not working i don't know why??
{
selectedBall.transform.GetComponent<Image>().color = new Color(0, 0, 0);
selectedBall.transform.GetComponent<Button>().interactable = false;
//Debug.Log(checkPBall);
return;
}
Debug.Log(checkPBall); //return false
//UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.transform.GetComponent<Image>().color = new Color(255, 255, 255);
}
}
`
Comment
Answer by TheGodling · Nov 21, 2020 at 12:38 PM
When you first create checkPBall you are assigning it to be true, you then have an if statement directly after that checks its state. This could never reach the else if statement as you are always setting it to be true right before the if true statement. Was this intentional?
Yes and no i tried it everywhere(global etc.). Because everywhere except "ClickedB" the "else if" statement is used after the second click and the "if" statement is not used for another ball.