- Home /
How to dynamically create a cube and color it?
I am a week into Unity and am confused about coloring a dynamic cube in javascript. I've been searching for over 2 hours and can't grasp the right way to do so. I know in logic I have to create the material and give it a color but, I don't know how to assign it to a dynamic cube. I was only able to create a cube for now:
function Start () {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = 'brown_cube';
}
When you create your cube, give it a material then color it. AddComponent($$anonymous$$aterial) https://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$aterial.html
Answer by SubatomicHero · Jul 02, 2013 at 06:56 AM
It's quite simple:
function Start() {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = 'brown_cube';
// color is controlled like this
cube.renderer.material.color = Color.brown; // for example
// There are lots more colours to choose
}
Hope this helps!
@SubatomicHero It gave me an error: ...'brown' is not a member of 'UnityEngine.Color'. Do you $$anonymous$$d showing me a quick syntax using RGB I guess?
Yes, I $$anonymous$$now brown isn't a color in that class it was just an example.
Read THIS link to see what you can use :D
If you are new at using Unity, I seriously suggest reading the documents online to answer any questions. It's a great place to start.
If you need brown you can find the RGB of any color you like online. Then you can "create" your own:
Color brown = new Color(139f/255f, 69f/255f, 19f/255f, 1f);
cube.renderer.material.color = brown;
The last parameter of the constructor is the alpha channel, 0 -> transparent, 1 visible and then 0.5f see through. Since your new color is not static, do not use Color.brown but just brown.
See there http://www.tayloredmktg.com/rgb/
hi, I found this page because I was trying to find out how to change the colour of an object using its RGBA value rather than the dam shortcut things that come up on all the documentations. When I tried to replace them with straight RGBA values I got error saying that they couldn't be used in that context so I was glad to finally find your comment but I replaced cube with my variable name and i got the same "does not exist in current context" error. I was wondering if you could help me out.
You'd have to show your code. I recommend to start a new question as this is not relevant to this one.
Answer by OlivierPons · May 07, 2021 at 05:12 PM
Answers (like almost all answers) are out of date and not working in recent versions of Unity. Here's a working version:
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = "brown_cube";
Color brown = new Color(139f/255f, 69f/255f, 19f/255f, 1f);
// color is controlled like this
cube.GetComponent<Renderer>().material.color = brown;
Your answer
![](https://koobas.hobune.stream/wayback/20220613105322im_/https://answers.unity.com/themes/thub/images/avi.jpg)