Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Send & Receive integer via button?

Discussion in 'Scripting' started by sebastiantho, Jan 14, 2016.

  1. sebastiantho

    sebastiantho

    Joined:
    Feb 3, 2015
    Posts:
    3
    Hi. I'm creating a quiz in Unity, and I need to send an integer value from my button to match the correct answer, to determine a right or wrong answer.

    The button is spawned in, so it doesn't have an interface.

    I need the button to send an int value to my script, and my script needs to recieve it and store it in another variable.
    Anyone know how to do this?
     
  2. Strategos

    Strategos

    Joined:
    Aug 24, 2012
    Posts:
    255
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    when you "spawn in" the button, you can set the variables on the attached scripts... just do that.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ButtonSpawner : MonoBehaviour
    6. {
    7.     public int numberOfButtons = 4;
    8.     public Transform buttonPanel;
    9.     public Transform buttonPrefab;
    10.  
    11.     void Start()
    12.     {
    13.         for(int i = 0; i<numberOfButtons; i++)
    14.         {
    15.             Transform buttonInstance = Instantiate(buttonPrefab, Vector3.zero, Quaternion.identity) as Transform;
    16.             buttonInstance.SetParent(buttonPanel);
    17.             buttonInstance.GetComponent<ButtonScript>().returnValue = i;
    18.         }
    19.     }
    20. }
    21.  
    22.  
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ButtonScript : MonoBehaviour
    6. {
    7.     public int returnValue;
    8.  
    9.     public void ClickMe()
    10.     {
    11.         Debug.Log(returnValue);
    12.     }
    13. }
    14.  
    set clickme as the onClick event function before creating the buttonPrefab, it'll keep the reference.
     
    Nigey likes this.