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 JeevanjotSingh · Nov 16, 2014 at 08:54 PM · collisioncollide

Complication with script

Hi guys i got some problem . I need some simple help as a newbie . I am developing my first game and i need help that My player is a ball(like roll-a-ball tutorial player) and i want to assign that ball health . and i also have enemy who always follow my player and i want when i touch to my player and play decrease it's health by 5/10/15 i will give it the number .

Here is my player script :-

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour 
 {
     
     public int health = 100;
 
 
 }

and my enemy script :-

 using UnityEngine;
 using System.Collections;
 
 public class EnemyAI: MonoBehaviour 
 {
     public Transform target;
     public int moveSpeed;
     public int rotationSpeed;
 
     private Transform myTransform;
 
     public int damage = 5;
     public GameObject otherGameObject;
 
 
     private PlayerController playerScript;
 
     void Awake(){
         playerScript = otherGameObject.GetComponent<PlayerController>();
         myTransform = transform;
     }
     // Use this for initialization
     void Start () {
         GameObject go = GameObject.FindGameObjectWithTag("Player");
         target = go.transform;
     }
     // Update is called once per frame
     void Update () {
         Debug.DrawLine(target.position, myTransform.position, Color.cyan);
         //look at target
         
         //move towards target
 
         Vector3 directionTowardsPlayer = (target.position - myTransform.position).normalized;
         rigidbody.AddForce (directionTowardsPlayer * moveSpeed * Time.deltaTime);
 
 }
     void OnCollisionEnter(Collision col){
         if(col.transform.tag == "Player"){
 
             health -= damage;
         }
     }
 
 }






Comment
Add comment · Show 3
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 Eck · Nov 16, 2014 at 08:58 PM 0
Share

When describing your problem, it would be beneficial to explain what is happening (in addition to what you expect to happen). What problem are you seeing?

avatar image Linus · Nov 16, 2014 at 09:01 PM 0
Share

I agree, it was hard to see what you actually wanted help with. Still not 100% sure, but my answer should solve at least something for you. Also edited the question, the code was not properly formatted and hard to read.

avatar image JeevanjotSingh · Nov 17, 2014 at 10:39 AM 0
Share

yeh sorry i forget to describe the 'health is not existing component problem' sorry about that . But you got it . Thanks

2 Replies

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

Answer by Linus · Nov 16, 2014 at 08:58 PM

You need to get the health variable from the script through GetComponent.

 void OnCollisionEnter(Collision col)
 {
     if (col.transform.tag == "Player")
     {
         col.transform.GetComponent<PlayerController>().health -= damage; 
     }
 }

Comment
Add comment · Show 5 · 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 JeevanjotSingh · Nov 17, 2014 at 10:36 AM 0
Share

Thanks , it works . Now how can i decrease my power of player without each collision . $$anonymous$$eans on each collision of enemy to my player takes 5 damage but if it collides my player for long time then my power needs to be decrease on time that how much time it touch with my player . I know something like time.delata time but i am not clear with it . Can you please tell me how can i do that .

and one more thing . does i need to describe 'Getcomponent'each time .

avatar image Kiwasi · Nov 17, 2014 at 10:49 AM 0
Share

You can just do GetComponent once in start and store the result.

Also worth noting it might be better to call method rather then touch health directly. Will be much easier to maintain in the long run.

avatar image Linus · Nov 18, 2014 at 12:06 AM 0
Share

In many cases you want to have variable that is a reference to the component. But thought I would just solve the question the way the asker wanted to handle the problem.

You really should consider either b1gry4n's answer, or at least as Bored$$anonymous$$ormon suggests, having a method that handles the damage dealing. What if player suddenly looses health for no apparent reason when the project is bigger? Would be handy then to have a Debug.Log that shows all places in your code that deals damage.

Here is how I would have made the scripts today, assu$$anonymous$$g there is always just one PlayerController

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : $$anonymous$$onoBehaviour
 {
     public static PlayerController instance;
     public int health = 100;
 
     void Awake()
     {
         //Note that PlayerController.instance can only be called from other scripts
         //after Awake
         instance = this;
     }
 
     public void TakeDamage(int damage)
     {
         health -= damage;
 
         if (health < 1)
         {
             Debug.Log("Time do die.");
         }
     }
 }
 
 
 using UnityEngine;
 using System.Collections;
 
 public class EnemyAI : $$anonymous$$onoBehaviour
 {
     public Transform target;
     public int moveSpeed;
     public int rotationSpeed;
 
     private Transform myTransform;
     private Rigidbody myRigidbody;
 
     public int damage = 5;
     public GameObject otherGameObject;
 
 
     private PlayerController playerScript;
 
     void Awake()
     {
        // no need for playerscript PlayerController can now be accesed using PlayerController.instance
        // playerScript = otherGameObject.GetComponent<PlayerController>();
         myTransform = transform;
         myRigidbody = GetComponent<Rigidbody>();
     }
     // Use this for initialization
     void Start()
     {
         //GameObject go = PlayerController.instance.gameObject;
         target = PlayerController.instance.transform;
     }
     // Update is called once per frame
     void Update()
     {
         Debug.DrawLine(target.position, myTransform.position, Color.cyan);
         //look at target
 
         //move towards target
 
         Vector3 directionTowardsPlayer = (target.position - myTransform.position).normalized;
 
         //rigidbody does GetComponent<Rigidbody>() in the background. This will also give error in Unity 5
         //consider doing as you do with myTransform.
         myRigidbody.AddForce(directionTowardsPlayer * moveSpeed * Time.deltaTime);
 
     }
     void OnCollisionEnter(Collision col)
     {
         if (col.transform.tag == "Player")
         {
             PlayerController.instance.TakeDamage(damage);
         }
     }
 
 }



avatar image JeevanjotSingh · Nov 18, 2014 at 02:33 PM 0
Share

Thanks for the script .

But i got some errors . I want to destroy my player , i use this

using UnityEngine; using System.Collections;

public class PlayerController : $$anonymous$$onoBehaviour { public float speed; private int count; public GUIText countText; public GUIText winText; public int health = 100;

 void start()

{

     count = 0;
     SetCountText();
     winText.text = "";

}

 void FixedUpdate ()

 {
     float moveHorizontal = Input.GetAxis("Horizontal");
     float moveVertical = Input.GetAxis("Vertical");
     Vector3 movement = new Vector3(moveHorizontal,0.0f,moveVertical);

     rigidbody.AddForce (movement * speed * Time.deltaTime);
 

 }

void OnTriggerEnter(Collider other) {

     if(other.gameObject.tag ==    "PickUp")
         {
             other.gameObject.SetActive(false);
         count = count + 1;
         SetCountText();
         audio.Play();
         }
 }

void SetCountText() { countText.text="Count: " + count.ToString(); if (count >= 12) { winText.text = "YOU WIN!"; } }

 void OnCollisionEnter(Collision col){
     if(col.transform.tag == "Enemy"){

         Destroy(gameObject);
     }
     }

}

and enemy -

using UnityEngine; using System.Collections;

public class EnemyAI: $$anonymous$$onoBehaviour { public Transform target; public int moveSpeed; public int rotationSpeed;

 private Transform myTransform;

 public int damage = 25;
 public GameObject otherGameObject;


 private PlayerController playerScript;

 void Awake(){

     myTransform = transform;
 
 }
 // Use this for initialization
 void Start () {
     GameObject go = GameObject.FindGameObjectWithTag("Player");
     target = go.transform;
 }
 // Update is called once per frame
 void Update () {
     Debug.DrawLine(target.position, myTransform.position, Color.cyan);
     //look at target
     
     //move towards target

     Vector3 directionTowardsPlayer = (target.position - myTransform.position).normalized;
     rigidbody.AddForce (directionTowardsPlayer * moveSpeed * Time.deltaTime);





}

}

i got this error - $$anonymous$$issingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. CameraController.LateUpdate () (at Assets/Scripts/CameraController.cs:17)

avatar image JeevanjotSingh · Nov 18, 2014 at 02:40 PM 0
Share

and i got that . OnCollisionStay is really helpful thanks for the help but what about my this error. can you please help

avatar image
0

Answer by b1gry4n · Nov 16, 2014 at 09:00 PM

on your PlayerController ...

         public float health = 100;
         
         public void TakeDamage(float amount){
         health -= amount;
             if(health <= 0.0f){
                 KillPlayer();
             }
         }
         void KillPlayer(){
         //do what you want here.
         }
     

and on your EnemyAI..

  void OnCollisionEnter(Collision col){
     if(col.transform.tag == "Player"){
         col.gameObject.SendMessage("TakeDamage", damage);
     }
 }
 


Comment
Add comment · Show 1 · 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 JeevanjotSingh · Nov 18, 2014 at 02:32 AM 0
Share

Thanks , that codes are really helpful for me . that is what i need to learn how to kill.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

How to check if an object is colliding with another? 3 Answers

Making the object collide while moving in the forward dir. (Vector3.forward) 1 Answer

What is the best way to script third person real-time action melee combat in C#? 0 Answers

Turn on Script when collide with this object? 1 Answer

Camera Colliding with Terrain 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