Search Unity

Visibility Switch for objects

Discussion in 'Scripting' started by Apprenticeneauxs, Jan 22, 2010.

  1. Apprenticeneauxs

    Apprenticeneauxs

    Joined:
    Mar 21, 2009
    Posts:
    256
    I have a character thats animated to pull a sword out of a sheath and then put it back again. I am using two swords and just switching the visibility in Maya. Since Unity doesnt support this part of the animation I need to come up with a script. Any examples of how this can be done? I need to set the visibility for a certain frame range and then turn off for a certain range. Please help! DL out!
     
  2. damien_oconnell

    damien_oconnell

    Joined:
    Dec 24, 2009
    Posts:
    58
    Code (csharp):
    1. //Attach to the game object playing the animation and assign the sword to swordGameObject.
    2. var swordGameObject : GameObject;
    3.  
    4. function switchSwordVisibility (showSword : float) {
    5.     swordGameObject.renderer.enabled = showSword ? true : false;
    6.  
    7. }

    Add animation events that call the above function:
    http://unity3d.com/support/documentation/Components/animeditor-AnimationEvents.html

    Note! You must duplicate the imported animation before you can add event markers to it.
     
  3. tmanallen

    tmanallen

    Joined:
    Nov 8, 2009
    Posts:
    395
    Here is a portion of code to display the objects visibility when the correct animation is called

    Code (csharp):
    1.  
    2. void Update () {
    3.         if(Mathf.Abs(Input.GetAxis("Vertical")) > 0.1f)
    4.         {
    5.             animation.CrossFade("run");
    6.         swordObject1.renderer.enabled = false;
    7.         swordObject2.renderer.enabled = true;
    8.         }
    9.         else
    10.         {
    11.         animation.CrossFade("idleSWI");
    12.         swordObject1.renderer.enabled = true;
    13.         swordObject2.renderer.enabled = false;
    14.         }
    15.        
    It may seem bulky but it works. This is done in C# also.