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
1
Question by eddieion · Apr 26, 2016 at 04:25 AM · unity 5enemysetactivedeath

.SetActive (false) deletes gameObject but it's effects still affect the player

Hey guys,

I'm having trouble with .SetActive (false) to disable some instances of game objects.

I was following the Roguelike Unity tutorial (whilst making tweaks for myself) and realised that when using .SetActive (false) to delete enemies they were still having an effect on the player (dealing damage whenever the player went to the point where they 'died') even though they sprites vanished as i'd expect them to. I really don't know what the issue is...

If anyone can point me in the right direction or explain why I might be getting the results i'm getting i'd really appreciate it. I've spent a long time trying to figure it out but to no avail, but I am very new to Unity and script in general.

Enemy.cs

     using UnityEngine;
     using System.Collections;
     
     namespace Completed
     {
         //Enemy inherits from MovingObject, our base class for objects that can move, Player also inherits from this.
         public class Enemy : MovingObject
         {
             public int playerDamage;                              //The amount of HULL POINTS to subtract from the player when attacking.
             //public int fuelLoss;                                //Amount of fuel to subtract from player when attacked.
             
             private Animator animator;                          //Variable of type Animator to store a reference to the enemy's Animator component.
             private Tra
 
 nsform target;                           //Transform to attempt to move toward each turn.
         private bool skipMove;                              //Boolean to determine whether or not enemy should skip a turn or move this turn.
         
         //Start overrides the virtual Start function of the base class.
         protected override void Start ()
         {
             //Register this enemy with our instance of GameManager by adding it to a list of Enemy objects. 
             //This allows the GameManager to issue movement commands.
 
             GameManager.instance.AddEnemyToList (this);
             
             //Find the Player GameObject using it's tag and store a reference to its transform component.
             target = GameObject.FindGameObjectWithTag ("Player").transform;
             
             //Call the start function of our base class MovingObject.
             base.Start ();
         }
 
         
         //Override the AttemptMove function of MovingObject to include functionality needed for Enemy to skip turns.
         //See comments in MovingObject for more on how base AttemptMove function works.
         protected override void AttemptMove <T> (int xDir, int yDir)
         {
             //Check if skipMove is true, if so set it to false and skip this turn.
             if(skipMove)
             {
                 skipMove = false;
                 return;
                 
             }
             
             //Call the AttemptMove function from MovingObject.
             base.AttemptMove <T> (xDir, yDir);
             
             //Now that Enemy has moved, set skipMove to true to skip next move.
             skipMove = true;
         }
         
         
         //MoveEnemy is called by the GameManger each turn to tell each Enemy to try to move towards the player.
         public void MoveEnemy ()
         {
             //Declare variables for X and Y axis move directions, these range from -1 to 1.
             //These values allow us to choose between the cardinal directions: up, down, left and right.
             int xDir = 0;
             int yDir = 0;
             
             //If the difference in positions is approximately zero (Epsilon) do the following:
             if(Mathf.Abs (target.position.x - transform.position.x) < float.Epsilon)
                 
                 //If the y coordinate of the target's (player) position is greater than the y coordinate of this enemy's position set y direction 1 (to move up). If not, set it to -1 (to move down).
                 yDir = target.position.y > transform.position.y ? 1 : -1;
             
             //If the difference in positions is not approximately zero (Epsilon) do the following:
             else
                 //Check if target x position is greater than enemy's x position, if so set x direction to 1 (move right), if not set to -1 (move left).
                 xDir = target.position.x > transform.position.x ? 1 : -1;
             
             //Call the AttemptMove function and pass in the generic parameter Player, because Enemy is moving and expecting to potentially encounter a Player
             AttemptMove <Player> (xDir, yDir);
         }
 
 
         //OnCantMove is called if Enemy attempts to move into a space occupied by a Player, it overrides the OnCantMove function of MovingObject 
         //and takes a generic parameter T which we use to pass in the component we expect to encounter, in this case Player
         protected override void OnCantMove <T> (T component)
         {
             //Declare hitPlayer and set it to equal the encountered component.
             Player hitPlayer = component as Player;
 
             //Call the LoseHullPoints function of hitPlayer passing it playerDamage, the amount of hull points to be subtracted.
             hitPlayer.LoseHullPoints (playerDamage);
 
             //Disable the gameObject.
             gameObject.SetActive (false);
         }
 
             
         }
     }

MovingObject.cs

 using UnityEngine;
 using System.Collections;
 
 namespace Completed
 {
     //The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
     public abstract class MovingObject : MonoBehaviour
     {
         public float moveTime = 0.1f;           //Time it will take object to move, in seconds.
         public LayerMask blockingLayer;         //Layer on which collision will be checked.
         
         
         private BoxCollider2D boxCollider;      //The BoxCollider2D component attached to this object.
         private Rigidbody2D rb2D;               //The Rigidbody2D component attached to this object.
         private float inverseMoveTime;          //Used to make movement more efficient.
         
         
         //Protected, virtual functions can be overridden by inheriting classes.
         protected virtual void Start ()
         {
             //Get a component reference to this object's BoxCollider2D
             boxCollider = GetComponent <BoxCollider2D> ();
             
             //Get a component reference to this object's Rigidbody2D
             rb2D = GetComponent <Rigidbody2D> ();
             
             //By storing the reciprocal of the move time we can use it by multiplying instead of dividing, this is more efficient.
             inverseMoveTime = 1f / moveTime;
         }
         
         
         //Move returns true if it is able to move and false if not. 
         //Move takes parameters for x direction, y direction and a RaycastHit2D to check collision.
         protected bool Move (int xDir, int yDir, out RaycastHit2D hit)
         {
             //Store start position to move from, based on objects current transform position.
             Vector2 start = transform.position;
             
             // Calculate end position based on the direction parameters passed in when calling Move.
             Vector2 end = start + new Vector2 (xDir, yDir);
             
             //Disable the boxCollider so that linecast doesn't hit this object's own collider.
             boxCollider.enabled = false;
             
             //Cast a line from start point to end point checking collision on blockingLayer.
             hit = Physics2D.Linecast (start, end, blockingLayer);
             
             //Re-enable boxCollider after linecast
             boxCollider.enabled = true;
             
             //Check if anything was hit
             if(hit.transform == null)
             {
                 //If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
                 StartCoroutine (SmoothMovement (end));
                 
                 //Return true to say that Move was successful
                 return true;
             }
             
             //If something was hit, return false, Move was unsuccesful.
             return false;
         }
         
         
         //Co-routine for moving units from one space to next, takes a parameter end to specify where to move to.
         protected IEnumerator SmoothMovement (Vector3 end)
         {
             //Calculate the remaining distance to move based on the square magnitude of the difference between current position and end parameter. 
             //Square magnitude is used instead of magnitude because it's computationally cheaper.
             float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
             
             //While that distance is greater than a very small amount (Epsilon, almost zero):
             while(sqrRemainingDistance > float.Epsilon)
             {
                 //Find a new position proportionally closer to the end, based on the moveTime
                 Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
                 
                 //Call MovePosition on attached Rigidbody2D and move it to the calculated position.
                 rb2D.MovePosition (newPostion);
                 
                 //Recalculate the remaining distance after moving.
                 sqrRemainingDistance = (transform.position - end).sqrMagnitude;
                 
                 //Return and loop until sqrRemainingDistance is close enough to zero to end the function
                 yield return null;
             }
         }
         
         
         //The virtual keyword means AttemptMove can be overridden by inheriting classes using the override keyword.
         //AttemptMove takes a generic parameter T to specify the type of component we expect our unit to interact with if blocked (Player for Enemies, Wall for Player).
         protected virtual void AttemptMove <T> (int xDir, int yDir)
             where T : Component
         {
             //Hit will store whatever our linecast hits when Move is called.
             RaycastHit2D hit;
             
             //Set canMove to true if Move was successful, false if failed.
             bool canMove = Move (xDir, yDir, out hit);
             
             //Check if nothing was hit by linecast
             if(hit.transform == null)
                 //If nothing was hit, return and don't execute further code.
                 return;
             
             //Get a component reference to the component of type T attached to the object that was hit
             T hitComponent = hit.transform.GetComponent <T> ();
             
             //If canMove is false and hitComponent is not equal to null, meaning MovingObject is blocked and has hit something it can interact with.
             if(!canMove && hitComponent != null)
                 
                 //Call the OnCantMove function and pass it hitComponent as a parameter.
                 OnCantMove (hitComponent);
         }
         
         
         //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation.
         //OnCantMove will be overriden by functions in the inheriting classes.
         protected abstract void OnCantMove <T> (T component)
             where T : Component;
     }
 }
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

0 Replies

· Add your reply
  • Sort: 

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Audio Issue, Plays with PlayOneShot but not Play 0 Answers

Help with attacking, and death animation. Unity 5 javascript 1 Answer

How to change float animator parameters on an NPC object? 0 Answers

How to check if a enemy is moving up or down? 1 Answer

Array SetActive C# Unity 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