- Home /
Editing Offset of Texture of Multi-Material Object
I need to change the offset of the Bumpmap every Frame. The object has 6 materials with assigned normalmaps.
I always get this message: "NullReferenceException: Object reference not set to an instance of an object".
I do not know how to access the instance of the material.
using UnityEngine;
using System.Collections;
public class offset : MonoBehaviour
{
public float scrollSpeed = 0.01f;
private Material[] mat = new Material[5];
void Update ()
{
float offset = Time.time * scrollSpeed;
mat[0].SetTextureOffset("_BumpMap", new Vector2(0f, offset));
mat[1].SetTextureOffset("_BumpMap", new Vector2(0f, offset));
mat[2].SetTextureOffset("_BumpMap", new Vector2(0f, offset));
mat[3].SetTextureOffset("_BumpMap", new Vector2(0f, offset));
mat[4].SetTextureOffset("_BumpMap", new Vector2(0f, offset));
mat[5].SetTextureOffset("_BumpMap", new Vector2(0f, offset));
}
}
Comment
Answer by rutter · Jan 23, 2014 at 12:00 AM
Materials are usually owned by Renderer components. You're getting a null reference because you've declared an array of materials, but didn't actually populate it with references to materials. Until you tell Unity otherwise, the array will be a bunch of null
s.
Assuming that Offset
will be attached to a GameObject with exactly one renderer, you could access its materials like so:
public class Offset : MonoBehaviour
{
public float scroolSpeed = 0.01f;
private Material[] mat;
void Start() {
mat = renderer.materials;
}
void Update() {
float offset = Time.time * scrollSpeed;
for (int i=0; i<mat.Length; i++) {
mat[i].SetTextureOffset("_BumpMap", Vector2.up * offset);
}
}
}
Related reading:
Your answer
![](https://koobas.hobune.stream/wayback/20220613131157im_/https://answers.unity.com/themes/thub/images/avi.jpg)