Tuesday, October 1, 2019

Reporting Services Basics: Adding Groups to Reports

The series so far:

  1. Reporting Services Basics: Overview and Installation
  2. Reporting Services Basics: Creating Your First Report
  3. Reporting Services Basics: Data Sources and Datasets
  4. Reporting Services Basics: Parameters
  5. Reporting Services Basics: Adding Groups to Reports

So far in this series, I’ve shown you how to create a basic report with parameters. The next necessary skill for report developers is to add grouping levels to the report. Managers often want to see subtotals, for example, at various levels, and adding groups is the way to do this. The report might be divided into categories and subcategories, maybe by locations and departments, or possibly by year and month. Whenever there is a hierarchical relationship in the data, it might make sense to add groups based on those relationships.

There are several ways to add groups, but I’m going to show you the ones that have worked the best for me.

The Groups section

When you look at a report in Visual Studio in design view, you will see a section under the report canvas with Row Groups and Column Groups as shown in Figure 1.

Figure 1: The groups section

If you don’t see the section, click on the report and then select Report View Grouping from the menu as shown in Figure 2 to make it visible.

Figure 2: Where to turn on the Grouping section

You may be wondering what the difference is between column and row groups, and they are quite different. Row groups are used to organize the report into horizontal sections in a typical report. Figure 3 shows one page of a report with row groups.

Figure 3: A report with row groups

Column groups are used in matrix reports, which might also be described as “pivot” reports. A matrix report displays data from a column across the top of the report as headings. You can also add row groups to matrix reports. For example, you might want to display several years across a report along with row groups for category and subcategory as shown in Figure 4.

Figure 4: A matrix report

The SSRS Toolbox contains Table and Matrix items. When you add either one to a report, you’ll notice that each is called a Tablix instead of the original name. It’s also possible to turn a Table into a Matrix by adding column groups or turn a Matrix into a Table by removing the column groups. In my experience, it is better to start with the one you need.

For years, I used the SSRS wizard to create matrix reports, but eventually I realized that simple matrix reports were not that difficult.

Creating a matrix report

In this example, I’ll show you how to create the report shown in Figure 4. If you need help with setting up an SSRS project or creating data sources or datasets, be sure to go back to the earlier articles in this series to learn more.

To get started, you’ll need an SSRS project with a shared data source pointing to the AdventureWorks2017 database. Create a new report by right-clicking Reports and selecting Add New Item…. In the Add New Item dialog, select Report. Name the report Sales by year and category and click Add. The dialog will look similar to Figure 5.

Figure 5: Creating a new report

Inside the Report Data window, create a Data Source that points to the project’s Shared Data Source. Create a Dataset that is embedded in the report named ProductSales with the query below:

SELECT PC.Name AS Category,
       PS.Name AS SubCategory,
       P.Name AS ProductName,
       P.ProductID,
       YEAR(SOH.OrderDate) AS OrderYear,
       SUM(SOD.OrderQty) AS Quantity,
       SUM(SOD.LineTotal) AS SalesAmt
FROM Production.Product AS P
    JOIN Sales.SalesOrderDetail AS SOD
        ON SOD.ProductID = P.ProductID
    JOIN Sales.SalesOrderHeader AS SOH
        ON SOH.SalesOrderID = SOD.SalesOrderID
    JOIN Production.ProductSubcategory AS PS
        ON PS.ProductSubcategoryID = P.ProductSubcategoryID
    JOIN Production.ProductCategory AS PC
        ON PC.ProductCategoryID = PS.ProductCategoryID
GROUP BY YEAR(SOH.OrderDate),
         PC.Name,
         PS.Name,
         P.Name,
         P.ProductID;

After creating the dataset, the Report Data window should look like Figure 6.

Figure 6: The Report Data window

The next step is to drag a Matrix object to the report canvas from the Toolbox window. You can also right click the canvas and select Insert Matrix. The empty matrix object will look like Figure 7.

Figure 7: The empty Matrix

When creating a matrix report, the trick is figuring out what goes where. The Columns cell will contain the column you want displayed as headings across the report. The Data cell will contain the value you want to aggregate. The Rows cell will be the remaining columns. In this case, the report must display the years across the report and add up the sales amount.

Drag OrderYear to the Columns cell, SalesAmt to the Data cell, and Category to the Rows cell as shown in Figure 8.

Figure 8: Report after adding main items

Notice that you can see the grouping levels in the grouping section. When you run the report, it will look something like Figure 9.

Figure 9: The report so far

The report’s not pretty at this point, but it does display as expected with the years going across the top as headings. The original report also includes subcategories. Go back to design view and right click on the Category group in the Row Groups section. Click Add Group Child Group… as shown in Figure 10.

Figure 10: Adding a Child Group

This brings up the Tablix group dialog. Select SubCategory as shown in Figure 11.

Figure 11: The Tablix group dialog

After clicking OK, the report should now look like Figure 12.

Figure 12: After adding SubCategory

When previewing the report, the top of it should look like Figure 13.

Figure 13: The report

You can format your report or not as desired since this article is about grouping, but at this point, I have to add some formatting for my own sanity! In this case, I have bolded the top row and the first two columns. Everything should end up bolded except for the Data cell as shown in Figure 14.

Figure 14: Bold everything except for the total

I also formatted the SalesAmt in the Data cell to be Currency with a thousands separator and no decimal places and added a heading with the report name. The default margins are too wide for this report, so I also changed them in the Report Properties and made sure that everything in the report was pulled to the left. (To learn more about formatting, see the previous articles.)

After the formatting is complete, the report looks like Figure 15.

Figure 15: The formatted report

The next step is to add some totals to the report. It is so easy to do when working with matrix reports! Right-click the Data cell that contains the summed SalesAmt and select Add Total Row. Repeat for Add Total Column. Figure 16 shows you where to find these.

Figure 16: Adding totals

Adding these two totals will leave your report canvas looking like Figure 17.

Figure 17: After adding the row and column totals

You might just guess the next step: adding a grand total in the empty cell. Hover over the cell until the column list appears and click it as shown in Figure 18. Select SalesAmt which will automatically sum.

Figure 18: Adding SaleAmt to the empty cell for a grand total

I also had to format that last cell since it didn’t pick up the previous formatting. After running the report, the first page in Print Layout mode looks like Figure 19.

Figure 19: The matrix report with totals in Print Layout mode

Obviously, you can add colors, a footer, and more to make this report look nicer, but just getting the data displayed correctly was quite simple! There’s one more thing that might be useful here. If you are in Print Layout mode and scroll, you’ll see that the top headings do not carry over from page to page. (If you are seeing alternating blank pages, go back adjust the page margins and make sure that the report edge has been pulled to the left.) To get the headings to appear on the second and subsequent pages, go to the Tablix properties and change the RepeatColumnHeaders and RepeatRowHeaders to True as shown in Figure 20. Probably the easiest way to see the Tablix properties is by selecting it from the list in the Properties window.

(Note that this method to repeat headings doesn’t work on regular table reports, and I’ll explain how to do that later in the article.)

Figure 20: The properties to get the matrix report headings to repeat

Now that you have seen how to create a matrix report, it’s time to learn how to create a regular row-grouped report.

Creating a table report

You saw a glimpse of row groups in the last section, but this time you will learn even more about row groups in reports as you create the report shown in Figure 1. To get started, create a new report in the project with the name Product Sales. It will also point to the project’s shared data source. Create a dataset using the same query that was used in the matrix report. Add a Table control to the report canvas and fill in the Data row, also known as the detail group, as shown in Figure 21. The headings should fill in by themselves.

Figure 21: The table with the detail row fields

The report is grouped by Category Sub Category OrderYear, so OrderYear is the first “parent” above the detail. In this type of report, I think it is easier to start at the detail and build out, but you can also go the other way. To add the group, right click the Details group in the Row Groups section. Select Add Group Parent Group… as shown in Figure 22.

Figure 22: Adding a parent group

This will bring up the Tablix group dialog where you will select the group’s field. Select OrderYear since it is the direct parent of the detail row. Also check Add group footer. This is where the subtotals will go. The dialog should look like Figure 23.

Figure 23: The Tablix group dialog

After you click OK to add the group, you’ll see quite a few changes to the report canvas. The Order Year group has been added to the report and to the Row Groups section. Figure 24 shows the report canvas at this point.

Figure 24: The OrderYear group added to the report

The next parent level is SubCategory. This time, I’ll show you another way to add a group. Right-click on the OrderYear cell and select Add Group Parent Group… as shown in Figure 25.

Figure 25: Another way to add a parent group

Add SubCategory as the new group and be sure to select Add group footer. Repeat the process to add Category using either method. Make sure to add the new group as a parent to SubCategory. Once all the groups are added, the report canvas should look like Figure 26.

Figure 26: All the groups added to the report

There are a lot of empty cells, and you can add totals to some of them. To figure out which grouping level a particular cell belongs to just select it. You’ll see the grouping level light up in orange as shown in Figure 27.

Figure 27: The grouping level lights up in orange

To add subtotal for each level, fill in SalesAmt for each cell underneath the SalesAmt cell. You can also add subtotals for Quantity. They will automatically sum as shown in Figure 28.

Figure 28: Adding subtotals

You can also add a grand total to the report by right-clicking the bottommost SalesAmt cell and selecting Add Total as shown in Figure 29.

Figure 29: Adding a grand total

When adding a total in this way, it is automatically added to the next parent grouping level. In this case, Category is at the top, so the total is added to the report level. You can add a grand total for Quantity. In this case, just add Quantity to the cell. The report design should look like Figure 30.

Figure 30: Adding grand totals

Preview the report. The report should look something like Figure 31.

Figure 31: The unformatted report

There is quite a bit of formatting that should be done, but I’ll leave it up to you to decide what to do except to be sure to modify the report’s margins so that all the fields fit on one page. After formatting, my report looks like Figure 32.

Figure 32: Report with some formatting

If you take a close look, it’s hard to tell what levels the total amounts refer to. To fix that, follow these steps. In the cell under ProductName, add this expression to the Value property:

="Total for " & Fields!OrderYear.Value

Holding down the Shift key, select the two cells in row 4 and columns 4 and 5. Right-click and select Merge Cells as shown in Figure 33.

Figure 33: Merging two cells

Add this expression to the new larger cell:

="Total for " & Fields!SubCategory.Value

Remove the word Total from the cell to the left. Merge the cells in row 5 and columns 4 and 5. Add this formula:

="Total for " & Fields!Category.Value

Finally, merge the cells in the bottom row and columns 4 and 5. The cell should just say Grand Total. Delete the original word Total from several cells. The report design should look like Figure 34.

Figure 34: The subtotals labeled

I would like to move some of the labels more to the left, but I found that the Merge Cells option was not always available. If it is for you, then modify accordingly.

The last thing to do to make this report more usable is to have the headings repeat on new pages. If you go into Print Layout mode and scroll to page 2, you will see that the top headings do not repeat. The RepeatRowHeaders property doesn’t seem to do anything on regular table reports. There is a way to do this, though.

On the grouping section at the bottom of the page, select Advanced Mode as shown in Figure 35.

Figure 35: Turning on Advanced Mode

Make sure this is checked which will add Static sections to the row and column groups as shown in Figure 36.

Figure 36: The Static groups

Working only on the row groups, select the first Static group and open the Properties window. Change the RepeatOnNewPage property to True as shown in Figure 37.

Figure 37: The RepeatOnNewPage property

Repeat the process for the next two Static groups. Now when you run the report and scroll to page 2, you’ll see the top headings repeated. Figure 39 shows you page 2 of my report.

Figure 39: The report with repeating row headings

Summary

This article introduced adding grouping by walking you through the creation of two simple reports. This article covered a lot of ground, but there is still so much to learn. In the next article, you’ll learn more about adding expressions to reports to add even more functionality.

 

The post Reporting Services Basics: Adding Groups to Reports appeared first on Simple Talk.



from Simple Talk https://ift.tt/2ngPx8Z
via

The Case of the Vanishing Index Compression

Recently, we started adding compression to some of our larger tables in our data warehouse where columnstore indexes didn’t make sense. (For example, some very large dimension tables, and a few facts where they are not used for large aggregates in the common manner).

The changes were checked into source control, we monitored performance, all seemed good. Then next time we were doing a code review/compare source control with our development instances, we discovered changes that we were not expecting. Indexes were no longer compressed in some cases.

So I pulled out my Sherlock Holmes hat (which I guarantee you doesn’t exist, and if it did it would have Mickey ears on it), and started sleuthing. To recreate the crime, I will create the following index in the WideWorldImporters database, just a simple index with page level creation turned on:

CREATE INDEX Description ON Sales.OrderLines(Description) 
                           WITH (DATA_COMPRESSION = PAGE);

So now, the index is compressed, right? If you are wondering what the answer is to this question, the answer is yes, clearly, but there is a slight problem with that logic. Is the index really compressed? Check the metadata of the index:

SELECT *
FROM   sys.indexes
WHERE  indexes.object_id = OBJECT_ID('Sales.OrderLines')
  AND indexes.name = 'Description';

The only mention of compression is “compression_delay”, which still might give you the feeling that compression is a part of the index metadata. What happened in our case was that in our processes to truncate and reload a table, we were disabling one or more indexes, loading the data, then rebuilding the index, using a process such as:

ALTER INDEX Description ON Sales.OrderLines DISABLE;
--Load the data
ALTER INDEX Description ON Sales.OrderLines REBUILD;

Now the index should be right back to where it started, right? If you query sys.indexes, everything will look the same, but remember how sys.indexes had nothing about compression? The compression is no longer in effect, as you can see in sys.partitions.

SELECT partitions.data_compression_desc
FROM   sys.partitions
         JOIN sys.indexes
           ON indexes.object_id = partitions.object_id
               AND indexes.index_id = partitions.index_id
WHERE  indexes.object_id = OBJECT_ID('Sales.OrderLines')
AND indexes.name = 'Description';

This returns:

data_compression_desc
---------------------------------
NONE

Partitions are where compression information is stored, because partitions (even if the table/index is not technically partitioned it has one partition), are compressed. Compression delay is part of a columnstore index, which is always compressed, and how long it waits to move the changes from the delta store to a columnstore segment is controlled by the delay. For more on that, see Niko Neugebaur’s blog here:):

The way you have to rebuild the index if you wish to keep it compressed after a disable, is to specify the data compression again:

ALTER INDEX Description ON Sales.OrderLines DISABLE;
--Load the data
ALTER INDEX Description ON Sales.OrderLines REBUILD 
                    WITH (DATA_COMPRESSION = PAGE);

Checking again in sys.partitions you have:

data_compression_desc
---------------------------------
PAGE

Problem solved and fairly easy to handle if you are seeing this problem in a typical OLTP database. In these cases, if you are disabling and reenabling indexes on a regular basis, it should be only a few indexes, (and if you are commonly disabling them first, you may need to question your processes.)

Just executing the following code to rebuild your index:

ALTER INDEX Description ON Sales.OrderLines REBUILD;

Effectively recreates the index, but it does not change the compression of the object’s partition, because a REBUILD doesn’t drop the index in the same way that a DISABLE does. If your physical structure is partitioned, this will be possibly be more obvious to you, in that you can compress only certain partitions. (If you are using the code that follows, you would need to extend it if your tables are partititoned, and it includes protections that stop it from working on partitioned tables).

Note that the way you change the compression status of the index is to do a rebuild.

ALTER INDEX Description ON Sales.OrderLines REBUILD 
                    WITH (DATA_COMPRESSION = PAGE);

The way we combatted this is in our data warehouse, non-partitioned case was by creating a table of indexes that are compressed and using that information our index rebuild stored procedure. This works fine if every programmer and DBA realizes this method and doesn’t use direct DDL to do this process.

CREATE SCHEMA Utility;
GO
-- Use to hold the status of compression for an index with disabling it
CREATE TABLE Utility.IndexCompressionMetadata
(
     SchemaName sysname NOT NULL,
     TableName sysname NOT NULL,
     IndexName sysname NOT NULL,
     CompressionStyle sysname NOT NULL,
     CONSTRAINT PKIndexCompressionMetadata PRIMARY KEY (SchemaName,TableName,IndexName)
)
GO

CREATE OR ALTER PROCEDURE Utility.Index$Disable
(
     @SchemaName sysname,
     @TableName sysname,
     @IndexName sysname
)
AS
 BEGIN
     SET NOCOUNT ON;
     IF EXISTS (
         SELECT *
         FROM Utility.IndexCompressionMetadata
         WHERE IndexCompressionMetadata.SchemaName = @SchemaName
           AND IndexCompressionMetadata.TableName = @TableName
           AND IndexCompressionMetadata.IndexName = @IndexName) 
      THROW 50000,'This Index Already Has Compression Metadata. Fix Manually',1;
     IF EXISTS (
           SELECT *
           FROM sys.indexes 
                 INNER join sys.data_spaces 
                  ON indexes.data_space_id = 
                            data_spaces.data_space_id
           WHERE data_spaces.type_desc ='PARTITION_SCHEME'
             AND OBJECT_SCHEMA_NAME(indexes.object_id) 
                               = @SchemaName
             AND OBJECT_NAME(indexes.object_id) = @TableName
             AND Indexes.name = @Indexname
     )
     THROW 50000,'This Utility may not be used with Partitioned Indexes',1;
     
     BEGIN TRY;
     BEGIN TRANSACTION;
       INSERT INTO Utility.IndexCompressionMetadata
                (SchemaName, TableName,
                 IndexName,CompressionStyle)
       SELECT @SchemaName, @TableName,@IndexName, 
              partitions.data_compression_desc
       FROM   sys.partitions
                 JOIN sys.indexes
                   ON indexes.object_id = partitions.object_id
                     AND indexes.index_id = partitions.index_id
       WHERE  indexes.object_id = 
                  OBJECT_ID(CONCAT(@SchemaName,'.',@TableName))
         AND indexes.name = 'Description';

       DECLARE @query varchar(MAX);
       SET @query = CONCAT ('ALTER INDEX ',@IndexName,
                          ' ON ',@SchemaName,'.',
                          @TableName,' DISABLE');
       --SELECT @query
       EXEC (@query);
       COMMIT TRANSACTION;
       END TRY
      BEGIN CATCH
          IF @@TRANCOUNT > 0
               ROLLBACK;
          THROW;
       END CATCH;
END;

Now to disable the index using:

EXEC Utility.[Index$Disable] @SchemaName = 'Sales',
                             @TableName = 'OrderLines',
                             @IndexName = 'Description';

Now you can check the compression on the partition, and what you will see is that it doesn’t even exist, because for indexes, the partition is deleted in the disable process.

SELECT partitions.data_compression_desc
FROM   sys.partitions
          JOIN sys.indexes
            ON indexes.object_id = partitions.object_id
               AND indexes.index_id = partitions.index_id
WHERE  indexes.object_id = OBJECT_ID('Sales.OrderLines')
AND indexes.name = 'Description';

You can also see in the metadata, that the index will have PAGE compression when the index is rebuilt using the tool we are about to create:

SELECT *
FROM   Utility.IndexCompressionMetadata;

This returns:

SchemaName    TableName    IndexName     CompressionStyle
------------- ------------ ------------- -------------------
Sales         OrderLines   Description   PAGE

Then this stored procedure will be used to reenable the index, with the last compression status

CREATE OR ALTER PROCEDURE Utility.Index$Enable
(
     @SchemaName sysname,
     @TableName sysname,
     @IndexName sysname
)
AS
 BEGIN
   BEGIN TRY;
     BEGIN TRANSACTION;
     DECLARE @compressionStyle sysname = 
         (SELECT IndexCompressionMetadata.CompressionStyle
          FROM  Utility.IndexCompressionMetadata
          WHERE IndexCompressionMetadata.SchemaName = @SchemaName
            AND IndexCompressionMetadata.TableName = @TableName
            AND IndexCompressionMetadata.IndexName = @IndexName)
    
     IF @compressionStyle IS NULL
          THROW 50000,'This procedure can only be used on indexes that are disabled, and registered with Utility.Index$Disable',1;

     DECLARE @query varchar(MAX);
     SET @query = CONCAT ('ALTER INDEX ',@IndexName,' ON ',@SchemaName,'.',@TableName,' REBUILD',
         ' WITH (DATA_COMPRESSION = ' + @compressionStyle + ')')
     --SELECT @query
     EXEC (@query);

     DELETE FROM Utility.IndexCompressionMetadata
     WHERE IndexCompressionMetadata.SchemaName = @SchemaName
       AND IndexCompressionMetadata.TableName = @TableName
       AND IndexCompressionMetadata.IndexName = @IndexName;

     COMMIT TRANSACTION;
   END TRY
   BEGIN CATCH
          IF @@TRANCOUNT > 0
          ROLLBACK;
          THROW;
   END CATCH;
END;

Execute the procedure:

EXEC Utility.Index$Enable  @SchemaName = 'Sales',
                           @TableName = 'OrderLines',
                           @IndexName = 'Description';

Now you can check the compression on the partition, and what you will see is that it is not compressed with PAGE level compression.

Mystery solved. It is funny how much fun finding things like this can be once you get started. So when you find something seems wrong in your configuration, never panic, just start looking at the system catalog views and look for the clues. The fact that the index had no compression information was my first clue that this was going to be a problem with how compression is done with indexes.

 

The post The Case of the Vanishing Index Compression appeared first on Simple Talk.



from Simple Talk https://ift.tt/2nd3rsI
via

Friday, September 27, 2019

Using the iTween Plugin for Unity

It’s happened to every developer at some point; you’re trying to accomplish a simple task but the method to accomplish said task requires more lines of code than you would like. Surely it doesn’t have to be this way. This is often especially true in the world of game development, where there are often many steps required to accomplish one large goal. For example, suppose you wish to fade an object while your game is running. Two common ways to do this would be to tie the fade action to an animation and call this animation in code or interpolate some color values in your script to create the fade effect. While they get the job done, both methods require several steps to accomplish. What if there was something out there that could do all that work in a single line of code?

You might think this is wishful thinking, but the reality is that such a feat is very possible. A plugin for Unity, iTween, can give you the result you want with minimal effort required on your end. iTween is an animation plugin that uses interpolation systems to create animations that look and feel good. The goal of the plugin, according to its website, is to streamline the production of your Unity project and put you in the mindset of an action-movie director instead of a coder. Here you’ll be shown a small project demonstrating iTween’s simple use and what it can bring to your Unity project.

Setup

Of course, to use iTween, you’ll have to create a project (Figure 1) and import the iTween plugin into said project.

Figure 1: Creating a new project

Name the project iTween Demo. To better show off iTween’s use, it is recommended that the project be in 3D. Decide on a location for the project, then create it as shown in Figure 2.

Figure 2: Project name, template, and creation.

First, you’ll have to get the iTween asset into your project. The easiest way to do this would be through Unity’s Asset Store. In the top menu, navigate to Window->Asset Store as shown in Figure 3.

Figure 3: Opening the Unity Asset Store

Once the Asset Store has loaded, you will need to search for iTween. The item you’ll be looking for will have a matching name created by PixelPlacement and should be free. After selecting the asset, click the download button. Once the asset has finished downloading, you’ll be able to press the button again to import iTween into the project. Once the plugin is extracted you’ll be able to import it into the project, as shown in Figure 4.

Figure 4: Importing iTween

After the package manager is finished loading, click Import near the bottom of the window to put iTween into your project. The example project will also need some music and a single sound to test out iTween functionality. If you need some recommendations, Loop & Music Free by Marching Dream and Sound FX – Retro Pack by Zero Rare will have what you need for sound effects. With all your assets in place, close out the Asset Store and begin setting up the project. The Assets window should look similar to Figure 5.

Figure 5: The current Assets window

To begin, two objects will need to be placed within the game world. The first will be a regular cube that will showcase the iTween animations. Your cube object can be created by going to the Hierarchy and selecting Create->3D Object->Cube, as shown in Figure 6.

Figure 6: Creating a cube.

In its Transform component in the Inspector window, set the rotation to x -10, y 45, and z -30. After that, set the scale to 2 across all axes. Figure 7 shows how that should look.

Figure 7: Setting the rotation and scale of the cube.

Create another 3D object, this time a sphere. This object will give the Cube object something to look at in a specific iTween animation. Supposing the sphere was the moon, it can be placed in the sky. The exact coordinates are x -6, y 11, z 15. The scale and rotation remain the same. When complete, the scene should look similar to Figure 8.

Figure 8: How the project currently looks

One last task remains before the coding part begins. Among other things, the Cube object will be able to fade in and out as though it used a cloaking device. However, its default material will not allow the fading. Instead, a new material will be created. In the Assets window right-click, then choose Create->Material as shown in Figure 9 and name the material FadeMat.

Figure 9: Creating a new material

Immediately after creating the material, navigate to the Inspector window and set its rendering mode to Transparent like Figure 10.

Figure 10: Setting the material’s rendering mode

Finally, the new material will need to be assigned to Cube. Select the Cube object, go to the Mesh Renderer component in the Inspector window, and click the arrow next to Materials. Then click and drag the FadeMat material from the Assets window into the Element 0 field under Materials. Figure 11 shows you how to do this.

Figure 11: Setting Cube’s material

All that’s left is a sound manager for the sound effect that will be played later. Create a new object, this time an Audio Source object. It can be created via Create->Audio->Audio Source. Name it SoundManager, and then the setup will be complete. To begin coding the project, create a new asset in the Assets window, this time a script, and call it Actions. Once created, double click the script to open it in Visual Studio.

The Code

To start, you want to make this script require the object it’s attached to have an AudioSource component. Doing this requires the following line of code above the class declaration:

[RequireComponent(typeof(AudioSource))]

Once the Actions script is attached to the object, it will automatically add this AudioSource component for you. In addition, it will prevent the removal of this component so long as the Actions script component is also attached. Next, the Start and Update functions can be removed or commented out as they will not be needed. Then you get variable declaration out of the way.

public Transform lookObject;
public AudioSource otherAudio;
public AudioClip stabSound;
public MeshRenderer mr;

The Transform variable, lookObject, will hold the Transform information from the Sphere object created earlier. One of the iTween animations the project will use will involve the Cube looking at the Sphere, but in order to do that, it will need to know where the Sphere is. Following this is the otherAudio variable, which will reference SoundManager‘s AudioSource component and stabSound which, despite the violent sounding name, has nothing to do with sharp objects. This is in reference to a sound that will be played using iTween’s Stab command, which will be covered later. Finally, there’s mr, which will contain information about the Cube object’s MeshRenderer component. This is how the object’s colour will be reset when you want to stop an iTween animation.

At this point, the script should look similar to Figure 12.

Figure 12: Beginning of Actions script.

With everything prepared, the first thing to do is to develop a UI that will display some buttons and text. Ordinarily you might do this in the Unity Editor rather than in code, but for this project using Unity’s OnGUI method will work nicely. But what does OnGUI do? OnGUI is a method that handles the creation and execution of UI elements and functionality. It’s a helpful method for when you need a quick UI or to create showcases such as this.

private void OnGUI()
{
        GUI.Label(new Rect(600, 10, 150, 50), "# of iTweens running: " 
            + iTween.Count());
}

After creating the method, the very first thing done is to create a GUI label. A new rectangle is created in this label that will contain some text. This text will display the number of iTween animations currently running using iTween’s Count method. Now several buttons will be created in the OnGUI function that the user can press to begin an iTween animation. The first three all relate to an object’s transform and look like this:

if (GUI.Button(new Rect(10, 10, 100, 20), "Move Object"))
        iTween.MoveBy(gameObject, iTween.Hash("x", 4, "easeType", 
        "easeInOutExpo", "loopType", "pingPong", "delay", 0.3f, 
        "onStart", "PlaySound"));
if (GUI.Button(new Rect(10, 30, 100, 20), "Rotate Object"))
        iTween.RotateBy(gameObject, iTween.Hash("y", 0.5f, "easeType", 
        "easeInOutExpo", "loopType", "pingPong", "delay", 0.5f));
if (GUI.Button(new Rect(10, 50, 100, 20), "Scale Object"))
        iTween.ScaleBy(gameObject, iTween.Hash("x", 3, "y", 3, "z", 3, 
        "easeType", "easeInOutExpo", "loopType", "pingPong", 
        "delay", 1f));

Now would be a good time to break down what all of these are doing. First, you’re creating a new button in code and checking if this button is clicked. The button’s size and position are defined in the new Rect‘s parameters. Some text is created within this rectangle, and then you get to the button’s functionality the next line down. As you can see, all three buttons operate very similarly to each other. You first select which iTween action you wish to take, followed by setting which object should perform this action. In this case, the object is the one this script will be attached to, so the code just says gameObject.

Next, an iTween hash is defined. This is where you set what part of an object is to be animated, such as the x-axis, and how it will animate. In the MoveBy iTween for instance, you’ve told Unity to move the object on its x-axis to four and set the easeType to easeInOutExpo. The easeType in an iTween, as the name implies, is how the object will ease in and out of its animation. There is also loopType, which has been set to pingPong in all three animations. Using pingPong will cause the animation to play forward then backward over and over. You can also set the loopType to none and loop. Next is delay which allows you to set how much time you want to pass before the animation begins, and finally in MoveBy, you have an onStart parameter. OnStart is where you can define a method to perform upon the start of an iTween, in this case a currently undefined method named PlaySound. Speaking of which, perhaps now is a good time to create this method.

void PlaySound()
{
        iTween.Stab(gameObject, iTween.Hash("audioClip", stabSound, 
              "audioSource", otherAudio, "volume", 1, "delay", 
              0.35f, "loopType", "none"));
}

A new iTween has been introduced, named Stab. Admittedly it sounds rather vicious, but all it does is play a sound effect of your choosing. Like the earlier iTweens, Stab first asks you to select a game object then create a hash. This time the hash has you setting audioClip to the previously defined stabSound, which will come from the otherAudio AudioSource. The volume is set to 1, a delay is set, and Unity is told that there will be no looping. At this point, the script should so far look like the one in Figure 13.

Figure 13: OnGUI and PlaySound methods.

Returning to the OnGUI method, the next few iTweens will deal with changing an object’s appearance as well as playing with the game’s music.

if (GUI.Button(new Rect(10, 70, 100, 20), "Color Object"))
        iTween.ColorTo(gameObject, iTween.Hash("r", 5, "easeType", 
        "easeInOutExpo", "loopType", "pingPong", "delay", 0.5f));
if (GUI.Button(new Rect(10, 90, 100, 20), "Change Pitch"))
        iTween.AudioTo(gameObject, iTween.Hash("pitch", 0, "delay", 
        1, "time", 3, "easeType", "easeInOutExpo", "onComplete", 
        "ReturnAudio"));
if (GUI.Button(new Rect(150, 10, 100, 20), "Fade Object"))
        iTween.FadeTo(gameObject, iTween.Hash("alpha", 0, "time", 1, 
        "delay", 0.35f, "easeType", "easeInOutExpo", "loopType", 
        "pingPong"));

Perhaps you’re noticing a pattern here? Barring a few key differences, almost every iTween is structured the same way. The most significant difference is in which value is being changed. For example, in ColorTo, the object’s r (red) value is changing while RotateBy is adjusting the object’s y rotation value. This is one more reason for iTween’s appeal – that being the universal rules to using an iTween command. There are of course some exceptions such as Stab, and you can add or remove complexity of the commands on a whim like what was done with the AudioTo line. In this iTween, the opposite of the MoveBy's onStart parameter is being performed, onComplete. Once this iTween has finished its task, it will perform the ReturnAudio method. That method performs a slightly different iTween that demonstrates how you can control as much or as little of the iTween command as you wish.

void ReturnAudio()
{
        iTween.AudioTo(gameObject, iTween.Hash("pitch", 1, "time",
        1.6, "delay", 0.5f));
}

There are a few other animations this project is looking to demonstrate before the script is complete. The following code shows how you can create an animation that rapidly shakes the object, “punches” the object, and how an object can be made to look at another point in the world. Once again, all this is to be entered in the OnGUI method.

if (GUI.Button(new Rect(150, 30, 100, 20), "Look Object"))
        iTween.LookTo(gameObject, iTween.Hash("lookTarget", lookObject,
        "time", 1, "delay", 1, "easeType", "linear", "loopType", 
        "pingPong"));
if (GUI.Button(new Rect(150, 50, 100, 20), "Shake Object"))
        iTween.ShakePosition(gameObject, iTween.Hash("amount", 
        new Vector3(2, 2, 2), "time", 2, "delay", 0.5f, "easeType", 
        "easeInBounce", "loopType", "loop"));
if (GUI.Button(new Rect(150, 70, 100, 20), "Punch Object"))
        iTween.PunchPosition(gameObject, iTween.Hash("amount", 
        new Vector3(5, 5, 5), "time", 2, "delay", 1, 
        "loopType", "loop"));

All of these animations involve feeding the code some kind of position or transform data to complete the task. For instance, LookTo has you giving lookTarget the transform data for lookObject, also known as the Sphere object created earlier. Similarly, ShakePosition and PunchPosition ask for Vector3 data to accomplish their goals. Now, the script is mostly finished but you might be wondering what one can do about all these looping animations. Naturally, there’s a way to stop all these animations immediately if so desired.

if (GUI.Button(new Rect(450, 10, 110, 20), "Stop Everything"))
{
        iTween.Stop();
        transform.position = new Vector3(0, 0, 0);
        transform.localScale = new Vector3(2, 2, 2);
        transform.eulerAngles = new Vector3(-10, 45, -30);
        mr.material.color = Color.white;
        iTween.AudioTo(gameObject, iTween.Hash("pitch", 1, 
            "time", 1.6, "delay", 0.5f));
}

The code, in particular, is iTween.Stop which, you guessed it, stops all currently running iTweens. The remainder of the code resets the object’s position, scale, rotation, and colour. It also uses the same AudioTo command from the ReturnAudio method in case this is pressed in the middle of the audio’s pitch being brought down. Now that the script is complete, the only task left to do is save the script and go back to the Unity editor to finish some last-minute tasks.

Finishing the Project

Very little remains to be done before the project is complete. First, you’ll need to attach the Actions script to the Cube object. To make it easier to work with the Cube properties, you might want to lock the inspector. Figure 14 shows where to drag the Actions script.

Figure 14: Attaching the Actions script component to Cube

Notice an AudioSource component is attached to the Cube at the same time thanks to the RequireComponent class attribute from earlier.

In the AudioSource component, place a song of your choice into the AudioClip field, as shown in Figure 15. This is the song that will receive a pitch change thanks to the AudioTo command from earlier. You can also set Loop to true if you wish, but it is not required.

Figure 15: Selecting a music track

All that’s left is to fill in the fields from the Action script component. Look Object will be given the Sphere object’s Transform data, while SoundManager will fill the Other Audio field, as shown in Figure 16.

Figure 16: Filling Look Object and Other Audio fields

Stab Sound will be a sound effect of your choosing. Like when selecting the music for Cube‘s AudioSource component, you’ll need to drag some audio file from the Assets window into Stab Sound. Finally, Mr is filled by dragging Cube’s Mesh Renderer component into the Mr field shown in Figure 16.

Figure 17: Filling the Mr field

Once all the fields are filled, you are ready to test out the project. The GUI you created in code will instantly appear and clicking any of the buttons will perform their respective tasks. Try mixing and matching iTweens so, as an example, you can have it changing size while rotating. You can also adjust the position of the Sphere object to get a slightly different result when clicking the Look Object button. Figure 18 shows the GUI once you are playing the game.

Figure 18: The finished project

Conclusion

It almost feels like cheating when using iTween, doesn’t it? What’s normally a three to five-step process can be simplified into one step, consisting of one line of code. The examples shown here are just a small sampling of what iTween can do. You can check out iTween’s website to see more examples as well as some documentation showing all the different commands available to you. Whether it be used for prototyping or giving your current development a nice boost, there’s plenty of reason to consider having the iTween plugin on hand for any project.

 

The post Using the iTween Plugin for Unity appeared first on Simple Talk.



from Simple Talk https://ift.tt/2mmTl8n
via

Wednesday, September 25, 2019

Getting back to normal after a long summer

It has been a fun summer, sort of.

13 weeks ago, I had my left knee replaced to balance out my other two hip replacements on my right side. This is hopefully the last time that Dr Morrison of Southern Joint Replacement Institute ever has to cut into parts of my body with power tools. (Never say never, but all my other joints are in decent enough shape comparatively!) For this surgery I did something I did not do for my last two. I kind of shut out the SQL world for a while. I barely worked for 4 weeks, and I didn’t blog or pay attention to several book projects I am working on currently.

This was kind of a wonderful feeling, but I definitely started missing writing blogs, articles, and a book I had started working on with a group of authors earlier in the year. The book had to come first before I got back into the real world, and last Saturday night, I finished my parts that were of the critical path of getting it done. (I revised (fairly heavily) two chapters, then tech edited half of the book. So far, I am pretty proud of my time on the book, and I expect the output to be really great.

The book is “SQL Server 2019 Administration Inside Out”, from Microsoft Press. You can find out more about here.

It has even been a fairly long time between conferences for me too. My last SQL Saturday was SQL Saturday Chattanooga, where I was on the leadership team. I missed Louisville, where I had been to every one of the events prior, as well as a few others like Indianapolis that I had been to the prior year. It was kind of hard to watch from the Twitterverse this year, but it was kind of restful there too. I also worked on the crew for Music City Tech again this year, which was in early September.

My next SQL Saturday I have scheduled is SQL Saturday Memphis, cause you know, I gotta support my Tennessee folks! I will be doing my newest presentation, Relational Design Critique, which I really enjoy with a group. I put up a design, and we discuss the issues with the model. Later that week, I will travel out to Richmond to their user group and do the presentation for them (their group was actually the inspiration for the presentation, as something VERY similar was on their list of possible topics for the year!)

The next SQL Saturday I plan to submit to is Nashville (http://www.sqlsatnash.com), my second home! Tammy and Kerry do a great job, and I look forward to attending, and maybe speaking. 

If any of my other editors happen to read this, know that you (and only you) are the next up on my to do list. No one else but you. Not any other SQL project, not my Disney Picture a Day twitter feed, not my Dollywood Pictures twitter feed, not even planning for my upcoming trip to Disney World to see Galaxy’s Edge, and certainly not planning a SQL Saturday, Music City Tech, PASS Summit, or even time with my grandkids. Just you!

The post Getting back to normal after a long summer appeared first on Simple Talk.



from Simple Talk https://ift.tt/2myyuP7
via