Selectiongrid too many action calls...

Hey there,

I have a number of buttons built from a selection grid. What I want to do is when you click a button, it makes just one call/action. At present, it keeps calling and generating multiple instantiations of the object as the button is active I think. Is there a way so it just calls once? Here’s my code so far…

using UnityEngine;
using System.Collections;

public class SelectionGridTest : MonoBehaviour
	
	
	

{
	
	public GUISkin leftnav;
	public int selGridInt = 0;
    public string[] selStrings = new string[] {"Grid 1", "Grid 2", "Grid 3", "Grid 4", "Grid 5", "Grid 6", "Grid 7", "Grid 8"};
   
 //Instansiate object references

	public GameObject TheObject;
	
	
	void OnGUI()
	
	{
		GUI.skin = leftnav;
		
		GUI.Box(new Rect(-90,14,100,320),"");
		
        selGridInt = GUI.SelectionGrid(new Rect(40, 40, 70, 800), selGridInt, selStrings, 1);
		
		
		
		 if (selGridInt == 0) 
			{
			// execute code for loading Object1
			GameObject objTheObject = (GameObject)Instantiate(TheObject, new Vector3(0,0,0), transform.rotation);
            }

            
			else if (selGridInt == 1)
			{
            // execute code for loading level //////Application.LoadLevel(1);
			
            }
		
		
			else if (selGridInt == 2)
			{
			// execute code for destroying tag
			Destroy (GameObject.FindWithTag("TheObject"));	
            }
		
		
    }
	
	
}

The variable selGridInt holds the last value selected - that’s why the actions repeat continuously. A simple solution is to detect changes with an auxiliary variable - like this:

...
public GameObject TheObject;
private int lastSel = -1; // declare this variable outside any function!

void OnGUI(){
    GUI.skin = leftnav;
    GUI.Box(new Rect(-90,14,100,320),"");
    selGridInt = GUI.SelectionGrid(new Rect(40, 40, 70, 800), selGridInt, selStrings, 1);
    if (selGridInt != lastSel){ // selGridInt changed?
        lastSel = selGridInt; // yes: update lastSel and take appropriate action
        if (selGridInt == 0) 
        {
            // option 0 code
        } else 
        if (selGridInt == 1)
        {
            // option 1 code
        } else 
        if (selGridInt == 2)
        {
            // option 2 code
        }
    }
}