Create colored rectangle at runtime

(Code is in C#)

edit: SOLVED.

will post solution later

My code

I’m trying to make a game in which the player has to move some colored rectangles around. What I’d like to do is have a controller create the rectangles when he starts up, and then keep those rectangles around. The player needs to be able to move the rectangles around.

For the rectangles I inherited from Monobehaviour, but that seems to be the wrong direction.

Basically all I need to do is create a sprite and give it a script and collider so it can be moved around and alter it’s color later on. (edit: I think if I make a prefab I can get around this and don’t have to add the components at runtime).

My guess it’s going to go over instantiate and addcomponent, i.e. something like

ColorSquare myColorSquare;
Instantiate(myColorSquare, new Vector3(x, y, 0), Quaternion.identity);
//somehow add script and box collider components using "addcomponent"
//set size of square

Also, do I need to initialize “myColorSquare” somehow before using instantiate?

From “Unity - Scripting API: GameObject.AddComponent
it seems all I have to do is declare the component in class somewhere.

edit: from the 2d platformer tutorial I found

Rigidbody2D bulletInstance = Instantiate(rocket,...

but i need mine to be along the line of

Colorsquare squre = Instantiate(colorsquareprefab,…
so I can put it in a list and access/alter it later with the script I attach as a component (there are parts of the script I need to call explicitly from the controller), such as “mysquare.changecolor()”


squaresgameobjects _= (GameObject) Instantiate (testy, new Vector3 (1.5f * ((float)i), 0, 0), Quaternion.identity);_

setting color