Search Unity

default values for gradients on adding component

Discussion in 'Scripting' started by fleity, Aug 11, 2016.

  1. fleity

    fleity

    Joined:
    Oct 13, 2015
    Posts:
    345
    Hey

    I have a c# script component which uses a few gradients for the user to tweak etc. which is turned into a 2d texture for a shader to work with. When I first drag the script onto a gameobject the gradients start off as entirely white, is there a way to supply some default gradients to give a better starting point for the user?
    I was hoping for something like an OnComponentAdded function or the ability to set defaults on the script itself but neither is possible as far as I have seen.

    is there an elegant way to give a script component some useful default gradient values?

    thx in advance
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    edit: sorry, think I misread the question. You mean within the editor, not anything in runtime?

    You're into the realm of editor scripting for things like that, I'd guess that would be done in "OnEnable" for a "CustomInspector"... few bits in the learn section, a few good vids from Unite on youtube etc.
     
    Last edited: Aug 11, 2016
  3. Eraph

    Eraph

    Joined:
    Aug 15, 2015
    Posts:
    45
    Well, I might be a bit late to the game but I have the solution!

    Code (CSharp):
    1. public Gradient MyGradient = new Gradient() {
    2.     // The number of keys must be specified in this array initialiser
    3.     colorKeys = new GradientColorKey[3] {
    4.         // Add your colour and specify the stop point
    5.         new GradientColorKey(new Color(1, 0, 0), 0),
    6.         new GradientColorKey(new Color(1, 1, 0), 0.5f),
    7.         new GradientColorKey(new Color(0, 1, 1), 1)
    8.     },
    9.     // This sets the alpha to 1 at both ends of the gradient
    10.     alphaKeys = new GradientAlphaKey[2] {
    11.         new GradientAlphaKey(1, 0),
    12.         new GradientAlphaKey(1, 1)
    13.     }
    14. };
     
    Last edited: Jan 5, 2019
    TalofaKalib and CrazyIvanTR like this.
  4. CrazyIvanTR

    CrazyIvanTR

    Joined:
    Oct 8, 2016
    Posts:
    3
    Works like a charm, even on Editor Window scripts. Thank you. (The first array needs to have length 3 but anyone can figure that much out :p)
     
  5. Eraph

    Eraph

    Joined:
    Aug 15, 2015
    Posts:
    45
    Thanks, you be correct!