需求
??一个曲面模型,它显示的图案是模型上材质球的主贴图,我们要给它换成需要的图。
原理
??改变模型上材质球的主贴图
一、手动换
??找到目标材质球(图一),对材质球的主贴图做修改(图二,给红框处拖入一张新的图片)
二、用代码换
??ChangeMainTextureOfMaterial.cs脚本放在模型“123”上,如红箭头指示,把模型和目标图片拖给脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeMainTextureOfMaterial : MonoBehaviour
{
public GameObject model_123;
public Texture targetTexture;
void Start()
{
ChangeMaterial_MainTexture();
}
public void ChangeMaterial_MainTexture()
{
Material[] mats = model_123.GetComponent<MeshRenderer>().materials;
for(int i=0;i<mats.Length;i++)
{
mats[i].mainTexture = targetTexture;
}
}
}
三、用代码换 存在于服务器上的图
第一步,下载图片
(如上图)下载图片脚本,放在了游戏物体“123”上 注意此时下载的是Texture2D格式,需强转成Texture格式——把它赋值给我们定义的Texture类型变量“targetTexture”(代码贴在了文章下方处)
第二步,给材质球换主贴图
(如上图)给材质球换图片的脚本,放在了游戏物体“Script_SetTexture”上(此游戏物体事先是隐藏的,它作为变量出现在“123”的脚本里,目的是让图片从服务器下载完后,再执行给材质球换图片的操作,且此脚本做了略微改动) 两个脚本如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class DownloadTextureFromServer_quMian : MonoBehaviour
{
public static DownloadTextureFromServer_quMian instance;
public Texture targetTexture;
public GameObject setTexture;
void Start()
{
instance = this;
StartCoroutine(DownloadImage());
}
void Update()
{
}
IEnumerator DownloadImage()
{
UnityEngine.Networking.UnityWebRequest www = UnityWebRequestTexture.GetTexture("http://47.96.106.49/filetest/test1.jpg");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
targetTexture = (Texture)(((DownloadHandlerTexture)www.downloadHandler).texture);
setTexture.SetActive(true);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeMainTextureOfMaterial : MonoBehaviour
{
public GameObject model_123;
private Texture targetTexture;
void Start()
{
targetTexture = DownloadTextureFromServer_quMian.instance.targetTexture;
ChangeMaterial_MainTexture();
}
public void ChangeMaterial_MainTexture()
{
Material[] mats = model_123.GetComponent<MeshRenderer>().materials;
for(int i=0;i<mats.Length;i++)
{
mats[i].mainTexture = targetTexture;
}
}
}
|