- Home /
Question by
Saucyminator · Oct 13, 2017 at 01:01 PM ·
skinnedmeshrendererskinned mesh renderer
Error when trying to change SkinnedMeshRenderer material colors on a character
I have an enemy that has two SkinnedMeshRenderer on it (one for head other for body). I'm trying to change the color of the materials when the enemy attack then reset it to the old (previous) color.
Using Unity 2017.2.0f3 Personal (64bit). Also made a GitLab snippet: https://gitlab.com/snippets/1679439
The error:
NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)
EnemyTest.SetupEnemy (Color skinColor) (at Assets/EnemyTest.cs:29)
EnemyTest.Awake () (at Assets/EnemyTest.cs:12)
EnemyTest.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTest : MonoBehaviour {
public Color attackColor = Color.green;
private Material[] skinMaterial;
private Color[] originalColor;
void Awake () {
SetupEnemy(attackColor);
}
void Update () {
if (Input.GetButtonDown("Jump")) {
StartCoroutine(Attack());
}
}
void SetupEnemy (Color skinColor) {
SkinnedMeshRenderer[] renderers = GetComponentsInChildren<SkinnedMeshRenderer>();
foreach (SkinnedMeshRenderer rend in renderers) {
Debug.Log("rend: " + rend.material);
}
for (int i = 0; i < renderers.Length; i++) {
skinMaterial[i] = renderers[i].material;
skinMaterial[i].color = skinColor;
originalColor[i] = skinMaterial[i].color;
}
}
IEnumerator Attack () {
for (int i = 0; i < skinMaterial.Length; i++) {
skinMaterial[i].color = Color.red;
}
// enemy does its attack
yield return null;
for (int i = 0; i < skinMaterial.Length; i++) {
skinMaterial[i].color = originalColor[i];
}
}
}
Comment
Best Answer
Answer by unit_nick · Oct 13, 2017 at 01:38 PM
add this at line 23
skinMaterial = new Material[renderers.Length];
That worked! I added originalColor = new Color[renderers.Length];
just below that as well, got another error otherwise. Thanks!