- Home /
Question by
thunderwiring · 2 days ago ·
c#cubemap
How to create and apply cubemap to material in C#?
In my scene there is a gameobject (with Sphere mesh) and i want to apply a cubemap texture to its material. Create a 'New Material' with Cubemap/Skybox shader, and applied it to the game object. i referenced both the sphere object and the material in my C# script.
How can i create and apply a Cubemap to the sphere in code? because texture will be changing in runtime.
This is the exception i get (code runs on Android device):
E/Unity: Material 'New Material (Instance)' with Shader 'Skybox/Cubemap' doesn't have a texture property '_MainTex'
E/Unity: NullReferenceException: Object reference not set to an instance of an object
at VrSphere.Start () [0x0006d] in <5baa6178d1f44f4fa9fe0697321ddb21>:0
(VrSphere is the name of the C# script file)
Code:
// referenced from Unity
[SerializeField] private GameObject sphere;
[SerializeField] private Material material;
void Start()
{
if (sphere == null)
{
Debug.Log("sphere is null");
}
sphereRenderer = sphere.GetComponent<Renderer>();
if (sphereRenderer == null)
{
Debug.Log("Sphere has no renderer");
return;
}
testCubemapShader();
sphereRenderer.material = material; // <-- throws exception here
}
private void testCubemapShader() {
if (material == null) {
Debug.Log("material is null, cannot set cube texture...");
return;
}
material.mainTexture = getTestCubemap();
}
private Cubemap getTestCubemap() {
int width = 500;
int cubeFaceLength = width * width;
Debug.Log(string.Format("FrameConfig.PanoramaWidth = {0}", FrameConfig.PanoramaWidth));
Color[] negativeX = new Color[cubeFaceLength];
Color[] negativeY = new Color[cubeFaceLength];
Color[] negativeZ = new Color[cubeFaceLength];
Color[] positiveX = new Color[cubeFaceLength];
Color[] positiveY = new Color[cubeFaceLength];
Color[] positiveZ = new Color[cubeFaceLength];
for (int i = 0; i < cubeFaceLength; i++)
{
negativeX[i] = new Color(0, 0, 255);
negativeY[i] = new Color(0, 255, 0);
negativeZ[i] = new Color(255, 0, 0);
positiveX[i] = new Color(100, 0, 55);
positiveY[i] = new Color(0, 100, 55);
positiveZ[i] = new Color(200, 0, 55);
}
Cubemap cube = new Cubemap(FrameConfig.PanoramaWidth, TextureFormat.ARGB32, false);
cube.filterMode = FilterMode.Point;
cube.Apply();
cube.SetPixels(negativeX, CubemapFace.NegativeX);
cube.SetPixels(negativeY, CubemapFace.NegativeY);
cube.SetPixels(negativeZ, CubemapFace.NegativeZ);
cube.SetPixels(positiveX, CubemapFace.PositiveX);
cube.SetPixels(positiveY, CubemapFace.PositiveY);
cube.SetPixels(positiveZ, CubemapFace.PositiveZ);
Debug.Log(string.Format("cube name: {0}", cube.name));
return cube;
}
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer