第一次写博客,必须来点干货。
今天遇到的问题是如何在unity中添加背景图片。其中主要是结合网上博客大牛的案例,总结一下,希望大家少走弯路。
具体方法:
1.添加一个摄像机,命名为background Camera,然后在Layer添加一个background层。并且将Plane拖放到该相机节点下。然后将backgroundCamera和Plane都置于Background层,修改ClearFlags未Depth only深度渲染,并且设置Culling Mask为只看到Background层,还有设置Depth为-1,说明背景层是最深,其他model所在的相机的Depth是0,UI的是1,这里层次关系就是UI在最前面,model层其次,然后是背景层,这样确保3D模型在背景的前面!
注意:ClearFlags 选择Depthonly是指渲染方式,这里选择深度渲染,下面的Depth设置越小,层次越深,所看到的物体在屏幕中越靠后。CullingMask是摄影机能看的层,这里就只选择背景层,说明这个相机只看到背景层看不到其他层。
2.同样的操作,将MainCamera设置一下,注意的就是,将MainCamera的CullingMask不能包含background层,也就是让它看不到背景层,不然还是会出现背景遮挡住模型的情况。
注意:其中的Depth为0;background Camera属于background层,而Main Camera属于Default层
3.最后一步就是要在backGround Camera中添加GUI Texture,backGround Camera->Add Component->Rendering->GUI Texture;加载图片,把Transform–>Position中的x和y都调节成0.5。
4.最后在plane上添加一个脚本,用于动态在plane上加载贴图。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AddBackground : MonoBehaviour
{
public Texture2D mtexture;
void Awake()
{
// Texture2D mtxture = new Texture2D(Screen.width, Screen.height);
// renderer.material.mainTexture = mtxture;
// mtxture.Apply();
gameObject.AddComponent<GUITexture>();
}
// Use this for initialization
void Start()
{
guiTexture.texture = mtexture;
transform.localScale = new Vector3(0, 0, 0);
transform.localPosition = new Vector3(0, 0, 25);
guiTexture.pixelInset = new Rect(65, 0, Screen.width, Screen.height);
}
}
最后,衷心感谢因特网。