Hello Guest

Author Topic: Dynamic opacity of animatedSprite  (Read 5490 times)

ItsMeAlan

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 22
    • View Profile
Dynamic opacity of animatedSprite
« on: March 09, 2013, 12:27:42 am »
Is there a way to change how transparent a sprite is with code?

Thanks!

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Dynamic opacity of animatedSprite
« Reply #1 on: March 09, 2013, 10:37:21 am »
Yup, change the alpha channel of the color property.

sprite.color = new Color (1, 1, 1, 0.5f ); // makes it 50% transparent

ItsMeAlan

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 22
    • View Profile
Re: Dynamic opacity of animatedSprite
« Reply #2 on: March 14, 2013, 06:45:22 am »
I'm using this:

Code: [Select]
GetComponent(tk2dSprite).color = new Color(1,1,1,myAlpha);
where myAlpha is a float that I add to or decrease from. Interestingly, this code works exactly as I want it to, but it causes a ton of errors. Specifically, this error:

Code: [Select]
NullReferenceException: Object reference not set to an instance of an object
HelpArrowScript.Update () (at Assets/Scripts/HelpArrowScript.js:23)

The line causing the error is the line I posted above. My game is having major framerate issues, so I figure this might be the culprit? Am I doing something wrong?

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Dynamic opacity of animatedSprite
« Reply #3 on: March 14, 2013, 08:14:14 am »
In JS, the syntax is
GetComponent(tk2dSprite).color = Color(1,  1, 1, myAlpha);


ItsMeAlan

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 22
    • View Profile
Re: Dynamic opacity of animatedSprite
« Reply #4 on: March 14, 2013, 03:15:34 pm »
I took out the New but this line is still causing the same error once per frame.

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Dynamic opacity of animatedSprite
« Reply #5 on: March 14, 2013, 09:04:49 pm »
What is GetComponent(tk2dSprite) returning? Do you have a sprite attached to the same gameobject the script is on?

ItsMeAlan

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 22
    • View Profile
Re: Dynamic opacity of animatedSprite
« Reply #6 on: March 17, 2013, 06:30:48 am »
Ah, that was it. I'd accidentally applied my script to an empty gameObject without realizing it. Thanks!