I want to click random position object
I made key move randomly and when I click key, I want to go to another scene. Key is a button, so I use OnClick(), but it doesn't work...
public void onClick()
{
SceneManager.LoadScene("14.PlayGround");
}
// Use this for initialization
void Start()
{
a = 0;
b = 0;
timer = 0.0f;
waitingTime = 1;
}
// Update is called once per frame
void Update()
{
if (key.activeSelf == true)
{
timer += Time.deltaTime;
if (timer > waitingTime)
{
a = Random.Range(0.0f, 605.0f);
b = Random.Range(0.0f, 294f);
key.transform.position = new Vector2(a, b);
timer = 0;
}
}
}
Answer by Cains · Nov 02, 2016 at 10:21 PM
As a note, it would be more helpful if you could include the entire script, or at least the declarations for the variables you're using such as key. It also helps if you include the GameObjects that you're working with in the editor and what components are on them.
If I understand correctly then the key variable is a GameObject and you're putting a UI button into that variable in the editor. If so, then that GameObject should have a Button component attached to it, and what you're probably trying to use is the onClick variable within the Button class.
onClick isn't a method/function like you're trying to create, but rather it is an event variable -- a variable that stores multiple methods/functions. The onClick variable is meant to store all the methods that you want executed when the button is clicked, so you want to make a method like you've done and then add it to onClick.
You should be able to modify your code to the below to get it to work as expected.
public void Clicked()
{
SceneManager.LoadScene("14.PlayGround");
}
// Use this for initialization
void Start()
{
a = 0;
b = 0;
timer = 0.0f;
waitingTime = 1;
key.GetComponent<Button>().onClick.AddListener(Clicked);
}