Create GUI button in update function?

Hello, I am quite new to Unity and need help with a simple task. I want a button to appear on an object, when I touch this object with the cursor. Depending on which object was touched, the button should get a diffrent texture. This is my script so far:

var IconCache : Texture2D;
var Icon1 : Texture2D;
var Icon2 : Texture2D;
var target : Transform;

function update(){

var hit:RaycastHit;
var ray = camera.main.ScreenPointToRay(Input.mousePosition);

if(Physics.Raycast (ray, hit))
{
   if(hit.transform.name=="Object1") 
   {
	IconCache=Icon1;
   }
   if(hit.transform.name=="Object2")
    IconCache=Icon2;
   //...etc

   target=hit.transform;
   var screenPos : Vector3 = camera.WorldToScreenPoint (target.position);
   if(GUI.Button(Rect(screenPos.x,screenPos.y,128,128),IconCache))
   {
	DoAction1();
   }

   }
}

But no button appears. I recognized that I am not able to create buttons outside an OnGUI-Function at all. Any suggestions? And is there an easy way to remove the button from another script, too? Thanks for all help.

GUI.Button derives from OnGUI, so it can only be called from the OnGUI() function. Also, rename update to Update (capital U).

function OnGUI () {
     if(GUI.Button(Rect(screenPos.x,screenPos.y,128,128),IconCache))
          DoAction1();
}

–David–

You can only call the GUI functions from within OnGUI(). So you’ll need two functions. For example:

var showButton = false;
var screenPos : Vector3;

function Update() {
    ...
    screenPos = camera.WorldToScreenPoint (target.position);
    showButton = true;
}

function OnGUI() {
    if (showButton) {
        if(GUI.Button(Rect(screenPos.x,screenPos.y,128,128),IconCache)) {
            DoAction1();
        }
    }

}

Use a bool and show/create the button if true in the OnGUI function. Use the Update loop to update the bool. This allows for control over that button from any function.
Here’s what I usually do:

public class ingamegui : MonoBehaviour {
public bool showBottomToolBar = true;
public bool showBackpack = false;
public Texture optionsButtonTexture;
public Texture attackButtonTexture;
public Texture backpackButtonTexture;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
	
}

void OnGUI() {
	if(showBottomToolBar) {
		if(GUI.Button(new Rect(0,Screen.height-64,64,64),optionsButtonTexture)) {
			
		}
		if(GUI.Button(new Rect(65,Screen.height-64,64,64),attackButtonTexture)) {
			
		}
		if(GUI.Button(new Rect(130,Screen.height-64,64,64),backpackButtonTexture)) {
			if(showBackpack)
				showBackpack = false;
			else
				showBackpack = true;
		}
	}
	if(showBackpack) {
		GUI.Box(new Rect(0,0,400,200),"Backpack");
	}
}

}