1
\$\begingroup\$

I'm working on a little game (which is also my first one) and I want to insert a splash screen at the beginning (after the Unity one). I've finally achieved to add a fade-in and a fade-out transistion when the splash screen starts and ends, but the fade out is activated by a button and I wont to play it simply after a certain time. I've made a script for that:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class FadeInOut_2 : MonoBehaviour
{
    public Animation anim;

    IEnumerator Start()
    {
        yield return new WaitForSeconds(2f);

        anim.GetComponent<Animation>().Play();

        Application.LoadLevel(Application.loadedLevel + 1);
    }

}

The problem is: when I try to attach the animation the Inspector refuses to do it.

Any ideas? Thanks

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Why are you calling GetComponent on anim, when anim is an Animation component? \$\endgroup\$
    – jhocking
    Commented Sep 10, 2015 at 1:31
  • \$\begingroup\$ @jhocking is right. You have already assigned a clip to anim, so there is no need to call GetComponent. Just say anim.Play(); \$\endgroup\$
    – SanSolo
    Commented Dec 9, 2015 at 5:43
  • \$\begingroup\$ just another bit of info: you can use transform.GetComponent<COMPONENT>() to access another component on the same object. \$\endgroup\$ Commented Dec 9, 2015 at 11:49

2 Answers 2

2
\$\begingroup\$

You aren't waiting on the animation so once you play it Application.LoadLevel just does its thing and you wont notice the animation.

First, you'll need a way to wait on the animation which could be a simple coroutine:

private IEnumerator WaitForAnimation ( Animation animation )
{
do
    {
        yield return null;
    } while ( animation.isPlaying );
}

And then use it to yield before calling Application.LoadLevel:

    ...
    anim.Play();
    yield WaitForAnimation(anim);

    Application.LoadLevel(Application.loadedLevel + 1);
}

Also, you don't need to call GetComponent<Animation> on an Animation.

\$\endgroup\$
0
\$\begingroup\$

I noticed that you created a coroutine but never called it, by using StartCoroutine().

\$\endgroup\$
3
  • 2
    \$\begingroup\$ The Start() function of a monobehaviour can be used as a coroutine without calling the StartCoroutine(). \$\endgroup\$
    – Lasse
    Commented Oct 10, 2015 at 7:01
  • \$\begingroup\$ @Lasse interesting, googled up and everybody seems to confirm this but could not find any documentation about it, could you provide one? \$\endgroup\$ Commented Dec 9, 2015 at 12:03
  • \$\begingroup\$ @NikaKasradze I'm afraid right now there isn't much more than what is on this documentation page: docs.unity3d.com/ScriptReference/… It seems to be one of the many badly documented features of Unity. \$\endgroup\$
    – Lasse
    Commented Dec 9, 2015 at 12:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .