- Home /
How can I change the texture of a game object by clicking on another game object?
Hello,
I am trying to make a menu that is setup like a journal where you click on a cube and it changes the texture of a plane to the next page. The only problem is I have no clue how to do it.
I just started working with Unity so thanks for your help.
Answer by robertbu · Feb 11, 2014 at 10:51 PM
Here is a bit of code to get you started. You attach it to the cube, then in the inspector you need to drag and drop the game object that will be used to display the pages onto the 'pagesGameObject' variable. You will also have to set the size and drag the textures for each page onto the 'pages' variable.
Note if you are going to create more controls for your pages beyond just next page, you will need to split out the page handling script into its own script attached to the pages game object. Then you will need to learn how to communicate between game objects. One way is described here:
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
#pragma strict
var pagesGameObject : GameObject;
var pages : Texture[];
private var currPage = 0;
function Start() {
pagesGameObject.renderer.material.mainTexture = pages[currPage];
}
function OnMouseDown() {
currPage = (currPage + 1) % pages.Length;
pagesGameObject.renderer.material.mainTexture = pages[currPage];
}
Thank you, this will work for one of my menus but I have another one where I have a corresponding cube for each page. Such as cube1 takes you to the about page and cube2 takes my to the map page.
In order to allow multiple object to drive your pages, you are going to have to learn about inter-component communication as I've indicated at the link. Think about creating a script that has three public functions: NextPage(), PrevPage(), and GotoPage(pageNum : int). Each of the buttons would communicate to the page game object calling one of these three functions.
THAN$$anonymous$$ YOU SOOO $$anonymous$$UCH!!!!!!!! It all works!!