THE ROAD RUNNER TUTORIAL 5: ADDING SNAGS AND POWERUPS TO OUR GAME

Check out the gameplay of the finished game below:



Now that we have programmed our character to move ahead (yeah, it's just an illusion, but nobody can know it except you, I hope), we will add some powerups and snags. On collecting the snags we will benefit and on collecting the latter, it will be the opposite.

Step 1:
Download the assets from this link. Import this custom package into your project by navigating to Assets->Import Package->Custom Package and selecting the package you downloaded.

Once you import this package, you will notice that the Prefab and Material sub-folders are added to the Assets folder. If you click on the Prefab folder you can see that there are two prefabs named Obstacle and Powerup. The obstacle as you can see is a Banana fruit, on collecting which, our Player will gain energy and the other being an Alcohol bottle, on drinking which, as study suggests, the energy of our player would drain.

If you happen to select any of the prefab you will see something like the image below:


The two important things to notice are the Collider and the Rigidbody.

"Adding a Rigidbody component to an object will put its motion under the control of Unity's physics engine. Even without adding any code, a Rigidbody object will be pulled downward by gravity and will react to collisions with incoming objects if the right Collider component is also present." is a quote from the Unity Documentation. I believe that is simple enough to understand why the two components are used.

IsTrigger: On checking this the field, the collision doesn't actually take place, instead it sends a message when the rigidbody enters/exits the tirgger based on the type of event used.

Gravity: This field is unchecked as we do not want the gravity to play a role on these prefabs.

If you drag and drop this prefab onto the Hierarchy, and double click on the prefab in the hierarchy to note its position (Do not forget to delete the gameobject from the hierarchy once you examine them).

Step 2:
Create a new C# script named SpawnScript. This script, as the name suggests, would be used to spawn the prefabs into the game scene dynamically i.e. through script. Copy the below code into the newly created script:

using UnityEngine;
using System.Collections;

public class SpawnScript : MonoBehaviour {
public GameObject obstacle;
 public GameObject powerup;
 
 float timeElapsed = 0;
 float spawnCycle = 0.5f;
 bool spawnPowerup = true;
 
 void Update () {
  timeElapsed += Time.deltaTime;
  if(timeElapsed > spawnCycle)
  {
   GameObject temp;
   if(spawnPowerup)
   {
    temp = (GameObject)Instantiate(powerup);
    Vector3 pos = temp.transform.position;
    temp.transform.position = new Vector3(Random.Range(-3, 4), pos.y, pos.z);
   }
   else
   {
    temp = (GameObject)Instantiate(obstacle);
    Vector3 pos = temp.transform.position;
    temp.transform.position = new Vector3(Random.Range(-3, 4), pos.y, pos.z);
   }
   
   timeElapsed -= spawnCycle;
   spawnPowerup = !spawnPowerup;
  }
 }
}

The script starts by defining references to the two prefabs(Powerup and Obstacle). The other variables are defined to control the timing and order in which the prefabs are spawned. Higher the value of spawnCycle, larger the time between spawning of the prefabs.
The bool variable spawnPowerup is used to spawn Obstacle and Powerup prefabs alternatively.
In the Update() method, the elapsed time is incremented and then the time at which the new objects are to be spawned is determined. The if else condition checks what object is to be spawned. We also determine the position at which the objects are to be spawned. Only the x co-ordinate is included in a Random range function as we need a static y and z values. The parameters in the Random.Range indicate the min and max value of x co-ordinate within which the random number is to be generated. Further we decrease the value of the timeElapsed so as to maintain the time between spawning of objects.(Note: comment out this line and see the difference). And finally we flip the bool value to spawn the other kind of object the next time around.

Step 3:
Create an empty GameObject and name it as as GameController. This will be a container of the scripts that do not require any object to be attached to. Attach the SpawnScript to this empty GameObject.
You will notice that there are two fields- Obstacle and Powerup are waiting for you to define their values. Drag the prefabs from the Prefab folder and place them onto their respective fields. Once you are done with this, you are left with something like in the image below:


Step 4: 
Create a new C# Script and name it as PowerupScript. Attach the file to the Powerup in the Prefab folder under Assets add the following code and save it.
using UnityEngine;
using System.Collections;

public class PowerupScript : MonoBehaviour {
public float objectSpeed = -0.5f;

void Update () {
 transform.Translate(0, 0, objectSpeed);
 }
}

The above lines of code basically moves the Powerup i.e. the Banana fruit in our case, towards the Character, which for the player playing the game feels as if he is moving towards the Banana.

Step 5:
Create another script named ObstacleScript. Add the below code and attach it to the Obstacle prefab.
using UnityEngine;
using System.Collections;

public class ObstacleScript : MonoBehaviour {
public float objectSpeed = -0.5f;

void Update () {
 transform.Translate(0, objectSpeed, 0);
 }
}

Note that in the case of the obstacle we have Translated towards the y-axis, this is based on the rotation axes of the prefab/object.
Manipulate the axes and check out the differences.
   
Now test this game by pressing the Play button or using the shortcut ctrl+P. You will notice that the banana and Alcohol bottle are being spawned randomly and are moving towards you i.e. you are moving towards them.

Download the completed version of this game from the Resources page.

The Road Runner Tutorial 1: Setting Up The World
The Road Runner Tutorial 2: Setting Up The World Continued
The Road Runner Tutorial 3: Adding A Character To Our Game
The Road Runner Tutorial 4: Set The Ground Moving
The Road Runner Tutorial 6: Collecting The Snags and Powerups
The Road Runner Tutorial 7: Adding Gameplay Logic
The Road Runner Tutorial 8: Creating a Custom GUI Skin
The Road Runner Tutorial 9: Creating a Pause Menu
The Road Runner Tutorial 10: Adding Countdown and Main Menu
The Road Runner Tutorial 11: Adding Sound Effects To Our Game
The Road Runner Tutorial 12: Porting The Game To Android
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

46 comments:

  1. Really It Helped Me A LOT Thank You So MUCH

    ReplyDelete
    Replies
    1. We are glad that you found our posts useful. You might want to check out the next part of the series. Find it here
      http://www.thegamecontriver.com/2014/07/how-to-create-subway-surfer-temple-run-like-game-6.html/

      Delete
  2. Hey I was wondering what you meant in step 3 by respective fields and define value for obstacle and powerup thank you

    ReplyDelete
    Replies
    1. It simply means that the spawnscript has two gameobject reference variables named Obstacle and Power up. And you need to assign value for these variables in the inspector. Values here are the prefabs obstacle and power up which we created and saved in the prefabs folder.
      Hope this made it clear..

      Delete
  3. im stuck at step 2 getting this error : Assets/Scripts/SpawnScript.cs(34,9): error CS8025: Parsing error

    ReplyDelete
    Replies
    1. Make sure you have enclosed the script within
      using UnityEngine;
      using System.Collections;

      public class SpawnScript : MonoBehaviour {

      //code here

      }

      Delete
    2. not working that can u do that u said with whole codes im kinda confused

      Delete
    3. This comment has been removed by the author.

      Delete
    4. This comment has been removed by the author.

      Delete
    5. its not working either keep saying Assets/SpawnScript.cs(34,9): error CS8025: Parsing error same problem

      Delete
    6. #sujit i added a curly bracket at the end and now its working well thanks!

      Delete
    7. #Amoudi Ibrahim, paste this code :


      using UnityEngine;
      using System.Collections;

      public class SpawnScript : MonoBehaviour {

      public GameObject obstacle;
      public GameObject powerup;

      float timeElapsed = 0;
      float spawnCycle = 0.5f;
      bool spawnPowerup = true;

      void Update () {
      timeElapsed += Time.deltaTime;
      if(timeElapsed > spawnCycle)
      {
      GameObject temp;
      if(spawnPowerup)
      {
      temp = (GameObject)Instantiate(powerup);
      Vector3 pos = temp.transform.position;
      temp.transform.position = new Vector3(Random.Range(-3, 4), pos.y, pos.z);
      }
      else
      {
      temp = (GameObject)Instantiate(obstacle);
      Vector3 pos = temp.transform.position;
      temp.transform.position = new Vector3(Random.Range(-3, 4), pos.y, pos.z);
      }

      timeElapsed -= spawnCycle;
      spawnPowerup = !spawnPowerup;
      }
      }
      }

      Delete
    8. This comment has been removed by the author.

      Delete
    9. I have edited and pasted the entire script, which I shud ve done in the first place. Anyhow, glad to know that your errors are resolved

      Delete
  4. First of all i must thank you for your very detailed and helpful tutorials.

    I have followed each of your steps above,
    But the problem is only the powerup is moving towards the player but not the Obstacle.
    Any help would be great.Thank you.

    ReplyDelete
    Replies
    1. If the Powerup is moving then I don't find any reason why the obstacle should not move as we have used identical steps for both of them. Please try following the tutorial again and let me know if you still face the same issue.

      Delete
    2. Thank you for the reply,
      I got it sorted out.

      But now the problem is despite of the snags & power ups the game time remains constant ie.gradually the time is descending from 10 to 0.

      Delete
    3. Chaitanya,

      What did you fix to get the obstacle and power ups to move toward the player?

      Delete
  5. Can anyone tell me why my items are spawning in the sky instead of the ground?

    ReplyDelete
    Replies
    1. and my character is not moving toward them. I did exactly what it said in the steps.

      Delete
    2. Fixed it. Does anyone know how to replace the actual images? Like if I want the whiskey to be something else and the banana? How do we customize these images?

      Delete
  6. where should i put the obstacle and powerup script

    ReplyDelete
    Replies
    1. Add the script to the respective prefabs that we have created i.e., obstacle script to the obstacle prefab and the powerup script to the powerup prefab, both of which are saved in the Prefabs folder under assets, if my memory serves me right.

      Delete
  7. hey please help me out, i am getting this weird error:

    The referenced script on this Behaviour is missing!
    UnityEngine.Object:Instantiate(Object)
    SpawnScript:Update() (at Assets/Prefabs/Scripts/SpawnScript.cs:25)

    ReplyDelete
    Replies
    1. Well, there are two possibilities as to why you are getting this error -
      1. You have renamed the script, check the name of the script in the Assets folder and the name of the class in the script. Make sure both of them are the same.
      2. The script on the prefab (which could be the powerup or the snag/obstacle) is missing and you got to add it again.to the prefab.
      Hope this helps

      Delete
  8. Hey there, not sure if my last post actually got on here so i'll say again,

    The snag for reason is my powerups and obstacles arent moving. I've checked the script and theres nothing wrong with it, I checked scale and there should be no problems. I'm using my own custom assets for the job but everythoing works except the movement as i have checked the references.

    Hope you can help, cheers mate.

    ReplyDelete
    Replies
    1. Not sure what exactly could be the issue, try attaching the script which you are using to translate the obstacle and powerups to something like e cube or a sphere perhaps and see if that works... Or even you could try this for your custom gameobjects in a new scene which has only the custom gameobjects and nothin else, add this script to it to see if it moves.. Sometimes unity fails to work with the prefabs in some scenes, so maybe try that in a new scene and let me know if this helps.

      Delete
  9. Hi um, I can't access the powerup/obstacle download because it says "This link has generated too much public traffic, link temporarily shut down" can you post a new link or something like that?

    (loving the tutorials so far though)

    ReplyDelete
  10. Um when I try to put the script onto the GameControl thing it says " 'SpawnScript' does not exist" Help? oh, and say I didn't want it to banana or alcohol how would I change this?

    ReplyDelete
  11. hi Dear,
    my powerups and obstcls aren't moving towards player...and player donot get them..and my score remains contineously increasing...;plz help meee....

    ReplyDelete
  12. how to create a empty GAME OBJECT in step 3 . i'm new to this unity3d pls help me out......::::::::::

    ReplyDelete
    Replies
    1. click on the GameObject in the Above Pannel and select the First one Option your EmptyObject will be created in Hierarchy

      Delete
  13. How can i add more than 1 different Obstacles

    ReplyDelete
  14. Hi
    i am New to Unity and Following Your Tutorials and this is helping me Alot
    cna you told me How can i add different obstacles and Different person instead of this your One
    share you Contact and View please

    ReplyDelete
  15. Hi I have a question, how can you make the power ups spawn in a straight line? that show up randomly. and also how can you stop the obstacle and power up alternately spawning? Thanks, learning a lot from this site

    ReplyDelete
  16. Hi sir I have this problem when I test my game. I get this error "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.". could you tell me how to fix it? thank you.

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. i have write some code that instantiate some objects using C# in android platform but there is an issue that when there is instantiating objects the Android device hangs until the code runs when instantiate completes then the game runs normal .......... can anybody tell me that why the game hang when instantiate objects?????????

    ReplyDelete
  19. How can I move the snags and powerups in in my desired position?

    ReplyDelete
  20. How can I move the snags and powerups in my desired position?

    ReplyDelete
  21. Need a clarification, both the script (Obstaclescript and PowerupScript) works fine when i crate it under prefabs folder. When i create the same script under script folder and tagged it to corresponding prefabs its doesnt work. only first two object created dynamically moves towards the player, rest of the objects are created statically far away from the player and it doesnt move! Please help me to understand it!! thnx in advance!

    ReplyDelete
  22. I want to spawn objects more far, how can I do it?

    ReplyDelete
  23. Hi i have a problem ...i followed your tutorial step by step I even had to re create another scene to check if I'm doing itright the snags spawn but they don't come to my player they ar stagnant while spawning.........any solutions

    ReplyDelete
  24. Awesome article, I am a big fan of this website, keep on posting that great content, and I'll be a regular visitor for a long time...looking for the next one....keep it up! blossom blast saga for pc

    ReplyDelete