Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Dogg · May 04, 2014 at 01:27 AM · power-up

Powerup Script to make player invincible?

Title says it all. I simply want to make my player invincible after getting a powerup for a short period of time, so he can't die from touching the objects that kill him instantly. I tried to look this up on the answered questions that were asked a while back and I could not find someone who asked this question except one guy. It was in java script so it's like a whole other language to me, also his script gives his player a health bar(which mine doesn't have, I'm making an infinite runner). Anyways since this is in the answers section I don't want to make a big discussion out of it, so let's be direct please or I'll get in trouble. Here's my basic powerup script:

public class PowerupScript : MonoBehaviour {

     void OnTriggerEnter2D(Collider2D other)
     {
        if (other.tag == "Player"){
          Destroy (gameObject);
        }
  
        {
  
       }
   }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by AlucardJay · May 04, 2014 at 02:24 AM

This is basically a write-my-code question, which is impossible to answer without knowing how your health system works. So a pseudo-solution would be :

  • when the player hits the power-up, call a function on the player to set invincible

  • that function would set a boolean to true, and invoke a function to set that boolean back to false after a delay

  • in the health part, before deducting health there would be a check to see if the boolean is true; if not, then deduct health.

Power-up script

 player.SetInvincible();

Player script

 public float invincibleTime = 3.0f;
 bool isInvincible = false;
 
 public void SetInvincible()
 {
     isInvincible = true;
     
     CancelInvoke( "SetDamageable" ); // in case the method has already been invoked
     Invoke( "SetDamageable", invincibleTime );
 }
 
 void SetDamageable()
 {
     isInvincible = false;
 }
 
 // health part
 if ( !isInvincible )
 {
     health -= whatever;
 }
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Dogg · May 04, 2014 at 04:30 AM 0
Share

Sorry, I wasn't clear on my health system and how it works. $$anonymous$$y player doesn't have health, he can't die unless he touches one of the many objects spawning in front of him. Again I'm making an infinite runner, so think games like flappy bird or other endless games to where I can't die unless I touch one of the objects. I want to make my player invurnable to death and be able to pass through the objects. So now that's clear, thank you for the script but I have one error in the powerup script. Here it is:

 An object reference is required to access non-static member `ControllerScript.SetInvincible()'

Here's my new powerup script:

 public class PowerupScript : $$anonymous$$onoBehaviour {
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.tag == "Player"){
             ControllerScript.SetInvincible();
             ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>(); // not sure about the syntax here...
             if (playerScript)
             {
                 // We speed up the player and then tell to stop after a few seconds
                 playerScript.coeffSpeedUp = 1.5f;
                 StartCoroutine(playerScript.StopSpeedUp());
 
             }
             Destroy (gameObject);
         }
     }
  }

And my new Player Script:

 public class ControllerScript : $$anonymous$$onoBehaviour
 {
     public float maxSpeed = 10f;
     bool facingRight = true;
     public float coeffSpeedUp = 1.0f;
     public float invincibleTime = 3.0f;
     bool isInvincible = false;
 
     Animator anim;
 
     bool grounded = false;
     public Transform groundCheck;
     float groundRadius = 0.2f;
     public Layer$$anonymous$$ask whatIsGround;
     public float jumpForce = 700f;
 
     public void SetInvincible()
     {
                 isInvincible = true;
 
                 CancelInvoke ("SetDamageable"); // in case the method has already been invoked
                 Invoke ("SetDamageable", invincibleTime);
         }
 
     void SetDamageable()
     {
                 isInvincible = false;
         }
 
     // Use this for initialization
     void Start () 
     {
         anim = GetComponent<Animator>();
     }
     
     // Update is called once per frame
     void FixedUpdate () 
     {
 
                 transform.Translate (5f * Time.deltaTime, 0f, 0f);
 
                 grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
                 anim.SetBool ("Ground", grounded);
 
                 anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
 
 
                 if (!grounded)
                         return;
                         
                 float move = Input.GetAxis ("Horizontal");
 
                 //anim.SetFloat ("Speed", $$anonymous$$athf.Abs(move));
 
                 //rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
 
     }
 
     void Update()
     {
 
         if (grounded && Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space)) 
         {
             anim.SetBool("Ground", false);
             rigidbody2D.AddForce(new Vector2(0, jumpForce));
 
         }
     }
 
     public IEnumerator StopSpeedUp() {
         yield return new WaitForSeconds(1.5f); // the number corresponds to the number of seconds the speed up will be applied
         coeffSpeedUp = 1.0f; // back to normal
     }
 }
 
avatar image AlucardJay · May 04, 2014 at 04:55 AM 0
Share

The error is because you are trying to call the function before you have stored the component. Line 6 should be at line 10, after you store a reference to the component and can access it. Portion of the power-up script should look like this :

 if (other.tag == "Player"){
     ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>();
     if (playerScript)
     {
         playerScript.SetInvincible(); // call function on playerScript to set player to invincible
         // speed up coroutine, etc as you have it already

The rest depends on how your 'enemy' item affects the player. Now you have a boolean on the player that shows if it is invincible or not. However, to access this boolean from other scripts, it will need to be made public (public bool isInvincible).

So if your 'enemy' script is set up the same way, just check if the player is invincible before killing the player/moving to respawn position/etc

 if (other.tag == "Player"){
     ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>();
     if (playerScript)
     {
         // check if NOT invincible
         if ( !playerScript.isInvincible )
         {
             // explode player
             // set to respawn
             // other death-type stuff
         }
avatar image Dogg · May 04, 2014 at 06:03 AM 0
Share

Alright the scripts are error free, but it doesn't work sadly. $$anonymous$$aybe it's because I don't quite understand what you mean by 'enemy' script. I'm assu$$anonymous$$g you mean the obstacles in my way that kill me. I have a OnCollisionEnter2D script that I attached to my player to kill the player when he touches any of the obstacles. As for my obstacles I only have 1 script which is a spawn script. So I don't understand. Here's my Collision script:

 public class OnCollisionEnter : $$anonymous$$onoBehaviour {
 
 
     void Update() {
         
     }
         
 
     void OnCollisionEnter2D (Collision2D col)
         {
             // If the colliding gameobject is an Enemy...
             if(col.gameObject.tag == "Dangerous")
             {
                 
                 // Find all of the colliders on the gameobject and set them all to be triggers.
                 Collider2D[] cols = GetComponents<Collider2D>();
                 foreach(Collider2D c in cols)
                 {
                     c.isTrigger = true;                                                                                                                   
                 }
                 
                 // ... disable user Player Control script
                 GetComponent<ControllerScript>().enabled = false;
         }
     }
 }

And my new updated powerup script(thanks to you):

 public class PowerupScript : $$anonymous$$onoBehaviour {
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.tag == "Player"){
             ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>(); // not sure about the syntax here...
             if (playerScript)
             {
                 playerScript.SetInvincible(); // call function on playerScript to set player to invincible
                 // speed up coroutine, etc as you have it already
 
                 // check if NOT invincible
                 if ( !playerScript.isInvincible )
                 {
                     // explode player
                     // set to respawn
                     // other death-type stuff
 
                 // We speed up the player and then tell to stop after a few seconds
                 playerScript.coeffSpeedUp = 1.5f;
                 StartCoroutine(playerScript.StopSpeedUp());
 
             }
             Destroy (gameObject);
         }
     }
  }
 }

By the way I made my bool isInvincible to public.

avatar image AlucardJay · May 04, 2014 at 06:27 AM 0
Share

Ok, I think I confused you in that last comment.

PowerUp Script

  • is attached to PowerUp object

  • is a trigger collider

  • finds the player script, and sets it to invincible

.

 public class PowerupScript : $$anonymous$$onoBehaviour {
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.tag == "Player"){
             ControllerScript playerScript = other.gameObject.GetComponent<ControllerScript>();
             if (playerScript)
             {
                 // call function on playerScript to set player to invincible
                 playerScript.SetInvincible(); 
                 // We speed up the player and then tell to stop after a few seconds
                 playerScript.coeffSpeedUp = 1.5f;
                 StartCoroutine(playerScript.StopSpeedUp());
             }
             Destroy (gameObject);
         }
     }
 }


Player Controller Script

  • controls the player

  • has functions that are called to set player to invincible, and then damageable after a delay time

.

 public float invincibleTime = 3.0f;
 public bool isInvincible = false;
 
 public void SetInvincible()
 {
     isInvincible = true;
 
     CancelInvoke ("SetDamageable"); // in case the method has already been invoked
     Invoke ("SetDamageable", invincibleTime);
 }
 
 void SetDamageable()
 {
     isInvincible = false;
 }


Player Collision Script

  • checks if a player collided with a 'Dangerous' obstacle

  • if player is invincible, player takes no damage

.

 public class PlayerCollision : $$anonymous$$onoBehaviour {
 
     ControllerScript player;
     
     void Start()
     {
         player = GetComponent<ControllerScript>();
     }
     
     void OnCollisionEnter2D (Collision2D col)
     {
         // If the colliding gameobject is an Enemy...
         if(col.gameObject.tag == "Dangerous")
         {
             // Find all of the colliders on the gameobject and set them all to be triggers.
             Collider2D[] cols = GetComponents<Collider2D>();
             foreach(Collider2D c in cols)
             {
                 c.isTrigger = true;
             }
             
             // check if player is invincible
             if ( player.isInvincible )
             {
                 // keep on truckin'
             }
             else
             {
                 // ... disable user Player Control script
                 player.enabled = false;
             }
         }
     }
 }


I still don't quite understand your setup. If the Obstacle is just going to be set to trigger anyway, why not just use trigger colliders?

avatar image Dogg · May 04, 2014 at 07:02 AM 0
Share

The scripts aren't doing what I want them to do. It does finally affect the game but not in the way I want it to. For an example when I grab the powerup and I run into one of the obstacles in my way, I just fall through the floor like if I died, but the difference is that I fall slightly more forward then I did before(so that's how I know it affected the game). After I fall through the floor the destroyer that I placed on the bottom of the screen(it doesn't even need to be there, so don't think it has any relevance, I just haven't removed it yet) kills me and it then takes me to the game over screen(which is supposed to happen). I increased the time it takes for the invincibility to wear off but that didn't affect it at all. To answer your question about trigger colliders, I was taught to do what I do now you see. I watched many different Youtube tutorials from many different people(so the methods are all different). I know some methods aren't the best(the colliders for example) but that's all I know. I'll check out trigger colliders while waiting for your response and see if that works for me. Thanks again for the scripts btw.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Help! How can I get my power up script to work? 1 Answer

Animation spins wildly after completed 0 Answers

hide object start script 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges