- Home /
Duplicate Question
How do I put a texture on my Cube using code (JavaScript)
I am completely new to Unity 3D. I own the free version. For my first project, I am trying to make a MineCraft like clone. I followed tutorials, but now i'm trying to change something so it works how I want it. First off, how can I place a cube with a texture on it? Here's a chunk of code where I need to be able to do this:
function Build() {
if (HitBlock()) {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hit.transform.position + hit.normal;
}
}
This spawns a default cube with no texture whatsoever. How do I get a texture?
Here is my entire code ( I followed tutorials, so I shouldn't be saying mine):
var blockLayer : LayerMask = 1;
var range : float = Mathf.Infinity;
var hit : RaycastHit;
function Update () {
if (Input.GetMouseButtonDown(1)) Build();
if (Input.GetMouseButtonDown(0)) Erase();
}
function Build() {
if (HitBlock()) {
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
renderer.material.mainTexture = Resources.Load("Dirt.png");
cube.transform.position = hit.transform.position + hit.normal;
}
}
function Erase() {
if (HitBlock())
Destroy(hit.transform.gameObject);
}
function HitBlock() : boolean {
return Physics.Raycast(transform.position, transform.forward, hit, range, blockLayer);
}
Answer by Berenger · Jun 02, 2012 at 01:44 AM
This should already work if Dirt.png can be found. However, note that Resources.Load is an expensive function. You must call only when you really have to and certainly not several times for the same resource. declare a Texture2D in your script and set it up in the inspector or, if you really can't do otherwise, call Load at Start and store the value.
Now that we worked that out, it appears that minecraft worlds are not thousands of cube, 24 vertices and all that stuff. I've never looked into it, but it seems more complicated than that. Usefull documentation :
http://forum.unity3d.com/threads/63149-After-playing-minecraft...
http://forum.unity3d.com/threads/69573-MinePackage-Minecraft-starter-package?highlight=Procedural
Follow this Question
Related Questions
How to make a Cube with a texture in a JavaScript? 0 Answers
Primitive Cube Texturing Help 3 Answers
Apply texture to a bar (cube) 2 Answers
How to add my texture to a cube? 2 Answers
background picture in my game 1 Answer