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 casparke12 · Jul 25, 2013 at 02:08 PM · c#fpsbarnon-statichealth

Non-static member Unity3d error

Hi,I am developing an FPS for the OUYA with FPS Kit 2.0. I have a problem I got an error when I linked an HealthBar Script from the internet linked with a playerhealth script from FPS Kit. I've tried to search on google there many answers but only code based. So can anyone help me. I am a noob on C#.

Error Assets/HealthBar.cs(39,31): error CS0120: An object reference is required to access non-static member `PlayerDamage.currentHp'

HealthBar.cs using UnityEngine; using System.Collections;

     public class HealthBar : MonoBehaviour
     {
  
     public GUIStyle progress_empty;
     public GUIStyle progress_full;
  
     //current progress
     public float barDisplay;
  
     Vector2 pos = new Vector2(10,50);
     Vector2 size = new Vector2(250,50);
  
     public Texture2D emptyTex;
     public Texture2D fullTex;
  
     void OnGUI()
     {
     //draw the background:
     GUI.BeginGroup(new Rect(pos.x, pos.y, size.x, size.y), emptyTex, progress_empty);
  
     GUI.Box(new Rect(pos.x, pos.y, size.x, size.y), fullTex, progress_full);
  
     //draw the filled-in part:
     GUI.BeginGroup(new Rect(0, 0, size.x * barDisplay, size.y));
  
     GUI.Box(new Rect(0, 0, size.x, size.y), fullTex, progress_full);
  
     GUI.EndGroup();
     GUI.EndGroup();
     }
  
     void Update()
     {
  
     //the player's health
     barDisplay = PlayerDamage.currentHp/PlayerDamage.Hp;
     }
  
     }

PlayerDamage.cs //This script is used to controll player health

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class PlayerDamage : Photon.MonoBehaviour {
     
     public GUISkin guiSKin;
     //Player health
     public float hp = 100;
     public GameObject ragdoll;
     public Texture2D bloodyScreen;
     public Texture2D hitMarkTexture;
     //Hitboxes and damage properties for each
     [System.Serializable]
     public class HitBoxes { 
         public Collider box /*{ get; set; } */;
         public float damage /*{ get; set; }*/;
         
         public HitBoxes(Collider box1, float damage1){
             box = box1;
             damage = damage1;
         } 
 
     } 
     public List<HitBoxes> hitBoxes = new List<HitBoxes>(); 
     
     [HideInInspector]
     public float currentHp;
     Quaternion camRot;
     Quaternion camDefaultRotation;
     //Fade hit mark
     float fadeValue;
     //Fade bloody screen
     float fadeValueB;
     [HideInInspector]
     public bool disableDamage = false;
         
     bool weKilled;
     
     RoomMultiplayerMenu rmm;
     
     void Awake(){
         currentHp = hp;
         if(!photonView.isMine){
             for(int i = 0; i < hitBoxes.Count;i++){
                 hitBoxes[i].box.gameObject.AddComponent<HitBox>();
                 hitBoxes[i].box.gameObject.GetComponent<HitBox>().maxDamage = hitBoxes[i].damage;
                 hitBoxes[i].box.gameObject.GetComponent<HitBox>().playerDamage = this;
                 hitBoxes[i].box.isTrigger = false;
             }
         }else{
             camDefaultRotation = Camera.main.transform.localRotation;
             for(int a = 0; a < hitBoxes.Count;a++){
                 //We dont need our hit boxes, destroy them
                 Destroy (hitBoxes[a].box.collider);
             }
             hitBoxes.Clear();
         }
         rmm = GameObject.FindWithTag("Network").GetComponent<RoomMultiplayerMenu>();
     }
     
     void Update(){
         fadeValue = Mathf.Lerp(fadeValue, 0, Time.deltaTime*2);    
         fadeValueB = Mathf.Lerp(fadeValueB, 0, Time.deltaTime*2);
         //Do camera shake effect
         if(Camera.main)
             Camera.main.transform.localRotation = Quaternion.Slerp(Camera.main.transform.localRotation, camRot, Time.deltaTime * 15); 
     }
     
     //This is a dmaage our remote player received from Hit Boxes
     public void TotalDamage(float damage){
         if(disableDamage)
             return;
         fadeValue = 2;
          photonView.RPC("DoDamage", PhotonTargets.All, damage, PhotonNetwork.player);
     }
     
     [RPC]
     //This is damage sent fro remote player instance to our local
     void DoDamage(float damage, PhotonPlayer player){
         if(weKilled)
             return;
         if(currentHp > 0 && photonView.isMine){
             this.StopAllCoroutines();
              StartCoroutine(doCameraShake());
         }
         
         fadeValueB = 2;
         currentHp -= damage;
         
         //We got killed
         if(currentHp < 0){
             //Deactivate all child meshes
             for(int i = 0; i < transform.childCount; i++){
                 transform.GetChild(i).gameObject.SetActive(false);    
             }
             
             //Spawn ragdoll
             GameObject temp;
             temp = Instantiate(ragdoll, transform.position, transform.rotation) as GameObject;
             
             if(!photonView.isMine){
                 temp.SendMessage("clearCamera");    
                 
                 if(PhotonNetwork.player == player){
                     //Send death notification message to script WhoKilledWho.cs
                     GameObject.FindWithTag("Network").SendMessage("AddKillNotification", gameObject.name, SendMessageOptions.DontRequireReceiver);
                     //Add 1 kill for our player
                     int totalKIlls = (int)PhotonNetwork.player.customProperties["Kills"];
                     totalKIlls ++;
                     Hashtable setPlayerKills = new Hashtable() {{"Kills", totalKIlls}};
                     PhotonNetwork.player.SetCustomProperties(setPlayerKills);
                     
                     //Add team score
                     int teamScore = new int();
                     if((string)PhotonNetwork.player.customProperties["TeamName"] == rmm.team_1.teamName){
                         teamScore = (int)PhotonNetwork.room.customProperties["Team1Score"];
                         teamScore ++;
                         Hashtable setTeam1Score = new Hashtable() {{"Team1Score", teamScore}};
                         PhotonNetwork.room.SetCustomProperties(setTeam1Score);
                     }
                     if((string)PhotonNetwork.player.customProperties["TeamName"] == rmm.team_2.teamName){
                         teamScore = (int)PhotonNetwork.room.customProperties["Team2Score"];
                         teamScore ++;
                         Hashtable setTeam2Score = new Hashtable() {{"Team2Score", teamScore}};
                         PhotonNetwork.room.SetCustomProperties(setTeam2Score);
                     }
                 }
             }else{
                 //print ("We got killed");
                 temp.SendMessage("RespawnAfter");
                 //We was killed, add 1 to deaths
                 int totalDeaths = (int)PhotonNetwork.player.customProperties["Deaths"];
                 totalDeaths ++;
                 Hashtable setPlayerDeaths = new Hashtable() {{"Deaths", totalDeaths}};
                 PhotonNetwork.player.SetCustomProperties(setPlayerDeaths);
                 //Destroy our player
                 StartCoroutine(DestroyPlayer(0.2f));
             }
             currentHp = 0;
             weKilled = true;
         }
     }
     
     IEnumerator DestroyPlayer(float delay){
         yield return new WaitForSeconds(delay);    
         PhotonNetwork.Destroy(gameObject);
     }
     
     //Destroy player if we change teams
     void SwapTeams(){
         photonView.RPC("DoSwapTeams", PhotonTargets.All);
     }
     
     [RPC]
     void DoSwapTeams(){
             GameObject temp;
             temp = Instantiate(ragdoll, transform.position, transform.rotation) as GameObject;    
             if(photonView.isMine){
                 temp.SendMessage("RespawnAfter");
                 StartCoroutine(DestroyPlayer(0));
             }else{
                 temp.SendMessage("clearCamera");    
             }
     }
     
     void OnGUI(){
         //Display HP for our player only
         if(photonView.isMine){
             GUI.skin = guiSKin;
             GUI.color = new Color(1,1,1,0.9f);
             GUI.depth = 10;
             GUI.color = new Color(1,1,1,fadeValueB);
             GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), bloodyScreen, ScaleMode.StretchToFill );
             GUI.color = new Color(1,1,1,0.9f);
             //Display player hp
             GUI.Box (new Rect (Screen.width - 220,Screen.height - 55,100,45), "HP | " + (int)currentHp);
         }else{
             GUI.color = new Color(1,1,1, fadeValue);
             GUI.DrawTexture(new Rect(Screen.width/2 - 13, Screen.height/2 - 13, 26, 26), hitMarkTexture, ScaleMode.StretchToFill );    
         }
     }
     
     IEnumerator doCameraShake(){
         //Change shake amount here (Currently its 10)
         camRot = Quaternion.Euler (Random.Range(-10, 10), Random.Range(-10, 10), 0);
         yield return new WaitForSeconds(0.1f);
         camRot = camDefaultRotation;
     }
 }

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
3
Best Answer

Answer by clunk47 · Jul 26, 2013 at 01:57 PM

You're trying to call a non static variable as if it were static. Use GetComponent to get what you need instead. Keep all your code the way it is except for the barDisplay declaration in HealthBar.cs.

 barDisplay = GetComponent<PlayerDamage>().currentHp/GetComponent<PlayerDamage>().hp;

Comment
Add comment · Show 2 · 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 casparke12 · Jul 26, 2013 at 07:44 PM 2
Share

Thank you very much it works!

avatar image clunk47 · Jul 26, 2013 at 07:48 PM 1
Share

Always happy to help! :D

avatar image
2

Answer by TK5005 · Jul 25, 2013 at 02:44 PM

A static variable is the same for all instances of a single class. You can access it without creating a new instance of the class that has it (such as what your doing by saying PlayerDamage.currenthp.) The problem is that the currenthp variable in PlayerDamage is not static so you must create a new PlayerDamage class or change currenthp to static (depending on how your code is organized and what is optimal). At the top of your HealthBar class, try creating an instance of the PlayerDamage class and set it equal to the PlayerDamage object you are using in your game. You should then be able to access that variable.

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 gardian06 · Jul 25, 2013 at 03:04 PM 0
Share

an example of this would be this.

 public class PlayerDamage : Photon.$$anonymous$$onoBehaviour {
     //preceding members
     public static PlayerDamage inst;
     //other members, and methods
     void Awake(){
         // other code in Awake if used
         if(inst == null){ inst = thing; }
         // other code in Awake if used
     }
     // other methods
 }

I chose Awake as this would allow for other classes to grab the instance in Start(). I know that this is a public instance, and that there are other implementations that utilize a private instance, and getters, but this example is provided for clarity.

avatar image casparke12 · Jul 25, 2013 at 03:04 PM 0
Share

Thank you for you answer! I get the part currentHp is not static but how i make the object static, must i do something lik public static or so (sorry iam really noob in it)?

avatar image TK5005 · Jul 25, 2013 at 03:47 PM 0
Share

If you create an instance of PlayerDamage you shouldn't have to make anything static. Just like gardian06 wrote, you should just have to make an instance of PlayerDamage and set it equal to the PlayerDamage object your character is using.

avatar image casparke12 · Jul 25, 2013 at 04:11 PM 0
Share

This dont work or i do something wrong

avatar image gardian06 · Jul 25, 2013 at 05:03 PM 0
Share

I made a mistake when writing the code sample, and did not actually use the static declaration. I have corrected that, and it should now work. (this is what I get from scratch writing, and not copying)

as a side note to access it from another script all you need to do is

 PlayerDamage.inst.$$anonymous$$ethodCallX(argList);

or

 PlayerDamage.inst.$$anonymous$$emberVariable;

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

19 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

Related Questions

Show GUI only when looking at an object? 1 Answer

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Health not working! 1 Answer

Health and Damage [C#] 2 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