• 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 Bonkahe · Sep 30, 2013 at 06:56 PM · zombie

Melee Weapon Collision addjust health

Hey guys, its probably pretty simple, I have a zombie, a player, and when I click an animation plays swinging the machete, I want the machete to when colliding with the zombie addjust its health by -100 ie killing it.

Player Script (Dont think you need this but its for reference. using UnityEngine; using System.Collections;

 // Require these components when using this script
 [RequireComponent(typeof (Animator))]
 [RequireComponent(typeof (CapsuleCollider))]
 [RequireComponent(typeof (Rigidbody))]
 public class JeffControl : MonoBehaviour
 {
     [System.NonSerialized]                    
     public float lookWeight;                    // the amount to transition when using head look
     
     [System.NonSerialized]
     public Transform enemy;                        // a transform to Lerp the camera to during head look
     
     public float animSpeed = 1.5f;                // a public setting for overall animator animation speed
     public float lookSmoother = 3f;                // a smoothing setting for camera motion
     public bool useCurves;                        // a setting for teaching purposes to show use of curves
     
     public int maxhealth = 100;
     public int curhealth = 100;
     public float healthbarlength;
     
 
     private Animator anim;                            // a reference to the animator on the character
     private AnimatorStateInfo currentBaseState;            // a reference to the current state of the animator, used for base layer
     private AnimatorStateInfo layer2CurrentState;    // a reference to the current state of the animator, used for layer 2
     private CapsuleCollider col;                    // a reference to the capsule collider of the character
     
     
     static int locoState = Animator.StringToHash("Base Layer.Locomotion");            // these integers are references to our animator's states
     static int jumpState = Animator.StringToHash("Base Layer.Jump");                // and are used to check state for various actions to occur
     static int jumpDownState = Animator.StringToHash("Base Layer.JumpDown");        // within our FixedUpdate() function below
     static int fallState = Animator.StringToHash("Base Layer.Fall");
     static int rollState = Animator.StringToHash("Base Layer.Roll");
     static int attackState = Animator.StringToHash("Layer2.Attack");
     
 
     void Start ()
     {
         // initialising reference variables
         healthbarlength = Screen.width / 2;
         anim = GetComponent<Animator>();                      
         col = GetComponent<CapsuleCollider>();                
     }
     
     
     void FixedUpdate ()
     {
         AddjustCurrentHealth(0);
         float h = Input.GetAxis("Horizontal");                // setup h variable as our horizontal input axis
         float v = Input.GetAxis("Vertical");                // setup v variables as our vertical input axis
         anim.SetFloat("Speed", v);                            // set our animator's float parameter 'Speed' equal to the vertical input axis                
         anim.SetFloat("Direction", h);                         // set our animator's float parameter 'Direction' equal to the horizontal input axis        
         anim.speed = animSpeed;                                // set the speed of our animator to the public variable 'animSpeed'
         anim.SetLookAtWeight(lookWeight);                    // set the Look At Weight - amount to use look at IK vs using the head's animation
         currentBaseState = anim.GetCurrentAnimatorStateInfo(0);    // set our currentState variable to the current state of the Base Layer (0) of animation
         
         if(anim.layerCount ==2)        
             layer2CurrentState = anim.GetCurrentAnimatorStateInfo(1);    // set our layer2CurrentState variable to the current state of the second Layer (1) of animation
         
         // STANDARD JUMPING
         
         // if we are currently in a state called Locomotion (see line 25), then allow Jump input (Space) to set the Jump bool parameter in the Animator to true
         if (currentBaseState.nameHash == locoState)
         {
             if(Input.GetButtonDown("Jump"))
             {
                 anim.SetBool("Jump", true);
             }
         }
         
         // if we are in the jumping state... 
         else if(currentBaseState.nameHash == jumpState)
         {
             //  ..and not still in transition..
             if(!anim.IsInTransition(0))
             {
                 if(useCurves)
                     // ..set the collider height to a float curve in the clip called ColliderHeight
                     col.height = anim.GetFloat("ColliderHeight");
                 
                 // reset the Jump bool so we can jump again, and so that the state does not loop 
                 anim.SetBool("Jump", false);
             }
             
             // Raycast down from the center of the character.. 
             Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up);
             RaycastHit hitInfo = new RaycastHit();
             
             if (Physics.Raycast(ray, out hitInfo))
             {
                 // ..if distance to the ground is more than 1.75, use Match Target
                 if (hitInfo.distance > 1.75f)
                 {
                     
                     // MatchTarget allows us to take over animation and smoothly transition our character towards a location - the hit point from the ray.
                     // Here we're telling the Root of the character to only be influenced on the Y axis (MatchTargetWeightMask) and only occur between 0.35 and 0.5
                     // of the timeline of our animation clip
                     anim.MatchTarget(hitInfo.point, Quaternion.identity, AvatarTarget.Root, new MatchTargetWeightMask(new Vector3(0, 1, 0), 0), 0.35f, 0.5f);
                 }
             }
         }
             
         // JUMP DOWN AND ROLL 
         
         // if we are jumping down, set our Collider's Y position to the float curve from the animation clip - 
         // this is a slight lowering so that the collider hits the floor as the character extends his legs
         else if (currentBaseState.nameHash == jumpDownState)
         {
             col.center = new Vector3(0, anim.GetFloat("ColliderY"), 0);
         }
         
         // if we are falling, set our Grounded boolean to true when our character's root 
         // position is less that 0.6, this allows us to transition from fall into roll and run
         // we then set the Collider's Height equal to the float curve from the animation clip
         else if (currentBaseState.nameHash == fallState)
         {
             col.height = anim.GetFloat("ColliderHeight");
         }
         
         // if we are in the roll state and not in transition, set Collider Height to the float curve from the animation clip 
         // this ensures we are in a short spherical capsule height during the roll, so we can smash through the lower
         // boxes, and then extends the collider as we come out of the roll
         // we also moderate the Y position of the collider using another of these curves on line 128
         else if (currentBaseState.nameHash == rollState)
         {
             if(!anim.IsInTransition(0))
             {
                 if(useCurves)
                     col.height = anim.GetFloat("ColliderHeight");
                 
                 col.center = new Vector3(0, anim.GetFloat("ColliderY"), 0);
                 
             }
         }
         // ATTACK
         
         if(Input.GetMouseButtonUp(0))
         {
             anim.SetBool("Attack", true);
         }
         // if we enter the attacking state, reset the bool to let us attack again in future
         if(layer2CurrentState.nameHash == attackState)
         {
             anim.SetBool("Attack", false);
         }
     }
     
     // HEALTH SYSTEM
     
     void OnGUI () {
         GUI.Box(new Rect(10, 10, healthbarlength, 20), curhealth + "/" + maxhealth);
     }
     public void AddjustCurrentHealth(int adj) {
         curhealth += adj;
         
         if(curhealth < 0)
             curhealth = 0;
         
         if(curhealth > maxhealth)
             curhealth = maxhealth;
         
         if(maxhealth < 1)
             maxhealth = 1;
         
         healthbarlength = (Screen.width / 2) * (curhealth / (float)maxhealth);
     }
 }
 


Machete Script using UnityEngine; using System.Collections;

 public class MacheteContol : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
     
     }
     
     public void OnCollisionEnter(collision Collision) 
     {
         EnemyHealth eh = (EnemyHealth)collision.getcomponent("ZombieControl");
         eh.AddjustCurrentHealth(-100);
     }
 }


And of course zombie script

 using System.Collections;
 
 public class ZombieControl : MonoBehaviour {
     
     public int maxhealth = 100;
     public int curhealth = 100;
 //    public float healthbarlength;
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void FixedUpdate () {
         AddjustCurrentHealth(0);
     }
     
     // Health System
     
         void OnGUI () {
 //        GUI.Box(new Rect(10, 10, healthbarlength, 20), curhealth + "/" + maxhealth);
     }
     public void AddjustCurrentHealth(int adj) {
         curhealth += adj;
         
         if(curhealth < 0)
             curhealth = 0;
         
         if(curhealth > maxhealth)
             curhealth = maxhealth;
         
         if(maxhealth < 1)
             maxhealth = 1;
         
         if(curhealth == 0)
         {
             Destroy(gameObject);
         }
     }
 }


I'm getting an error that says: Assets/Scripts/MacheteContol.cs(16,38): error CS0246: The type or namespace name `collision' could not be found. Are you missing a using directive or an assembly reference?

However with a bit of fiddiling I can get this error to go away, that's not the problem, basically the script is broken, and I don't know how to fix it.

FOR REFERENCE: the machete collision is set as trigger.

Comment
Add comment · Show 15
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 hamstar · Sep 30, 2013 at 07:49 PM 0
Share

Firstly it needs to be OnCollisionEnter(Collision collision). Note capital C in class/type name. Any more errors after that?

avatar image hamstar · Sep 30, 2013 at 08:03 PM 0
Share

Also, method names are case sensitive. getcomponent should be GetComponent. Why are you casting to EnemyHealth when the component you are trying to retrieve is of type "ZombieControl"?

avatar image Bonkahe · Sep 30, 2013 at 08:18 PM 0
Share

$$anonymous$$y bad about the Enemy Health, that was just what it used to be called here's the new code:

using UnityEngine; using System.Collections;

 public class $$anonymous$$acheteControl : $$anonymous$$onoBehaviour {
     
  public void OnCollisionEnter(Collision collision)
 {
     ZombieControl eh = (ZombieControl)collision.GetComponent("ZombieControl");
         eh.AddjustCurrentHealth(-100);
     }
 }


And of course I got a new error:

 Assets/Scripts/$$anonymous$$acheteContol.cs(8,53): error CS1061: Type `UnityEngine.Collision' does not contain a definition for `GetComponent' and no extension method `GetComponent' of type `UnityEngine.Collision' could be found (are you missing a using directive or an assembly reference?)
 

Thoughts?

avatar image hamstar · Sep 30, 2013 at 08:22 PM 0
Share

The compiler is telling you that Collision does not have a GetComponent method. But we know that GameObject does, and collision has a reference to the GameObject collided with. Try (ZombieControl)collision.gameObject.GetComponent();

avatar image Bonkahe · Sep 30, 2013 at 08:29 PM 0
Share
 using UnityEngine;
 using System.Collections;
 
 public class $$anonymous$$acheteControl : $$anonymous$$onoBehaviour {
     
  public void OnCollisionEnter(Collision collision)
 {
     ZombieControl eh = (ZombieControl)collision.gameObject.GetComponent("ZombieControl");
         eh.AddjustCurrentHealth(-100);
     }
 }


Ok so that brought no errors, but when the machete passes through the object nothing happeneds, it seems like the command to addjustcurrenthealth is being lost, btw thanks allot for taking the time to help me.

Show more comments

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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

16 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

Related Questions

Ai Zombie Melee Attack script. 5 Answers

javascrpit ischasing error 1 Answer

Making projectiles disappear when they hit the ground 2 Answers

Hunger system help - Money to be made 0 Answers

how is it possible to make a sound based spawning system? 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges