How do I fix my code so that these If statements turn an object off or on depending on a number
I have the code down below able to produce a random number but it only turn one object on each time it picks the same object each time no matter the number.
using UnityEngine;
using System.Collections;
public class RandomAudio : MonoBehaviour
{
public GameObject One;
public GameObject Two;
public int Fun;
// Use this for initialization
void Start()
{
Fun = Random.Range(1,3);
}
public void StartMusic()
{
if (Fun == 1)
{
One.gameObject.SetActive(true);
Two.gameObject.SetActive(false);
}
if(Fun == 2)
{
Two.gameObject.SetActive(true);
One.gameObject.SetActive(false);
}
}
// Update is called once per frame
}
Could you add a Debug.Log() in the Start() method to print out the value of Fun and in Start$$anonymous$$usic() to see the ti$$anonymous$$g of those methods? Is Start() called before Start$$anonymous$$usic() (e.g. is Start$$anonymous$$usic() called from some Awake() method?).
What is the value of Fun in the inspector (as it is public)?
Answer by hellojbb1234 · Oct 04, 2016 at 10:02 PM
Right You guys aren't to helpful with this type of stuff you overcomplicated it. Just do this next time
using UnityEngine;
using System.Collections;
public class RandomAudio : MonoBehaviour {
public float NumberSelect;
public GameObject One;
public GameObject Two;
// Use this for initialization
void Start() {
NumberSelect = Random.Range(1, 3);
}
// Update is called once per frame
void Update() {
if (NumberSelect <= 1)
{
One.gameObject.SetActive(true);
}
else
{
Two.gameObject.SetActive(true);
}
}
}
This code is logically different from the original one (e.g. no gameobject is ever de-activated). And the original problem wasn't really solved, you just used a different method without understanding what was wrong in the old code.
But if you're happy with that, so be it.
Answer by doublemax · Oct 04, 2016 at 05:25 AM
Start() is only called once. Move the "Fun = Random.Range(1,3);" into the StartMusic() method.
the problem is something like a logic error and any number that is picked always causes it to pick the second gameobject and I don't why. Also I only need the number picked once right now maybe later when the song ends and I need to cycle through the different songs
Under the same conditions the random number generator will always produce the same sequence.
Try adding this line at the beginning of Start():
Random.InitState( Time.time );
Ok that is an int but Time.time is a float so it wont convert and anyway the thing is I got it to generate either one or two which is what I want, it is the if statements that dont seem to work right as in if its one it still uses the second gameobject. EDIT Also if I uncheck the objects in unity then neither object will become active