Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 Drakkith · Jun 27, 2017 at 04:48 AM · collisionvariablesinstatiate

Checking to See if the Player is Invincible on Collision

Hey all.

I've just completed the space shooter tutorial and I've started to try to add a few things. I'd like to add a feature where the ship can "dash" through projectiles and objects without being destroyed. Unfortunately I'm not sure how to do this. My first thought was to add a bool "invincible" variable on the playerController class that I would just toggle on when the player is dashing and then off after the dash ends. This would be checked inside the destroyOnContact script when the player collided with anything.

However, I don't know how to code this in since the playerController is not instantiated until the game starts.

Any ideas?

Edit: The following is the collision code from the tutorial.

 using UnityEngine;
 using System.Collections;
 
 public class DestroyByContact : MonoBehaviour {
     public GameObject explosion;
     public GameObject playerExplosion;
     public int scoreValue;
     private GameController gameController;
     
 
     void Start()
     {
         GameObject gameControllerObject = GameObject.FindWithTag("GameController");
         if (gameControllerObject != null)
         {
             gameController = gameControllerObject.GetComponent<GameController>();
         }
         if (gameController == null)
         {
             Debug.Log("Cannot find 'GameController' script");
         }
         
         
     }
 
     void OnTriggerEnter(Collider other)
     {
         
         if (other.tag == "Boundary")
         {
             return;
         }
 
         Instantiate(explosion, transform.position, transform.rotation);
 
         if (other.tag == "Player")
         {
  
             Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
             gameController.GameOver();
         }
         gameController.AddScore(scoreValue);
         Destroy(other.gameObject);
         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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by justinc847 · Jun 29, 2017 at 03:48 AM

Awesome, so to answer your question about passing variable values between scripts, I can see you are already doing that, but you are calling functions instead. It is treated the same way. In your current script you are calling gameover and addscore from the gamecontroller script. Here is an example

 public GameObject variableName;
 /* this variable will be the gameobject that holds the other script in a script component, also notice how we declared it GameObject, this is a class, also known as a 'Type' in unity. You will see that unity objects and components are just classes that you can access by using the various namespaces throughout unity. (For example, all of the UI elements have there own class, but are all tied together via the UnityEngine.UI namespace, which is called with the 'using' keyword at the top of a C# script. Once you realize it is structured this way, you realize you can actually create your own classes. The reason I'm pointing this out, is because not only can you create your own classes, but you DO, every time you make a new script. keep this is mind */
 
 public MyScriptName variableName2;
 /* this is why I pointed this out previously. you'll notice instead of calling this a gameobject or transform or any other thing, is because whatever you named your script is now its own class! pretty cool eh? So check this next thing out */
 
 public static numberVariable;
 /* this is the variable we want to access from the other script. Notice we are using the static keyword. Let me explain this. There are two ways to pass a variable between scripts, and I am illustrating both. This 'static' way of doing things requires less code, but you can't always use it, because declaring something as static means you can't change it. The reason I have illustrated the first two, is because if you have a variable that is NOT static that you need to share with another script, you will have to reference the gameobject that holds the script. Keep this stuff in mind, but lets move on */
 
 private int numberVariableNotStatic;
 /* here we are doing the dynamic variable, which is why we referenced the gameobject in the beginning */
 
 void Start() {
      variableName2 = GameObject.GetComponent<MyScriptName>();
      numberVariableNotStatic = MyScriptName.numberVariableInScript;
 
 /* if we did it the static way, we would just have to do the second line. EDIT: I wanted to add this after posting, keep in mind that when you do this with your invincible boolean, you wont put that second line in the start function, rather you would do it in the oncollision before the if statements, or in the update function if you wanted to play animations with it so the player would swerve without having to hit an asteroid first, but where you put it depends on if you swerve or go through the asteroid, and I elaborate on this later. But in either situation, you will not place that line in start, because that value will change after the game starts. I just put it there for demonstrative purposes. END EDIT */
 }

I hope I've cleared some of that up and didn't give you any inaccurate information. But you would use that for the invincible bool. You could add a new script to the player and do player values and such, and then pass the bool to the asteroid script to check the collision. Like so

 if (other.tag == "Player" && !invincible)
          {
 
              Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
              gameController.GameOver();
          }
 
 /* invincible is the name of the bool. Putting an exclamation mark in front of it means it is false. So we are saying "If the object this asteroid collides with is the player, and the invincible boolean is false (meaning the player is not invincible), then execute the explosion instantiation and then call the gameover function.

Now that you can check if the player is invincible or not, you can look into to doing the "Dash" thing you were talking about. I can't see the game, and I've honestly never done the tutorial so I really have no idea what you mean, but I imagine you just mean the player speeding up and dodging asteroids. If so, then all of that can be done like so

 void Update() {
     if(invincible) {
         //do dash stuff here, animations, etc.
        /* notice no exclamation mark, this means if invincible is true, so now we are saying "if we are invincible, do this". And this would need to be done in your update function, so that the game checks if you are invincible every frame, and it does not get stuck on the other side of your collision if statement, because that would cause a ton of unintended issues. */
     }
 }

Now with the actual dash, I feel like you may be imagining the player automatically swerving through asteroids at high speeds. There are number of ways you could do this, but I warn you, they are all pretty complex. It would be much easier to keep the player going straight and just have the asteroids get destroyed but not the player. You could do that by throwing on an "else if" on the original if statement, and put in the condition that the tag is player and invincible is true, and then tell it to destroy asteroids but do not call the gameover function and you would be set. If you want it get really fancy and swerve through asteroids though, you are looking at pretty complex little project, ESPECIALLY if your asteroids are randomized. We'd be talking something along the lines of "procedural generation" at that point. Not to mention the complex animation system behind it. I honestly wouldn't be able to help much do to the complexity, but I can for sure point you in the right direction. Unity has a ton of tutorials on it's animation system and procedural generation. BTW, "Procedural Generation" is a fancy way of saying "Instantiate these things randomly, but base them on a rule system". Think minecraft, like how bedrock can only generate at the bottom of the map, even though all the generation is random. I hope I've helped and was able to answer all your questions. Good luck with your project, and if you do decide to do all the animations and swerving and randomize and what nought, let me know. That would be pretty cool to check out a one man operation like that. Have a good day!

Comment
Add comment · Show 4 · 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 Drakkith · Jun 29, 2017 at 07:05 AM 0
Share

Thanks Justinc847.

I haven't been able to implement the rest of the code to test it all, but I've stopped getting errors by using this code:

  private PlayerController playerController; 
 //above variable is up in top of the class. 
   if (other.tag == "Player")
     {
             GameObject playerControllerObject = GameObject.FindWithTag("PlayerController");
             playerController = playerControllerObject.GetComponent<PlayerController>();
 
             if (playerController.invincible == false)
             {
                 Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
                 gameController.GameOver();
             }
     }
avatar image Drakkith · Jun 29, 2017 at 07:15 AM 0
Share

I think my main mistake earlier was that I was trying to do something like:

GameObject playerControllerObject = GameObject.FindWithTag("Player");

And then trying to find the playerController through that somehow, which wasn't working.

avatar image justinc847 Drakkith · Jun 29, 2017 at 02:41 PM 1
Share

Oh ok. As long as the playecontroller script is attached to the player object tho that should work. You just have to make sure you are calling the component. What you have right will work if you havent tested it. Well it will work as long as you have an object tagged as player controller and then that object holds the script.But anyway, glad I could help!

avatar image Drakkith justinc847 · Jul 02, 2017 at 06:35 AM 0
Share

Well, that's not working and I have no idea why. If I use what I wrote above then neither the player's ship nor the asteroids are destroyed, regardless of whether the player is "dashing" or not. This is unbelievably frustrating. I've spent hours trying to figure this stuff out and I'm no closer to understanding anything about how unity script works.

Ins$$anonymous$$d of creating a whole new comment with a large code box, I went ahead and made a thread on the forums: https://forum.unity3d.com/threads/finding-a-script-attached-to-a-game-object.481171/

avatar image
0

Answer by neosca · Jun 27, 2017 at 05:38 AM

First assign unique tags to your gameobjects(projectiles,etc.) than you can use Physics.IgnoreCollision.

https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html

for 2d Physics refer to: https://docs.unity3d.com/ScriptReference/Physics2D.IgnoreCollision.html

Example:

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class IgnoreCollision : MonoBehaviour {

 // Use this for initialization
 void Start ()
 {
         
 }
 
 // Update is called once per frame
 void Update ()
 {
     
 }

 void OnCollisionEnter (Collision coll)
 {
     if (coll.gameObject.CompareTag ("Object1")|| coll.gameObject.CompareTag ("Object2")) {
         Physics.IgnoreCollision (coll.gameObject.GetComponent<Collider> (), GetComponent<Collider> ());
     }
 }

}

In the above example, you can replace "Object1" and "Object2" with tags of the gameObjects you wish to ignorecollision with.

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 Drakkith · Jun 28, 2017 at 11:20 PM 0
Share

Hi neosca, thanks for your reply.

I'm a bit of a newb when it comes to this stuff. I've taken a basic C program$$anonymous$$g class and tried to dabble a bit into C++ and C#, but most of this is still well over my head and I'm not sure what this code is doing. I'll dive into the manual and see if this makes sense after I read more on all the nuts and bolts of scripting in Unity.

Thanks again!

avatar image justinc847 · Jun 29, 2017 at 12:13 AM 0
Share

I don't see how instantiated the player controller will effect you in this specific scenario. The above answer seems a little unnecessary also, and wouldn't actually work in its current state. In the if statement posted above that compares object tags, you still need to check the invinsible boolean condition by adding

 if(coll.gameObject.CompareTag ("Object1")|| coll.gameObject.CompareTag ("Object2") && !invisibleBool)

But ins$$anonymous$$d of having a seperate script to manage this it seems alot easier to just do it in OnCollisionEnter function of your player controller using if (col.gameObject.name =="asteroid" && !invincible) { //get hit here}

avatar image Drakkith justinc847 · Jun 29, 2017 at 12:25 AM 0
Share

The space shooter tutorial puts the collision checks on the asteroids, not the player. I suppose I could try to put a collision checker on the player, but I'd still like to know how to check a variable on an instance of another class.

avatar image justinc847 Drakkith · Jun 29, 2017 at 12:46 AM 0
Share

Oh ok. So the original answer may be better as far as being its own class. But so your question more so comes down to passing a variable between different scripts?

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

102 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 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 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 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 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

How do I get an object to send a value to a manager script using an ontriggerenter? 1 Answer

Adding varibales from other scripts 3 Answers

onCollisionEnter2d spawn - unity 4.6 0 Answers

Take health from enemy 3 Answers

How to instantiate an object with scripts? 1 Answer


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