Question by
kuivalappa · Mar 11, 2017 at 06:37 PM ·
gameobjectshootingsetactiveswitchshop
SetActive between gameobjects
Hi everyone,
I'm trying to active one object at a time between five, every time I press one button and save it. But now I can only switch between two objects...
public class PlayerGun : MonoBehaviour {
public GameObject gun1;
public GameObject gun2;
public GameObject gun3;
public GameObject gun4;
public GameObject gun5;
public void Start () {
gun1.SetActive(true);
gun2.SetActive(false);
gun3.SetActive(false);
gun4.SetActive(false);
gun5.SetActive(false);
if (PlayerPrefs.HasKey("guns")){
if(PlayerPrefs.GetInt("guns") == 1) {
gun1.SetActive(false);
gun2.SetActive(true);
gun3.SetActive(false);
gun4.SetActive(false);
gun5.SetActive(false);
}
else
{
gun1.SetActive(false);
gun2.SetActive(true);
gun3.SetActive(false);
gun4.SetActive(false);
gun5.SetActive(false);
}
}
}
public void Upgradebuttom() {
PlayerPrefs.SetInt ("guns", 1);
gun1.SetActive(false);
gun2.SetActive(true);
gun3.SetActive(false);
gun4.SetActive(false);
gun5.SetActive(false);
}
public void Update () {
}
}
Comment
Best Answer
Answer by br90218 · Mar 11, 2017 at 07:41 PM
According to the code you posted you're not even switching between two guns. Your code starts out activating gun1
, and then whenever the button is pressed it turns on gun2
and stays there even if you push the button again.
What you wanna do is write something like this:
//Pseudo-code only
set all guns to inactive (false) first, and turn on the default gun
if(GetKey("The key")) {
i = a random int from 0 ~ 4
switch(i) {
PlayerPrefs.SetInt("guns", i);
turn on corresponding gun
break;
}
}
Something like above. It's a little brief but I believe you can understand the concept.