我有一个沙发的3D模型,我希望通过屏幕上显示的纹理更改按钮更改其纹理。
例如。如果我触摸红色按钮,沙发颜色将为红色;如果我触摸黑色按钮,沙发颜色将为黑色。
目前,我可以通过触摸屏幕上的任何位置来更改沙发纹理,但现在我想触摸特定按钮,并根据按钮更改沙发纹理。
这是我到目前为止的所作内容:
public class change_texture : MonoBehaviour {
public Texture[] texture;
public int currentTexture;
// Use this for initialization
void Start () {
Screen.orientation = ScreenOrientation.Landscape;
}
// Update is called once per frame
void Update () {
if (Input.touches[0].phase == TouchPhase.Began) {
currentTexture++;
currentTexture %= texture.Length;
GetComponent<Renderer> ().material.mainTexture = texture [currentTexture];
}
}
}
答案 0 :(得分:1)
您应该使用GUI按钮OnClick事件。首先将您的脚本(连接到沙发)更改为此脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class textureChange : MonoBehaviour {
public Texture[] texture; //set in inspector
public int[] price; // price for every texture (in parallel to the textures array)
public int currentTexture; //set default/starting index in inspector
bool shouldChange = false; //this bool is set to prevent unwanted texture changes to the same texture every frame
public Text priceObject; // the Price text object
// Use this for initialization
void Start()
{
Screen.orientation = ScreenOrientation.Landscape; //your code
priceObject.text = "Price: " + price[currentTexture] + "$"; //show default price
}
public void changetexture(int textureToSet)
{
currentTexture = textureToSet;
shouldChange = true;
}
public void incrementtexture()
{
currentTexture++;
shouldChange = true;
}
// Update is called once per frame
void Update()
{
if (shouldChange)
{
shouldChange = false;
GetComponent<Renderer>().material.mainTexture = texture[currentTexture]; //set new texture
priceObject.text = "Price: " + price[currentTexture] + "$";
}
}
}
然后使用画布作为父级向场景添加按钮。 在按钮检查器中,通过以下方法将功能添加到OnClick列表:
答案 1 :(得分:0)
答案 2 :(得分:0)
这将只使用一个按钮。
public class textureChange : MonoBehaviour {
public Texture[] textures;
public int index;
public void Changetexture()
{
// Will loop through array and restart from 0
int index = (++index == this.textures.Length) ? 0 : index;
GetComponent<Renderer>().material.mainTexture = this.textures[index];
}
}
如果您有增加/减少按钮,请为每个按钮指定以下内容。到达阵列的结束/开始时它将停止变化。
public class TextureChange : MonoBehaviour {
public Texture[] textures;
private int index;
public void IncreaseIndex()
{
// Will loop through array and restart from 0
if(++index == this.textures.Length){index = this.textures.Length - 1;}
GetComponent<Renderer>().material.mainTexture = this.textures[index];
}
public void DecreaseIndex()
{
// Will loop through array and restart from 0
if(--index < 0){ index = 0}
GetComponent<Renderer>().material.mainTexture = this.textures[index];
}
}
您也可以使用一种方法:
public void SetIndex(int polarity)
{
// Will loop through array and restart from 0
index += polarity;
if(index < 0){ index = 0 }
else if(index >= this.textures.Length){ index = this.textures.Length -1; }
GetComponent<Renderer>().material.mainTexture = this.textures[index];
}