Saturday, June 21, 2014

Tech Blog: Useful Unity Inspector Variable Inputs

There are a couple of neat and very useful tricks you can use to help you and/or your team out when creating scripts to attach onto objects. Today I'll show you a couple of inspector mods for variables that will help you out if you want a specific function.

The first one is a variable slider that will accept values within a specified range.


[Range(n,x)]
public float blah= 0;

This is placed at the beginning of the class, just like any other variable. Note the structure of the code. How range is placed in the brackets and the line doesn't end in a semicolon. How the line immediately after that is a float declaration. Also remember to declare the float as public so that it can be accessed outside of the script.

What this will do in the inspector is create a sliding bar which you can drag left and right, (and optionally input a number in the accompanying text box) but the minimum and maximum values will be set to N and X respectively. Want an example?

[Range(0,360)]
public float angle = 0;

Here's my code to simulate a circle. Pretty self explanatory. In my inspector, under the attachment for my code, there is a sliding bar that will let me set the variable between 0 and 360. Any less and it'll default to 0. Any more and it'll default to 360. This is definitely useful for a value that can be changed, but has imposed limits on it. Maybe the maximum speed of a car for example, given an equation for acceleration. Or for measuring circular angles. I don't know. These are just a handful of uses for the range inspector option.

The other one that might be useful to you is the drop down variable selection via an enum.

public enum ObjectType {Obj1, Obj2, Obj3}
public ObjectType object;

Alright, so there's alot going on here. Let me break it down. Just like the previous option, this too goes right at the start of the class before everything else. When you create an enum, you create your own subclass derived from an enum. Use capitalization to name the first line because it'll show that it isn't a variable. That comes later. After naming your new class, you have to declare what's in it. The names that you put within the curly braces are Read Only variables with names for more intuitive understanding. You can put as many as you need in here. Note there's no semicolon at the end again.

Then in the next line, you just create a variable under that new class and that variable will equal whatever of the RO variables you set it to!

This becomes useful later on in your code. You can even use this to write Boolean expressions to check what the variable equals!

if(plantType == PlantType.Kelp1)
{

      blah blah;
}

Well that's all for now. Next time I'll be teaching you how you can use one object to represent many using what I just taught you! Look forward to it!

No comments:

Post a Comment