Can I animate the enabled value on a renderer on and off?

I'm trying to make a gameObject blink on and off. I want this to be driven by an animation so that my artist can choose the speed of the blinking when the enemy gameObject is shot and killed.

Animating the renderer's enabled value to false works but the animation doesn't seem to be able to enable the renderer again.

I managed to make the object blink like this code sample in the script reference shows and it works fine... But this is not driven by animation like I'd prefer.

Why would animation not be able to do this? Is it a bug?

Hi,

I think it's simply because when disabled a component is not reachable again, so you can set it to false, but then you loose access to it.

Instead, you would likely need a script that would expose the speed variable that you can animate and then react within the script. Something like that:

using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Renderer))]
public class Blink : MonoBehaviour {

    public bool visible = true;
    private bool _visible;

    private Renderer _renderer;

    // Use this for initialization
    void Start () {
        _renderer = GetComponent<Renderer>();
    }

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

        if (_visible!=visible){
            _visible = visible;
            _renderer.enabled = _visible;
        }
    }

}

tested animating the visible value and it works,oddly enough, you can animate a boolean value like a float... so be careful when you animate, anything different than 0 is considered 1 ( from what I could figure out).

The script above could win optimization like maybe using getter and setter to avoid running code in the Update, not ideal....

Bye,

Jean

You should be able to animate any boolean value, including the enabled flag on a component.

To make this work …

  • set keyframe values to 0 (off/disabled) or 1 (on/enabled)
  • on each keyframe, set both tangents to constant – this will create a step function
  • for each keyframe that changes the state from 0 to 1 or 1 to 0, create another keyframe a little later (30 frames? 60? see what works) at the same value – without this, I found the animation playback was prone to skipping right over single keyframes and never setting the correct value

Note that this is based on an hour or so of messing around, not deep use of this functionality. Please add comments if you have more info.