Hello everyone,
I am developing an AR app to spawn a game object in my scene, and then switch between its two configurations with a UI button.
I have a prefab of the game object in my project folder that is composed of the two configurations required.
I managed to have it spawn without a problem but I’m struggling with the configuration switch part.
So far I have :
A script like the following on each configuration :
public class ConfigOneScript : MonoBehaviour {
public PositionSwitch positionScript;
void Update()
{
if (positionScript.configState)
{
gameObject.SetActive(false);
}
else
{
gameObject.SetActive(true);
}
}
}
and a script that’s in an empty game object in my scene :
public class PositionSwitch : MonoBehaviour
{
public bool configState;
private void Start()
{
configState = false;
}
public void MachineConfiguration()
{
configState = !configState;
}
}
I am a self taught newbie when it comes to coding so I’m pretty sure it’s something simple that I missed, but if anyone could help me I’d be most appreciative.
PositionSwitch is supposed to activate when I press a UI Button.
I have a script for each configuration (which I’m sure isn’t the right way), ConfigOneScript and ConfigTwoScript. They are built the same way. but one activates its respective gameObject when configState is true, and the other one when it is false.
At the moment, the UI Button doesn’t seem to work for both scripts, or (and that was my original assumption) the boolean doesn’t work properly. What happens is the object spawns with configuration one enabled (which is good), but when I press the UI Button to switch the configuration, the first one disappears but the second one fails to activate. Basically I start with the back of my machine in config one and end up with no configuration at all, even if I press the UI Button again.
One thing I noticed is that the configuration does switch when I change the original state of the configState boolean manually.
I am not quite familiar with passing a boolean to other classes so I can’t tell if I did it properly or not.
There could be other easier ways to achieve what I have in mind.
The difficulty, I found, is the fact that the game objects aren’t in the scene from the beginning. Switching between two game objects with a UI Button is easy enough usually, but I couldn’t make it work with prefabs because it would affect the prefab and not its spawned version in the scene.
My first hunch was to try and find the configurations after they spawned by finding them using respective tags in a void Update(), as follows :
As far as I can see is that you’re turning on/off two GameObjects. And I think you’re trying to turn on/off two scripts? I’m not sure what you desired outcome is. Either way, I would try to make seperate methods of both configurations in your PositionSwitch class. Then you could just call either of the methods by ConfigOne(bool); and ConfigTwo(bool); if you’d design them that way…