Not sure where to put my code

Hi, my script creates a cube and moves it from A to B.

Although because i’m creating it all in script, i’m not sure how to place it.
I know my movement line has to be in update, but then my create line can’t be as it’ll create hundreds of them.

If anyone could help that’d be great!

using UnityEngine;
using System.Collections;

public class myScript : MonoBehaviour {

	public Transform startTransform;
	public Transform endTransform;
	public float speed = 3;
	public static bool createCube = false;
	
	void OnGUI(){
			if (GUI.Button (new Rect (10, 10, 100, 30), "Create cube")) {

			createCube = !createCube;
			GameObject myCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
			myCube.transform.position = startTransform.position;
			myCube.transform.position = Vector3.MoveTowards(myCube.transform.position, endTransform.position, speed * Time.deltaTime);
		}
	}	

	void Update(){
	
	}		
}

So you want to create a cube at starttransform and want to move in the direction of endtransform?

OnGUI is for the UserInterface (“GUI” → “Graphical User Interface”). You can spawn your cube there, but you should move it in the Update void. (Update is called once every frame) Try the following:
`
using UnityEngine;
using System.Collections;

public class myScript : MonoBehaviour {
   public Transform startTransform;
   public Transform endTransform;
   public float speed = 3;
   public static bool createCube = false;
   GameObject myCube;
 
   void OnGUI(){
      if (GUI.Button (new Rect (10, 10, 100, 30), "Create cube")) {
         createCube = true;
         myCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
         myCube.transform.position = startTransform.position;
      }
   }
 
   void Update(){
      if(createCube){
         myCube.transform.position = Vector3.MoveTowards(myCube.transform.position, endTransform.position, speed * Time.deltaTime);
      }
   }
}`

You can also use createCube for disabling the Create-Cube button after pressing it by changing the line to

if (!createCube&&GUI.Button (new Rect (10, 10, 100, 30), "Create cube")) {