1

I am developing and android game where i fade in enemy when the spawn, the problem is that the enemy prefabs have 2 skinned mesh renderer material(ZombearMaterial, EyeMaterial). I use the down given code to fade in the enemy but the problem I face is that the script is only able to fade in the first element in the hierarchy. So how can I access and change all the skinned mesh renderer material in a Gameobject.

Fade In

public Material enemyAlpha;
public float fadetime;

// Use this for initialization
void Start () {

    enemyAlpha = GetComponent<SkinnedMeshRenderer> ().material;
}

// Update is called once per frame
void Update () {

    fadetime = (Time.time)/2;
    fadeIn (fadetime);
}

void fadeIn(float time)
{
    enemyAlpha.color = new Color (1, 1, 1, (time));
}

Gameobject inspector

enter image description here

Ved Sarkar
  • 347
  • 2
  • 8
  • 18

1 Answers1

1

Just create an array of materials:

public class EnemySetAlpha : MonoBehaviour {

    public float fadeSpeed = 0.1f;
    private Material[] enemyMaterials;
    // Value used to know when the enemy has been spawned
    private float spawnTime ;

    // Use this for initialization
    void Start () {
        // Retrieve all the materials attached to the renderer
        enemyMaterials = GetComponent<SkinnedMeshRenderer> ().materials;
        spawnTime = Time.time ;
    }

    // Update is called once per frame
    void Update () {
            // Set the alpha according to the current time and the time the object has spawned
            SetAlpha( (Time.time - spawnTime) * fadeSpeed );
    }

    void SetAlpha(float alpha)
    {
        // Change the alpha value of each materials' color
        for( int i = 0 ; i < enemyMaterials.Length ; ++i )
        {
            Color color = enemyMaterials[i].color;
            color.a = Mathf.Clamp( alpha, 0, 1 );
            enemyMaterials[i].color = color;
        }
    }
}
Hellium
  • 7,206
  • 2
  • 19
  • 49
  • this works perfectly, any idea how can i change the rendering from fade to opaque in this code when alpha becomes 1!!!!! – Ved Sarkar Jan 15 '18 at 10:07
  • I invite you to follow [this link](https://answers.unity.com/questions/1004666/change-material-rendering-mode-in-runtime.html) where someone had the same question. Create a new C# script, copy paste bellicapax's code and then, in the `SetAlpha` function: `if( alpha > 1 - Mathf.Epsilon ) { for( int i = 0 ; i < enemyMaterials.Length ; ++i ) ChangeRenderMode( enemyMaterials[i], BlendMode.Opaque ) ; return ; }` – Hellium Jan 15 '18 at 10:18
  • GetComponent*s*(typeof(SkinnedMeshRenderer)); //not GetComponent – David Jan 15 '18 at 10:36
  • Only one `SkinnedMeshRenderer` is attached to the gameobject. And this Renderer has multiple materials, so I think `GetComponent` is the function to call. – Hellium Jan 15 '18 at 10:38