destroying objects when answering a question correctly

Hi guys, Is there any way that you can allow users to answer a question correctly before they can collect a coin?

I’m not good at coding but i tried this

var x =2;
var y =3;
var z= 4;
var HOB =25;
var Sum = x+y;

function OnTriggerEnter(info: Collider){

GUI.Label(Rect((Screen.width)/2-230, 130,200,50),"what is the sum of x+y?");



if(Sum !=(x+y)){

 Debug.Log("wrong answer, please try again");
}else{ Destroy(gameObject);
 CoinSystem.coinscollect +=1;


Hi. @Rissa_Ja There are a couple things wrong with the code but overall you’re pretty much there. Below is a working example of the code with revision and some quick comments detailing them.

#pragma strict

var x : int = 2;

var y : int = 3;

//The total sum of x+y which will be compared against the answer.
var answer : int = x+y;

var z : int = 4;

var HOB : int = 25;

//The string which the player will type and will be compared.
var sum : String = null;

//Boolean to chech whether or not the question should be displayed.
var shouldDisplayQuestion : boolean = false;

function OnTriggerEnter (other : Collider)
	//Player has entered collider and we want to display 
	//the question so we turn our boolean to true.
	shouldDisplayQuestion = true;

//Function which handles GUI output.
function OnGUI ()
	//An if statement to check for whether or not we should display the question.
		//If true we then run the display question method.

//Function which handles the question.
function DisplayQuestion ()
	GUI.Label(Rect((Screen.width)/2-230, 130, 200, 50), "What is the sum of x+y?");
	//The string we wish to input with our text field.
	sum = GUI.TextField(Rect((Screen.width)/2-20,130,200,HOB), sum, 45);
	//Check for whether the button was pressed.
 		//If statement which compares the players string answer 
 		//with that of x+y's answer parsed into a string.
		 if(sum != answer.ToString())
		 	Debug.Log("wrong answer, please try again");
		 	CoinSystem.coinscollect +=1;
		 	//We turn our boolean to false as the question as has been answered 
		 	//and we no longer want to show the menu.
		 	shouldDisplayQuestion = false;

Now for a bit more information on the code the main issues with your code are:

  1. Your GUI statements must be declared within or from the OnGUI function otherwise they will not be drawn and the console will throw an error.
  2. The text field takes a string value and as such can only compare the x+y question as a string value so you have to parse your int’s to a string to compare them.
  3. To deal with the OnGUI function i’ve used a boolean to decide whether or not the OnGUI function should display the question based on whether the player has entered the trigger.
  4. The text field requires a string value to change in this case i have used the sum variable.

That’s pretty much it, if you need any more help or this code is causing problems don’t hesitate to ask. I hope this helps! :slight_smile: