x


[Closed] 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); 
}
more ▼

asked Jun 02 '12 at 01:32 AM

MinecraftUnity gravatar image

MinecraftUnity
0 4 4 4

(comments are locked)
10|3000 characters needed characters left

The question has been closed Jun 02 '12 at 01:49 AM by Eric5h5 for the following reason:

Duplicate Question


1 answer: sort voted first

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

more ▼

answered Jun 02 '12 at 01:44 AM

Berenger gravatar image

Berenger
11k 12 19 53

(comments are locked)
10|3000 characters needed characters left

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3445
x2191
x288
x95

asked: Jun 02 '12 at 01:32 AM

Seen: 732 times

Last Updated: Jun 02 '12 at 01:44 AM